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::gossip::NetworkGraph;
27 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
44 use bitcoin::{Transaction, TxIn, TxOut, Witness};
45 use bitcoin::OutPoint as BitcoinOutPoint;
47 use bitcoin::secp256k1::Secp256k1;
48 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use alloc::collections::BTreeSet;
55 use core::default::Default;
56 use sync::{Arc, Mutex};
58 use ln::functional_test_utils::*;
59 use ln::chan_utils::CommitmentTransaction;
62 fn test_insane_channel_opens() {
63 // Stand up a network of 2 nodes
64 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
65 let mut cfg = UserConfig::default();
66 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
67 let chanmon_cfgs = create_chanmon_cfgs(2);
68 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
70 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72 // Instantiate channel parameters where we push the maximum msats given our
74 let channel_value_sat = 31337; // same as funding satoshis
75 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78 // Have node0 initiate a channel to node1 with aforementioned parameters
79 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81 // Extract the channel open message from node0 to node1
82 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84 // Test helper that asserts we get the correct error string given a mutator
85 // that supposedly makes the channel open message insane
86 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89 assert_eq!(msg_events.len(), 1);
90 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93 &ErrorAction::SendErrorMessage { .. } => {
94 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96 _ => panic!("unexpected event!"),
98 } else { assert!(false); }
101 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103 // Test all mutations that would make the channel open message insane
104 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 });
105 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 });
107 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109 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 });
111 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113 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 });
115 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 });
117 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 fn test_funding_exceeds_no_wumbo_limit() {
124 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
126 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
127 let chanmon_cfgs = create_chanmon_cfgs(2);
128 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
131 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
133 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
134 Err(APIError::APIMisuseError { err }) => {
135 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
141 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
142 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
143 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
144 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
145 // in normal testing, we test it explicitly here.
146 let chanmon_cfgs = create_chanmon_cfgs(2);
147 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
148 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
149 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
151 // Have node0 initiate a channel to node1 with aforementioned parameters
152 let mut push_amt = 100_000_000;
153 let feerate_per_kw = 253;
154 let opt_anchors = false;
155 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
156 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
158 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();
159 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
160 if !send_from_initiator {
161 open_channel_message.channel_reserve_satoshis = 0;
162 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
164 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
166 // Extract the channel accept message from node1 to node0
167 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
168 if send_from_initiator {
169 accept_channel_message.channel_reserve_satoshis = 0;
170 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
172 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
175 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
176 chan.holder_selected_channel_reserve_satoshis = 0;
177 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
180 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
181 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
182 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
184 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
185 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
186 if send_from_initiator {
187 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
188 // Note that for outbound channels we have to consider the commitment tx fee and the
189 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
190 // well as an additional HTLC.
191 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
193 send_payment(&nodes[1], &[&nodes[0]], push_amt);
198 fn test_counterparty_no_reserve() {
199 do_test_counterparty_no_reserve(true);
200 do_test_counterparty_no_reserve(false);
204 fn test_async_inbound_update_fee() {
205 let chanmon_cfgs = create_chanmon_cfgs(2);
206 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
207 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
208 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
209 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
212 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
216 // send (1) commitment_signed -.
217 // <- update_add_htlc/commitment_signed
218 // send (2) RAA (awaiting remote revoke) -.
219 // (1) commitment_signed is delivered ->
220 // .- send (3) RAA (awaiting remote revoke)
221 // (2) RAA is delivered ->
222 // .- send (4) commitment_signed
223 // <- (3) RAA is delivered
224 // send (5) commitment_signed -.
225 // <- (4) commitment_signed is delivered
227 // (5) commitment_signed is delivered ->
229 // (6) RAA is delivered ->
231 // First nodes[0] generates an update_fee
233 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
236 nodes[0].node.timer_tick_occurred();
237 check_added_monitors!(nodes[0], 1);
239 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
240 assert_eq!(events_0.len(), 1);
241 let (update_msg, commitment_signed) = match events_0[0] { // (1)
242 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
243 (update_fee.as_ref(), commitment_signed)
245 _ => panic!("Unexpected event"),
248 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
250 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
251 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
252 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
253 check_added_monitors!(nodes[1], 1);
255 let payment_event = {
256 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
257 assert_eq!(events_1.len(), 1);
258 SendEvent::from_event(events_1.remove(0))
260 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
261 assert_eq!(payment_event.msgs.len(), 1);
263 // ...now when the messages get delivered everyone should be happy
264 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
265 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
266 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
267 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
268 check_added_monitors!(nodes[0], 1);
270 // deliver(1), generate (3):
271 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
272 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
273 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
274 check_added_monitors!(nodes[1], 1);
276 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
277 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
278 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
279 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
280 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
281 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
282 assert!(bs_update.update_fee.is_none()); // (4)
283 check_added_monitors!(nodes[1], 1);
285 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
286 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
287 assert!(as_update.update_add_htlcs.is_empty()); // (5)
288 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
289 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
290 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
291 assert!(as_update.update_fee.is_none()); // (5)
292 check_added_monitors!(nodes[0], 1);
294 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
295 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
296 // only (6) so get_event_msg's assert(len == 1) passes
297 check_added_monitors!(nodes[0], 1);
299 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
300 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
301 check_added_monitors!(nodes[1], 1);
303 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
304 check_added_monitors!(nodes[0], 1);
306 let events_2 = nodes[0].node.get_and_clear_pending_events();
307 assert_eq!(events_2.len(), 1);
309 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
310 _ => panic!("Unexpected event"),
313 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
314 check_added_monitors!(nodes[1], 1);
318 fn test_update_fee_unordered_raa() {
319 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
320 // crash in an earlier version of the update_fee patch)
321 let chanmon_cfgs = create_chanmon_cfgs(2);
322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
325 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
328 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
330 // First nodes[0] generates an update_fee
332 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
335 nodes[0].node.timer_tick_occurred();
336 check_added_monitors!(nodes[0], 1);
338 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
339 assert_eq!(events_0.len(), 1);
340 let update_msg = match events_0[0] { // (1)
341 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
344 _ => panic!("Unexpected event"),
347 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
349 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
350 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
351 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
352 check_added_monitors!(nodes[1], 1);
354 let payment_event = {
355 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
356 assert_eq!(events_1.len(), 1);
357 SendEvent::from_event(events_1.remove(0))
359 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
360 assert_eq!(payment_event.msgs.len(), 1);
362 // ...now when the messages get delivered everyone should be happy
363 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
364 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
365 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
366 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
367 check_added_monitors!(nodes[0], 1);
369 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
370 check_added_monitors!(nodes[1], 1);
372 // We can't continue, sadly, because our (1) now has a bogus signature
376 fn test_multi_flight_update_fee() {
377 let chanmon_cfgs = create_chanmon_cfgs(2);
378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
380 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
381 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
384 // update_fee/commitment_signed ->
385 // .- send (1) RAA and (2) commitment_signed
386 // update_fee (never committed) ->
388 // We have to manually generate the above update_fee, it is allowed by the protocol but we
389 // don't track which updates correspond to which revoke_and_ack responses so we're in
390 // AwaitingRAA mode and will not generate the update_fee yet.
391 // <- (1) RAA delivered
392 // (3) is generated and send (4) CS -.
393 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
394 // know the per_commitment_point to use for it.
395 // <- (2) commitment_signed delivered
397 // B should send no response here
398 // (4) commitment_signed delivered ->
399 // <- RAA/commitment_signed delivered
402 // First nodes[0] generates an update_fee
405 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406 initial_feerate = *feerate_lock;
407 *feerate_lock = initial_feerate + 20;
409 nodes[0].node.timer_tick_occurred();
410 check_added_monitors!(nodes[0], 1);
412 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
413 assert_eq!(events_0.len(), 1);
414 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
415 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
416 (update_fee.as_ref().unwrap(), commitment_signed)
418 _ => panic!("Unexpected event"),
421 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
422 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
423 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
424 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
425 check_added_monitors!(nodes[1], 1);
427 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
430 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
431 *feerate_lock = initial_feerate + 40;
433 nodes[0].node.timer_tick_occurred();
434 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
435 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
437 // Create the (3) update_fee message that nodes[0] will generate before it does...
438 let mut update_msg_2 = msgs::UpdateFee {
439 channel_id: update_msg_1.channel_id.clone(),
440 feerate_per_kw: (initial_feerate + 30) as u32,
443 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
447 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449 // Deliver (1), generating (3) and (4)
450 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
451 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
452 check_added_monitors!(nodes[0], 1);
453 assert!(as_second_update.update_add_htlcs.is_empty());
454 assert!(as_second_update.update_fulfill_htlcs.is_empty());
455 assert!(as_second_update.update_fail_htlcs.is_empty());
456 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
457 // Check that the update_fee newly generated matches what we delivered:
458 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
459 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
461 // Deliver (2) commitment_signed
462 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
463 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
464 check_added_monitors!(nodes[0], 1);
465 // No commitment_signed so get_event_msg's assert(len == 1) passes
467 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
468 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
469 check_added_monitors!(nodes[1], 1);
472 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
473 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
474 check_added_monitors!(nodes[1], 1);
476 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
477 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[0], 1);
480 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
481 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482 // No commitment_signed so get_event_msg's assert(len == 1) passes
483 check_added_monitors!(nodes[0], 1);
485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
486 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[1], 1);
490 fn do_test_sanity_on_in_flight_opens(steps: u8) {
491 // Previously, we had issues deserializing channels when we hadn't connected the first block
492 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
493 // serialization round-trips and simply do steps towards opening a channel and then drop the
496 let chanmon_cfgs = create_chanmon_cfgs(2);
497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
501 if steps & 0b1000_0000 != 0{
503 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
506 connect_block(&nodes[0], &block);
507 connect_block(&nodes[1], &block);
510 if steps & 0x0f == 0 { return; }
511 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
512 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
514 if steps & 0x0f == 1 { return; }
515 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
516 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
518 if steps & 0x0f == 2 { return; }
519 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
521 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
523 if steps & 0x0f == 3 { return; }
524 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
525 check_added_monitors!(nodes[0], 0);
526 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
528 if steps & 0x0f == 4 { return; }
529 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
531 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
532 assert_eq!(added_monitors.len(), 1);
533 assert_eq!(added_monitors[0].0, funding_output);
534 added_monitors.clear();
536 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
538 if steps & 0x0f == 5 { return; }
539 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
541 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
542 assert_eq!(added_monitors.len(), 1);
543 assert_eq!(added_monitors[0].0, funding_output);
544 added_monitors.clear();
547 let events_4 = nodes[0].node.get_and_clear_pending_events();
548 assert_eq!(events_4.len(), 0);
550 if steps & 0x0f == 6 { return; }
551 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
553 if steps & 0x0f == 7 { return; }
554 confirm_transaction_at(&nodes[0], &tx, 2);
555 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
556 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
560 fn test_sanity_on_in_flight_opens() {
561 do_test_sanity_on_in_flight_opens(0);
562 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
563 do_test_sanity_on_in_flight_opens(1);
564 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
565 do_test_sanity_on_in_flight_opens(2);
566 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
567 do_test_sanity_on_in_flight_opens(3);
568 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
569 do_test_sanity_on_in_flight_opens(4);
570 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(5);
572 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(6);
574 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(7);
576 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(8);
578 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
582 fn test_update_fee_vanilla() {
583 let chanmon_cfgs = create_chanmon_cfgs(2);
584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
590 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
593 nodes[0].node.timer_tick_occurred();
594 check_added_monitors!(nodes[0], 1);
596 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
597 assert_eq!(events_0.len(), 1);
598 let (update_msg, commitment_signed) = match events_0[0] {
599 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 } } => {
600 (update_fee.as_ref(), commitment_signed)
602 _ => panic!("Unexpected event"),
604 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
606 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
607 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
608 check_added_monitors!(nodes[1], 1);
610 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
611 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
612 check_added_monitors!(nodes[0], 1);
614 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
615 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
616 // No commitment_signed so get_event_msg's assert(len == 1) passes
617 check_added_monitors!(nodes[0], 1);
619 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
620 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
621 check_added_monitors!(nodes[1], 1);
625 fn test_update_fee_that_funder_cannot_afford() {
626 let chanmon_cfgs = create_chanmon_cfgs(2);
627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630 let channel_value = 5000;
632 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
633 let channel_id = chan.2;
634 let secp_ctx = Secp256k1::new();
635 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
637 let opt_anchors = false;
639 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
640 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
641 // calculate two different feerates here - the expected local limit as well as the expected
643 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;
644 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
646 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
647 *feerate_lock = feerate;
649 nodes[0].node.timer_tick_occurred();
650 check_added_monitors!(nodes[0], 1);
651 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
653 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
655 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
657 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
659 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
661 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
662 assert_eq!(commitment_tx.output.len(), 2);
663 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
664 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
665 actual_fee = channel_value - actual_fee;
666 assert_eq!(total_fee, actual_fee);
670 // Increment the feerate by a small constant, accounting for rounding errors
671 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
674 nodes[0].node.timer_tick_occurred();
675 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
676 check_added_monitors!(nodes[0], 0);
678 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
680 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
681 // needed to sign the new commitment tx and (2) sign the new commitment tx.
682 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
683 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
684 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
685 let chan_signer = local_chan.get_signer();
686 let pubkeys = chan_signer.pubkeys();
687 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
688 pubkeys.funding_pubkey)
690 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
691 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
692 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
693 let chan_signer = remote_chan.get_signer();
694 let pubkeys = chan_signer.pubkeys();
695 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
696 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
697 pubkeys.funding_pubkey)
700 // Assemble the set of keys we can use for signatures for our commitment_signed message.
701 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
702 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
705 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
706 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
707 let local_chan_signer = local_chan.get_signer();
708 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
709 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
710 INITIAL_COMMITMENT_NUMBER - 1,
712 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
713 opt_anchors, local_funding, remote_funding,
714 commit_tx_keys.clone(),
715 non_buffer_feerate + 4,
717 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
719 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
722 let commit_signed_msg = msgs::CommitmentSigned {
725 htlc_signatures: res.1
728 let update_fee = msgs::UpdateFee {
730 feerate_per_kw: non_buffer_feerate + 4,
733 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
735 //While producing the commitment_signed response after handling a received update_fee request the
736 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
737 //Should produce and error.
738 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
739 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
740 check_added_monitors!(nodes[1], 1);
741 check_closed_broadcast!(nodes[1], true);
742 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
746 fn test_update_fee_with_fundee_update_add_htlc() {
747 let chanmon_cfgs = create_chanmon_cfgs(2);
748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
750 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
751 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
754 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
757 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
760 nodes[0].node.timer_tick_occurred();
761 check_added_monitors!(nodes[0], 1);
763 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
764 assert_eq!(events_0.len(), 1);
765 let (update_msg, commitment_signed) = match events_0[0] {
766 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 } } => {
767 (update_fee.as_ref(), commitment_signed)
769 _ => panic!("Unexpected event"),
771 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
772 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
773 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
774 check_added_monitors!(nodes[1], 1);
776 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
778 // nothing happens since node[1] is in AwaitingRemoteRevoke
779 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
781 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
782 assert_eq!(added_monitors.len(), 0);
783 added_monitors.clear();
785 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
786 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
787 // node[1] has nothing to do
789 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791 check_added_monitors!(nodes[0], 1);
793 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
794 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
795 // No commitment_signed so get_event_msg's assert(len == 1) passes
796 check_added_monitors!(nodes[0], 1);
797 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
798 check_added_monitors!(nodes[1], 1);
799 // AwaitingRemoteRevoke ends here
801 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
803 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
804 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
805 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
806 assert_eq!(commitment_update.update_fee.is_none(), true);
808 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
809 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
810 check_added_monitors!(nodes[0], 1);
811 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
813 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
814 check_added_monitors!(nodes[1], 1);
815 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
818 check_added_monitors!(nodes[1], 1);
819 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
820 // No commitment_signed so get_event_msg's assert(len == 1) passes
822 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
823 check_added_monitors!(nodes[0], 1);
824 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
826 expect_pending_htlcs_forwardable!(nodes[0]);
828 let events = nodes[0].node.get_and_clear_pending_events();
829 assert_eq!(events.len(), 1);
831 Event::PaymentReceived { .. } => { },
832 _ => panic!("Unexpected event"),
835 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
837 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
838 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
839 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
840 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
841 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
845 fn test_update_fee() {
846 let chanmon_cfgs = create_chanmon_cfgs(2);
847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
850 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851 let channel_id = chan.2;
854 // (1) update_fee/commitment_signed ->
855 // <- (2) revoke_and_ack
856 // .- send (3) commitment_signed
857 // (4) update_fee/commitment_signed ->
858 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
859 // <- (3) commitment_signed delivered
860 // send (6) revoke_and_ack -.
861 // <- (5) deliver revoke_and_ack
862 // (6) deliver revoke_and_ack ->
863 // .- send (7) commitment_signed in response to (4)
864 // <- (7) deliver commitment_signed
867 // Create and deliver (1)...
870 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
871 feerate = *feerate_lock;
872 *feerate_lock = feerate + 20;
874 nodes[0].node.timer_tick_occurred();
875 check_added_monitors!(nodes[0], 1);
877 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
878 assert_eq!(events_0.len(), 1);
879 let (update_msg, commitment_signed) = match events_0[0] {
880 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 } } => {
881 (update_fee.as_ref(), commitment_signed)
883 _ => panic!("Unexpected event"),
885 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
887 // Generate (2) and (3):
888 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
889 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890 check_added_monitors!(nodes[1], 1);
893 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
894 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
895 check_added_monitors!(nodes[0], 1);
897 // Create and deliver (4)...
899 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
900 *feerate_lock = feerate + 30;
902 nodes[0].node.timer_tick_occurred();
903 check_added_monitors!(nodes[0], 1);
904 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
905 assert_eq!(events_0.len(), 1);
906 let (update_msg, commitment_signed) = match events_0[0] {
907 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 } } => {
908 (update_fee.as_ref(), commitment_signed)
910 _ => panic!("Unexpected event"),
913 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
914 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915 check_added_monitors!(nodes[1], 1);
917 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
918 // No commitment_signed so get_event_msg's assert(len == 1) passes
920 // Handle (3), creating (6):
921 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
922 check_added_monitors!(nodes[0], 1);
923 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
924 // No commitment_signed so get_event_msg's assert(len == 1) passes
927 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929 check_added_monitors!(nodes[0], 1);
931 // Deliver (6), creating (7):
932 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
933 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
934 assert!(commitment_update.update_add_htlcs.is_empty());
935 assert!(commitment_update.update_fulfill_htlcs.is_empty());
936 assert!(commitment_update.update_fail_htlcs.is_empty());
937 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
938 assert!(commitment_update.update_fee.is_none());
939 check_added_monitors!(nodes[1], 1);
942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
943 check_added_monitors!(nodes[0], 1);
944 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
945 // No commitment_signed so get_event_msg's assert(len == 1) passes
947 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
948 check_added_monitors!(nodes[1], 1);
949 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
951 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
952 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
953 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
954 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
955 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
959 fn fake_network_test() {
960 // Simple test which builds a network of ChannelManagers, connects them to each other, and
961 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
962 let chanmon_cfgs = create_chanmon_cfgs(4);
963 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
964 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
965 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
967 // Create some initial channels
968 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
969 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
970 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
972 // Rebalance the network a bit by relaying one payment through all the channels...
973 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
978 // Send some more payments
979 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
980 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
981 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
983 // Test failure packets
984 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
985 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
987 // Add a new channel that skips 3
988 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
991 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
992 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998 // Do some rebalance loop payments, simultaneously
999 let mut hops = Vec::with_capacity(3);
1000 hops.push(RouteHop {
1001 pubkey: nodes[2].node.get_our_node_id(),
1002 node_features: NodeFeatures::empty(),
1003 short_channel_id: chan_2.0.contents.short_channel_id,
1004 channel_features: ChannelFeatures::empty(),
1006 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1008 hops.push(RouteHop {
1009 pubkey: nodes[3].node.get_our_node_id(),
1010 node_features: NodeFeatures::empty(),
1011 short_channel_id: chan_3.0.contents.short_channel_id,
1012 channel_features: ChannelFeatures::empty(),
1014 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1016 hops.push(RouteHop {
1017 pubkey: nodes[1].node.get_our_node_id(),
1018 node_features: NodeFeatures::known(),
1019 short_channel_id: chan_4.0.contents.short_channel_id,
1020 channel_features: ChannelFeatures::known(),
1022 cltv_expiry_delta: TEST_FINAL_CLTV,
1024 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;
1025 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;
1026 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;
1028 let mut hops = Vec::with_capacity(3);
1029 hops.push(RouteHop {
1030 pubkey: nodes[3].node.get_our_node_id(),
1031 node_features: NodeFeatures::empty(),
1032 short_channel_id: chan_4.0.contents.short_channel_id,
1033 channel_features: ChannelFeatures::empty(),
1035 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1037 hops.push(RouteHop {
1038 pubkey: nodes[2].node.get_our_node_id(),
1039 node_features: NodeFeatures::empty(),
1040 short_channel_id: chan_3.0.contents.short_channel_id,
1041 channel_features: ChannelFeatures::empty(),
1043 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1045 hops.push(RouteHop {
1046 pubkey: nodes[1].node.get_our_node_id(),
1047 node_features: NodeFeatures::known(),
1048 short_channel_id: chan_2.0.contents.short_channel_id,
1049 channel_features: ChannelFeatures::known(),
1051 cltv_expiry_delta: TEST_FINAL_CLTV,
1053 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;
1054 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;
1055 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;
1057 // Claim the rebalances...
1058 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1059 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1061 // Add a duplicate new channel from 2 to 4
1062 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1064 // Send some payments across both channels
1065 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1066 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1070 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1071 let events = nodes[0].node.get_and_clear_pending_msg_events();
1072 assert_eq!(events.len(), 0);
1073 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);
1075 //TODO: Test that routes work again here as we've been notified that the channel is full
1077 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1078 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1079 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1081 // Close down the channels...
1082 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1083 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1086 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1089 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1092 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1095 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1100 fn holding_cell_htlc_counting() {
1101 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1102 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1103 // commitment dance rounds.
1104 let chanmon_cfgs = create_chanmon_cfgs(3);
1105 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1106 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1107 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1108 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1109 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1111 let mut payments = Vec::new();
1112 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1113 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1114 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1115 payments.push((payment_preimage, payment_hash));
1117 check_added_monitors!(nodes[1], 1);
1119 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1120 assert_eq!(events.len(), 1);
1121 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1122 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1124 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1125 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1127 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1129 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1130 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1131 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1135 // This should also be true if we try to forward a payment.
1136 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1138 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1139 check_added_monitors!(nodes[0], 1);
1142 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143 assert_eq!(events.len(), 1);
1144 let payment_event = SendEvent::from_event(events.pop().unwrap());
1145 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150 // fails), the second will process the resulting failure and fail the HTLC backward.
1151 expect_pending_htlcs_forwardable!(nodes[1]);
1152 expect_pending_htlcs_forwardable!(nodes[1]);
1153 check_added_monitors!(nodes[1], 1);
1155 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161 // Now forward all the pending HTLCs and claim them back
1162 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164 check_added_monitors!(nodes[2], 1);
1166 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172 check_added_monitors!(nodes[1], 1);
1173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175 for ref update in as_updates.update_add_htlcs.iter() {
1176 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179 check_added_monitors!(nodes[2], 1);
1180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181 check_added_monitors!(nodes[2], 1);
1182 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185 check_added_monitors!(nodes[1], 1);
1186 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187 check_added_monitors!(nodes[1], 1);
1188 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191 check_added_monitors!(nodes[2], 1);
1193 expect_pending_htlcs_forwardable!(nodes[2]);
1195 let events = nodes[2].node.get_and_clear_pending_events();
1196 assert_eq!(events.len(), payments.len());
1197 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199 &Event::PaymentReceived { ref payment_hash, .. } => {
1200 assert_eq!(*payment_hash, *hash);
1202 _ => panic!("Unexpected event"),
1206 for (preimage, _) in payments.drain(..) {
1207 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1214 fn duplicate_htlc_test() {
1215 // Test that we accept duplicate payment_hash HTLCs across the network and that
1216 // claiming/failing them are all separate and don't affect each other
1217 let chanmon_cfgs = create_chanmon_cfgs(6);
1218 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1224 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1225 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1226 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1227 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1229 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234 *nodes[0].network_payment_count.borrow_mut() -= 1;
1235 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244 // Test that ChannelMonitor doesn't generate 2 preimage txn
1245 // when we have 2 HTLCs with same preimage that go across a node
1246 // in opposite directions, even with the same payment secret.
1247 let chanmon_cfgs = create_chanmon_cfgs(2);
1248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1255 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1261 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263 // Provide preimage to node 0 by claiming payment
1264 nodes[0].node.claim_funds(payment_preimage);
1265 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266 check_added_monitors!(nodes[0], 1);
1268 // Broadcast node 1 commitment txn
1269 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272 let mut has_both_htlcs = 0; // check htlcs match ones committed
1273 for outp in remote_txn[0].output.iter() {
1274 if outp.value == 800_000 / 1000 {
1275 has_both_htlcs += 1;
1276 } else if outp.value == 900_000 / 1000 {
1277 has_both_htlcs += 1;
1280 assert_eq!(has_both_htlcs, 2);
1282 mine_transaction(&nodes[0], &remote_txn[0]);
1283 check_added_monitors!(nodes[0], 1);
1284 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1287 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288 assert_eq!(claim_txn.len(), 8);
1290 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1292 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1293 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1295 let bump_tx = if claim_txn[1] == claim_txn[4] {
1296 assert_eq!(claim_txn[1], claim_txn[4]);
1297 assert_eq!(claim_txn[2], claim_txn[5]);
1299 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1301 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1304 assert_eq!(claim_txn[1], claim_txn[3]);
1305 assert_eq!(claim_txn[2], claim_txn[4]);
1307 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1309 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1314 assert_eq!(claim_txn[0].input.len(), 1);
1315 assert_eq!(bump_tx.input.len(), 1);
1316 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1318 assert_eq!(claim_txn[0].input.len(), 1);
1319 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1320 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1322 assert_eq!(claim_txn[6].input.len(), 1);
1323 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1324 check_spends!(claim_txn[6], remote_txn[0]);
1325 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1327 let events = nodes[0].node.get_and_clear_pending_msg_events();
1328 assert_eq!(events.len(), 3);
1331 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1332 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1333 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1334 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1336 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, .. } } => {
1337 assert!(update_add_htlcs.is_empty());
1338 assert!(update_fail_htlcs.is_empty());
1339 assert_eq!(update_fulfill_htlcs.len(), 1);
1340 assert!(update_fail_malformed_htlcs.is_empty());
1341 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1343 _ => panic!("Unexpected event"),
1349 fn test_basic_channel_reserve() {
1350 let chanmon_cfgs = create_chanmon_cfgs(2);
1351 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1352 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1353 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1354 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1356 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1357 let channel_reserve = chan_stat.channel_reserve_msat;
1359 // The 2* and +1 are for the fee spike reserve.
1360 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1361 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1362 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1363 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1365 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1367 &APIError::ChannelUnavailable{ref err} =>
1368 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1369 _ => panic!("Unexpected error variant"),
1372 _ => panic!("Unexpected error variant"),
1374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1375 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);
1377 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1381 fn test_fee_spike_violation_fails_htlc() {
1382 let chanmon_cfgs = create_chanmon_cfgs(2);
1383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1385 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1386 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1388 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1389 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1390 let secp_ctx = Secp256k1::new();
1391 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1393 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1395 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1396 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1397 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1398 let msg = msgs::UpdateAddHTLC {
1401 amount_msat: htlc_msat,
1402 payment_hash: payment_hash,
1403 cltv_expiry: htlc_cltv,
1404 onion_routing_packet: onion_packet,
1407 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1409 // Now manually create the commitment_signed message corresponding to the update_add
1410 // nodes[0] just sent. In the code for construction of this message, "local" refers
1411 // to the sender of the message, and "remote" refers to the receiver.
1413 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1415 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1417 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1418 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1419 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1420 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1421 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1422 let chan_signer = local_chan.get_signer();
1423 // Make the signer believe we validated another commitment, so we can release the secret
1424 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1426 let pubkeys = chan_signer.pubkeys();
1427 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1428 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1429 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1430 chan_signer.pubkeys().funding_pubkey)
1432 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1433 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1434 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1435 let chan_signer = remote_chan.get_signer();
1436 let pubkeys = chan_signer.pubkeys();
1437 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1438 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1439 chan_signer.pubkeys().funding_pubkey)
1442 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1443 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1444 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1446 // Build the remote commitment transaction so we can sign it, and then later use the
1447 // signature for the commitment_signed message.
1448 let local_chan_balance = 1313;
1450 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1452 amount_msat: 3460001,
1453 cltv_expiry: htlc_cltv,
1455 transaction_output_index: Some(1),
1458 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1461 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1462 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1463 let local_chan_signer = local_chan.get_signer();
1464 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1468 local_chan.opt_anchors(), local_funding, remote_funding,
1469 commit_tx_keys.clone(),
1471 &mut vec![(accepted_htlc_info, ())],
1472 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1474 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1477 let commit_signed_msg = msgs::CommitmentSigned {
1480 htlc_signatures: res.1
1483 // Send the commitment_signed message to the nodes[1].
1484 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1485 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1487 // Send the RAA to nodes[1].
1488 let raa_msg = msgs::RevokeAndACK {
1490 per_commitment_secret: local_secret,
1491 next_per_commitment_point: next_local_point
1493 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1495 let events = nodes[1].node.get_and_clear_pending_msg_events();
1496 assert_eq!(events.len(), 1);
1497 // Make sure the HTLC failed in the way we expect.
1499 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1500 assert_eq!(update_fail_htlcs.len(), 1);
1501 update_fail_htlcs[0].clone()
1503 _ => panic!("Unexpected event"),
1505 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1506 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1508 check_added_monitors!(nodes[1], 2);
1512 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1513 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1514 // Set the fee rate for the channel very high, to the point where the fundee
1515 // sending any above-dust amount would result in a channel reserve violation.
1516 // In this test we check that we would be prevented from sending an HTLC in
1518 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523 let opt_anchors = false;
1525 let mut push_amt = 100_000_000;
1526 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1527 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1529 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1531 // Sending exactly enough to hit the reserve amount should be accepted
1532 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1533 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536 // However one more HTLC should be significantly over the reserve amount and fail.
1537 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1538 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1539 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1540 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1541 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);
1545 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1546 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1547 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1550 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1552 let opt_anchors = false;
1554 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1555 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1556 // transaction fee with 0 HTLCs (183 sats)).
1557 let mut push_amt = 100_000_000;
1558 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1559 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1560 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1562 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1563 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1564 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1567 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1568 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1569 let secp_ctx = Secp256k1::new();
1570 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1571 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1572 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1573 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1574 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1575 let msg = msgs::UpdateAddHTLC {
1577 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578 amount_msat: htlc_msat,
1579 payment_hash: payment_hash,
1580 cltv_expiry: htlc_cltv,
1581 onion_routing_packet: onion_packet,
1584 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586 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);
1587 assert_eq!(nodes[0].node.list_channels().len(), 0);
1588 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590 check_added_monitors!(nodes[0], 1);
1591 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() });
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597 // calculating our commitment transaction fee (this was previously broken).
1598 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1601 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1605 let opt_anchors = false;
1607 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609 // transaction fee with 0 HTLCs (183 sats)).
1610 let mut push_amt = 100_000_000;
1611 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1613 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1615 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619 // commitment transaction fee.
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1622 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1627 // One more than the dust amt should fail, however.
1628 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1630 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1634 fn test_chan_init_feerate_unaffordability() {
1635 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636 // channel reserve and feerate requirements.
1637 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1643 let opt_anchors = false;
1645 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1647 let mut push_amt = 100_000_000;
1648 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1652 // During open, we don't have a "counterparty channel reserve" to check against, so that
1653 // requirement only comes into play on the open_channel handling side.
1654 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1655 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657 open_channel_msg.push_msat += 1;
1658 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1660 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661 assert_eq!(msg_events.len(), 1);
1662 match msg_events[0] {
1663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1666 _ => panic!("Unexpected event"),
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673 // calculating our counterparty's commitment transaction fee (this was previously broken).
1674 let chanmon_cfgs = create_chanmon_cfgs(2);
1675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1680 let payment_amt = 46000; // Dust amount
1681 // In the previous code, these first four payments would succeed.
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702 let chanmon_cfgs = create_chanmon_cfgs(3);
1703 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1707 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1710 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1712 let feerate = get_feerate!(nodes[0], chan.2);
1713 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1715 // Add a 2* and +1 for the fee spike reserve.
1716 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717 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;
1718 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1720 // Add a pending HTLC.
1721 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722 let payment_event_1 = {
1723 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1724 check_added_monitors!(nodes[0], 1);
1726 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1727 assert_eq!(events.len(), 1);
1728 SendEvent::from_event(events.remove(0))
1730 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1732 // Attempt to trigger a channel reserve violation --> payment failure.
1733 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1734 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;
1735 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1736 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1738 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1739 let secp_ctx = Secp256k1::new();
1740 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1741 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1742 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1743 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1744 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1745 let msg = msgs::UpdateAddHTLC {
1748 amount_msat: htlc_msat + 1,
1749 payment_hash: our_payment_hash_1,
1750 cltv_expiry: htlc_cltv,
1751 onion_routing_packet: onion_packet,
1754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757 assert_eq!(nodes[1].node.list_channels().len(), 1);
1758 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760 check_added_monitors!(nodes[1], 1);
1761 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766 let chanmon_cfgs = create_chanmon_cfgs(2);
1767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1771 let channels0 = node_chanmgrs[0].list_channels();
1772 let channels1 = node_chanmgrs[1].list_channels();
1773 assert_eq!(channels0.len(), 1);
1774 assert_eq!(channels1.len(), 1);
1776 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1777 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1778 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1780 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1781 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1784 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1785 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1789 fn test_channel_reserve_holding_cell_htlcs() {
1790 let chanmon_cfgs = create_chanmon_cfgs(3);
1791 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1792 // When this test was written, the default base fee floated based on the HTLC count.
1793 // It is now fixed, so we simply set the fee to the expected value here.
1794 let mut config = test_default_channel_config();
1795 config.channel_config.forwarding_fee_base_msat = 239;
1796 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1797 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1798 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1799 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1801 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1802 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1804 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1805 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1807 macro_rules! expect_forward {
1809 let mut events = $node.node.get_and_clear_pending_msg_events();
1810 assert_eq!(events.len(), 1);
1811 check_added_monitors!($node, 1);
1812 let payment_event = SendEvent::from_event(events.remove(0));
1817 let feemsat = 239; // set above
1818 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1819 let feerate = get_feerate!(nodes[0], chan_1.2);
1820 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1822 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1824 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1826 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1827 route.paths[0].last_mut().unwrap().fee_msat += 1;
1828 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1829 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1830 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)));
1831 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1832 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);
1835 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1836 // nodes[0]'s wealth
1838 let amt_msat = recv_value_0 + total_fee_msat;
1839 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1840 // Also, ensure that each payment has enough to be over the dust limit to
1841 // ensure it'll be included in each commit tx fee calculation.
1842 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1843 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1844 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1847 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1849 let (stat01_, stat11_, stat12_, stat22_) = (
1850 get_channel_value_stat!(nodes[0], chan_1.2),
1851 get_channel_value_stat!(nodes[1], chan_1.2),
1852 get_channel_value_stat!(nodes[1], chan_2.2),
1853 get_channel_value_stat!(nodes[2], chan_2.2),
1856 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1857 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1858 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1859 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1860 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1863 // adding pending output.
1864 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1865 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1866 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1867 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1868 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1869 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1870 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1871 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1872 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1874 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1875 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1876 let amt_msat_1 = recv_value_1 + total_fee_msat;
1878 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);
1879 let payment_event_1 = {
1880 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1881 check_added_monitors!(nodes[0], 1);
1883 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1884 assert_eq!(events.len(), 1);
1885 SendEvent::from_event(events.remove(0))
1887 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1889 // channel reserve test with htlc pending output > 0
1890 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1892 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1893 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1894 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1895 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1898 // split the rest to test holding cell
1899 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1900 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1901 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1902 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1904 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1905 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);
1908 // now see if they go through on both sides
1909 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);
1910 // but this will stuck in the holding cell
1911 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1912 check_added_monitors!(nodes[0], 0);
1913 let events = nodes[0].node.get_and_clear_pending_events();
1914 assert_eq!(events.len(), 0);
1916 // test with outbound holding cell amount > 0
1918 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1919 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1920 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1921 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1922 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);
1925 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);
1926 // this will also stuck in the holding cell
1927 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1928 check_added_monitors!(nodes[0], 0);
1929 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1930 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1932 // flush the pending htlc
1933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1934 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1935 check_added_monitors!(nodes[1], 1);
1937 // the pending htlc should be promoted to committed
1938 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1939 check_added_monitors!(nodes[0], 1);
1940 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1943 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1944 // No commitment_signed so get_event_msg's assert(len == 1) passes
1945 check_added_monitors!(nodes[0], 1);
1947 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1948 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1949 check_added_monitors!(nodes[1], 1);
1951 expect_pending_htlcs_forwardable!(nodes[1]);
1953 let ref payment_event_11 = expect_forward!(nodes[1]);
1954 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1955 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1957 expect_pending_htlcs_forwardable!(nodes[2]);
1958 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1960 // flush the htlcs in the holding cell
1961 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1962 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1963 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1964 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1965 expect_pending_htlcs_forwardable!(nodes[1]);
1967 let ref payment_event_3 = expect_forward!(nodes[1]);
1968 assert_eq!(payment_event_3.msgs.len(), 2);
1969 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1970 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1972 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1973 expect_pending_htlcs_forwardable!(nodes[2]);
1975 let events = nodes[2].node.get_and_clear_pending_events();
1976 assert_eq!(events.len(), 2);
1978 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1979 assert_eq!(our_payment_hash_21, *payment_hash);
1980 assert_eq!(recv_value_21, amount_msat);
1982 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1983 assert!(payment_preimage.is_none());
1984 assert_eq!(our_payment_secret_21, *payment_secret);
1986 _ => panic!("expected PaymentPurpose::InvoicePayment")
1989 _ => panic!("Unexpected event"),
1992 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1993 assert_eq!(our_payment_hash_22, *payment_hash);
1994 assert_eq!(recv_value_22, amount_msat);
1996 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1997 assert!(payment_preimage.is_none());
1998 assert_eq!(our_payment_secret_22, *payment_secret);
2000 _ => panic!("expected PaymentPurpose::InvoicePayment")
2003 _ => panic!("Unexpected event"),
2006 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2007 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2008 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2010 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2011 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2012 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2014 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2015 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);
2016 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2017 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2018 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2020 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2021 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2025 fn channel_reserve_in_flight_removes() {
2026 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2027 // can send to its counterparty, but due to update ordering, the other side may not yet have
2028 // considered those HTLCs fully removed.
2029 // This tests that we don't count HTLCs which will not be included in the next remote
2030 // commitment transaction towards the reserve value (as it implies no commitment transaction
2031 // will be generated which violates the remote reserve value).
2032 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2034 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2035 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2036 // you only consider the value of the first HTLC, it may not),
2037 // * start routing a third HTLC from A to B,
2038 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2039 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2040 // * deliver the first fulfill from B
2041 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2043 // * deliver A's response CS and RAA.
2044 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2045 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2046 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2047 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2048 let chanmon_cfgs = create_chanmon_cfgs(2);
2049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2050 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2051 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2052 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2054 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2055 // Route the first two HTLCs.
2056 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2057 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2058 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2060 // Start routing the third HTLC (this is just used to get everyone in the right state).
2061 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2063 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2064 check_added_monitors!(nodes[0], 1);
2065 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2066 assert_eq!(events.len(), 1);
2067 SendEvent::from_event(events.remove(0))
2070 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2071 // initial fulfill/CS.
2072 nodes[1].node.claim_funds(payment_preimage_1);
2073 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2074 check_added_monitors!(nodes[1], 1);
2075 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2077 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2078 // remove the second HTLC when we send the HTLC back from B to A.
2079 nodes[1].node.claim_funds(payment_preimage_2);
2080 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2081 check_added_monitors!(nodes[1], 1);
2082 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2084 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2085 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2086 check_added_monitors!(nodes[0], 1);
2087 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2088 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2090 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2091 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2092 check_added_monitors!(nodes[1], 1);
2093 // B is already AwaitingRAA, so cant generate a CS here
2094 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2096 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2097 check_added_monitors!(nodes[1], 1);
2098 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2100 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2101 check_added_monitors!(nodes[0], 1);
2102 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105 check_added_monitors!(nodes[1], 1);
2106 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2108 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2109 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2110 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2111 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2112 // on-chain as necessary).
2113 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2114 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2115 check_added_monitors!(nodes[0], 1);
2116 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2117 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2119 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2120 check_added_monitors!(nodes[1], 1);
2121 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2123 expect_pending_htlcs_forwardable!(nodes[1]);
2124 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2126 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2127 // resolve the second HTLC from A's point of view.
2128 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2129 check_added_monitors!(nodes[0], 1);
2130 expect_payment_path_successful!(nodes[0]);
2131 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2133 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2134 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2135 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2137 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2138 check_added_monitors!(nodes[1], 1);
2139 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2140 assert_eq!(events.len(), 1);
2141 SendEvent::from_event(events.remove(0))
2144 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2145 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2146 check_added_monitors!(nodes[0], 1);
2147 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2149 // Now just resolve all the outstanding messages/HTLCs for completeness...
2151 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2152 check_added_monitors!(nodes[1], 1);
2153 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2155 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2156 check_added_monitors!(nodes[1], 1);
2158 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2159 check_added_monitors!(nodes[0], 1);
2160 expect_payment_path_successful!(nodes[0]);
2161 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2163 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2164 check_added_monitors!(nodes[1], 1);
2165 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2167 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2168 check_added_monitors!(nodes[0], 1);
2170 expect_pending_htlcs_forwardable!(nodes[0]);
2171 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2173 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2174 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2178 fn channel_monitor_network_test() {
2179 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2180 // tests that ChannelMonitor is able to recover from various states.
2181 let chanmon_cfgs = create_chanmon_cfgs(5);
2182 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2183 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2184 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2186 // Create some initial channels
2187 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2188 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2189 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2190 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2192 // Make sure all nodes are at the same starting height
2193 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2194 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2195 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2196 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2197 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2199 // Rebalance the network a bit by relaying one payment through all the channels...
2200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2201 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2202 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2203 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2205 // Simple case with no pending HTLCs:
2206 nodes[1].node.force_close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2207 check_added_monitors!(nodes[1], 1);
2208 check_closed_broadcast!(nodes[1], true);
2210 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2211 assert_eq!(node_txn.len(), 1);
2212 mine_transaction(&nodes[0], &node_txn[0]);
2213 check_added_monitors!(nodes[0], 1);
2214 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2216 check_closed_broadcast!(nodes[0], true);
2217 assert_eq!(nodes[0].node.list_channels().len(), 0);
2218 assert_eq!(nodes[1].node.list_channels().len(), 1);
2219 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2220 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2222 // One pending HTLC is discarded by the force-close:
2223 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2225 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2226 // broadcasted until we reach the timelock time).
2227 nodes[1].node.force_close_channel(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2228 check_closed_broadcast!(nodes[1], true);
2229 check_added_monitors!(nodes[1], 1);
2231 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2232 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2233 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2234 mine_transaction(&nodes[2], &node_txn[0]);
2235 check_added_monitors!(nodes[2], 1);
2236 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2238 check_closed_broadcast!(nodes[2], true);
2239 assert_eq!(nodes[1].node.list_channels().len(), 0);
2240 assert_eq!(nodes[2].node.list_channels().len(), 1);
2241 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2242 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2244 macro_rules! claim_funds {
2245 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2247 $node.node.claim_funds($preimage);
2248 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2249 check_added_monitors!($node, 1);
2251 let events = $node.node.get_and_clear_pending_msg_events();
2252 assert_eq!(events.len(), 1);
2254 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2255 assert!(update_add_htlcs.is_empty());
2256 assert!(update_fail_htlcs.is_empty());
2257 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2259 _ => panic!("Unexpected event"),
2265 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2266 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2267 nodes[2].node.force_close_channel(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2268 check_added_monitors!(nodes[2], 1);
2269 check_closed_broadcast!(nodes[2], true);
2270 let node2_commitment_txid;
2272 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2273 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2274 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2275 node2_commitment_txid = node_txn[0].txid();
2277 // Claim the payment on nodes[3], giving it knowledge of the preimage
2278 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2279 mine_transaction(&nodes[3], &node_txn[0]);
2280 check_added_monitors!(nodes[3], 1);
2281 check_preimage_claim(&nodes[3], &node_txn);
2283 check_closed_broadcast!(nodes[3], true);
2284 assert_eq!(nodes[2].node.list_channels().len(), 0);
2285 assert_eq!(nodes[3].node.list_channels().len(), 1);
2286 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2287 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2289 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2290 // confusing us in the following tests.
2291 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2293 // One pending HTLC to time out:
2294 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2295 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2298 let (close_chan_update_1, close_chan_update_2) = {
2299 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2300 let events = nodes[3].node.get_and_clear_pending_msg_events();
2301 assert_eq!(events.len(), 2);
2302 let close_chan_update_1 = match events[0] {
2303 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2306 _ => panic!("Unexpected event"),
2309 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2310 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2312 _ => panic!("Unexpected event"),
2314 check_added_monitors!(nodes[3], 1);
2316 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2318 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2319 node_txn.retain(|tx| {
2320 if tx.input[0].previous_output.txid == node2_commitment_txid {
2326 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2328 // Claim the payment on nodes[4], giving it knowledge of the preimage
2329 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2331 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2332 let events = nodes[4].node.get_and_clear_pending_msg_events();
2333 assert_eq!(events.len(), 2);
2334 let close_chan_update_2 = match events[0] {
2335 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2338 _ => panic!("Unexpected event"),
2341 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2342 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2344 _ => panic!("Unexpected event"),
2346 check_added_monitors!(nodes[4], 1);
2347 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2349 mine_transaction(&nodes[4], &node_txn[0]);
2350 check_preimage_claim(&nodes[4], &node_txn);
2351 (close_chan_update_1, close_chan_update_2)
2353 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2354 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2355 assert_eq!(nodes[3].node.list_channels().len(), 0);
2356 assert_eq!(nodes[4].node.list_channels().len(), 0);
2358 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2359 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2360 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2364 fn test_justice_tx() {
2365 // Test justice txn built on revoked HTLC-Success tx, against both sides
2366 let mut alice_config = UserConfig::default();
2367 alice_config.channel_handshake_config.announced_channel = true;
2368 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2369 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2370 let mut bob_config = UserConfig::default();
2371 bob_config.channel_handshake_config.announced_channel = true;
2372 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2373 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2374 let user_cfgs = [Some(alice_config), Some(bob_config)];
2375 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2376 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2377 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2380 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2381 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2382 // Create some new channels:
2383 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2385 // A pending HTLC which will be revoked:
2386 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2387 // Get the will-be-revoked local txn from nodes[0]
2388 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2389 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2390 assert_eq!(revoked_local_txn[0].input.len(), 1);
2391 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2392 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2393 assert_eq!(revoked_local_txn[1].input.len(), 1);
2394 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2395 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2396 // Revoke the old state
2397 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2400 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2402 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2403 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2404 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2406 check_spends!(node_txn[0], revoked_local_txn[0]);
2407 node_txn.swap_remove(0);
2408 node_txn.truncate(1);
2410 check_added_monitors!(nodes[1], 1);
2411 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2412 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2414 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2415 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2416 // Verify broadcast of revoked HTLC-timeout
2417 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2418 check_added_monitors!(nodes[0], 1);
2419 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2420 // Broadcast revoked HTLC-timeout on node 1
2421 mine_transaction(&nodes[1], &node_txn[1]);
2422 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2424 get_announce_close_broadcast_events(&nodes, 0, 1);
2426 assert_eq!(nodes[0].node.list_channels().len(), 0);
2427 assert_eq!(nodes[1].node.list_channels().len(), 0);
2429 // We test justice_tx build by A on B's revoked HTLC-Success tx
2430 // Create some new channels:
2431 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2437 // A pending HTLC which will be revoked:
2438 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2439 // Get the will-be-revoked local txn from B
2440 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2441 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2442 assert_eq!(revoked_local_txn[0].input.len(), 1);
2443 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2444 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2445 // Revoke the old state
2446 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2448 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2450 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2451 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2452 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2454 check_spends!(node_txn[0], revoked_local_txn[0]);
2455 node_txn.swap_remove(0);
2457 check_added_monitors!(nodes[0], 1);
2458 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2460 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2461 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2462 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2463 check_added_monitors!(nodes[1], 1);
2464 mine_transaction(&nodes[0], &node_txn[1]);
2465 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2466 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2468 get_announce_close_broadcast_events(&nodes, 0, 1);
2469 assert_eq!(nodes[0].node.list_channels().len(), 0);
2470 assert_eq!(nodes[1].node.list_channels().len(), 0);
2474 fn revoked_output_claim() {
2475 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2476 // transaction is broadcast by its counterparty
2477 let chanmon_cfgs = create_chanmon_cfgs(2);
2478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2480 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2481 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2482 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2483 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2484 assert_eq!(revoked_local_txn.len(), 1);
2485 // Only output is the full channel value back to nodes[0]:
2486 assert_eq!(revoked_local_txn[0].output.len(), 1);
2487 // Send a payment through, updating everyone's latest commitment txn
2488 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2490 // Inform nodes[1] that nodes[0] broadcast a stale tx
2491 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2492 check_added_monitors!(nodes[1], 1);
2493 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2494 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2495 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2497 check_spends!(node_txn[0], revoked_local_txn[0]);
2498 check_spends!(node_txn[1], chan_1.3);
2500 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2501 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2502 get_announce_close_broadcast_events(&nodes, 0, 1);
2503 check_added_monitors!(nodes[0], 1);
2504 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2508 fn claim_htlc_outputs_shared_tx() {
2509 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2510 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2511 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516 // Create some new channel:
2517 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2519 // Rebalance the network to generate htlc in the two directions
2520 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2521 // 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
2522 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2523 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2525 // Get the will-be-revoked local txn from node[0]
2526 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2527 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2528 assert_eq!(revoked_local_txn[0].input.len(), 1);
2529 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2530 assert_eq!(revoked_local_txn[1].input.len(), 1);
2531 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2532 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2533 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2535 //Revoke the old state
2536 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2539 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2540 check_added_monitors!(nodes[0], 1);
2541 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2542 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543 check_added_monitors!(nodes[1], 1);
2544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2545 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2546 expect_payment_failed!(nodes[1], payment_hash_2, true);
2548 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2549 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2551 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2552 check_spends!(node_txn[0], revoked_local_txn[0]);
2554 let mut witness_lens = BTreeSet::new();
2555 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2556 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2557 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2558 assert_eq!(witness_lens.len(), 3);
2559 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2560 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2561 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2563 // Next nodes[1] broadcasts its current local tx state:
2564 assert_eq!(node_txn[1].input.len(), 1);
2565 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2567 get_announce_close_broadcast_events(&nodes, 0, 1);
2568 assert_eq!(nodes[0].node.list_channels().len(), 0);
2569 assert_eq!(nodes[1].node.list_channels().len(), 0);
2573 fn claim_htlc_outputs_single_tx() {
2574 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2575 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2576 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2581 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2583 // Rebalance the network to generate htlc in the two directions
2584 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2585 // 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
2586 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2587 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2588 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2590 // Get the will-be-revoked local txn from node[0]
2591 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2593 //Revoke the old state
2594 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2597 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2598 check_added_monitors!(nodes[0], 1);
2599 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2600 check_added_monitors!(nodes[1], 1);
2601 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2602 let mut events = nodes[0].node.get_and_clear_pending_events();
2603 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2605 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2606 _ => panic!("Unexpected event"),
2609 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2610 expect_payment_failed!(nodes[1], payment_hash_2, true);
2612 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2613 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2615 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2616 assert_eq!(node_txn[0].input.len(), 1);
2617 check_spends!(node_txn[0], chan_1.3);
2618 assert_eq!(node_txn[1].input.len(), 1);
2619 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2620 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2621 check_spends!(node_txn[1], node_txn[0]);
2623 // Justice transactions are indices 1-2-4
2624 assert_eq!(node_txn[2].input.len(), 1);
2625 assert_eq!(node_txn[3].input.len(), 1);
2626 assert_eq!(node_txn[4].input.len(), 1);
2628 check_spends!(node_txn[2], revoked_local_txn[0]);
2629 check_spends!(node_txn[3], revoked_local_txn[0]);
2630 check_spends!(node_txn[4], revoked_local_txn[0]);
2632 let mut witness_lens = BTreeSet::new();
2633 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2634 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2635 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2636 assert_eq!(witness_lens.len(), 3);
2637 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2638 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2639 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2641 get_announce_close_broadcast_events(&nodes, 0, 1);
2642 assert_eq!(nodes[0].node.list_channels().len(), 0);
2643 assert_eq!(nodes[1].node.list_channels().len(), 0);
2647 fn test_htlc_on_chain_success() {
2648 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2649 // the preimage backward accordingly. So here we test that ChannelManager is
2650 // broadcasting the right event to other nodes in payment path.
2651 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2652 // A --------------------> B ----------------------> C (preimage)
2653 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2654 // commitment transaction was broadcast.
2655 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2657 // B should be able to claim via preimage if A then broadcasts its local tx.
2658 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2659 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2660 // PaymentSent event).
2662 let chanmon_cfgs = create_chanmon_cfgs(3);
2663 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2664 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2665 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2667 // Create some initial channels
2668 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2669 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2671 // Ensure all nodes are at the same height
2672 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2673 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2674 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2675 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2677 // Rebalance the network a bit by relaying one payment through all the channels...
2678 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2679 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2681 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2682 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2684 // Broadcast legit commitment tx from C on B's chain
2685 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2686 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2687 assert_eq!(commitment_tx.len(), 1);
2688 check_spends!(commitment_tx[0], chan_2.3);
2689 nodes[2].node.claim_funds(our_payment_preimage);
2690 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2691 nodes[2].node.claim_funds(our_payment_preimage_2);
2692 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2693 check_added_monitors!(nodes[2], 2);
2694 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2695 assert!(updates.update_add_htlcs.is_empty());
2696 assert!(updates.update_fail_htlcs.is_empty());
2697 assert!(updates.update_fail_malformed_htlcs.is_empty());
2698 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2700 mine_transaction(&nodes[2], &commitment_tx[0]);
2701 check_closed_broadcast!(nodes[2], true);
2702 check_added_monitors!(nodes[2], 1);
2703 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2704 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)
2705 assert_eq!(node_txn.len(), 5);
2706 assert_eq!(node_txn[0], node_txn[3]);
2707 assert_eq!(node_txn[1], node_txn[4]);
2708 assert_eq!(node_txn[2], commitment_tx[0]);
2709 check_spends!(node_txn[0], commitment_tx[0]);
2710 check_spends!(node_txn[1], commitment_tx[0]);
2711 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2712 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2713 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2714 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2715 assert_eq!(node_txn[0].lock_time, 0);
2716 assert_eq!(node_txn[1].lock_time, 0);
2718 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2719 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2720 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2721 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2723 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2724 assert_eq!(added_monitors.len(), 1);
2725 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2726 added_monitors.clear();
2728 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2729 assert_eq!(forwarded_events.len(), 3);
2730 match forwarded_events[0] {
2731 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2732 _ => panic!("Unexpected event"),
2734 let chan_id = Some(chan_1.2);
2735 match forwarded_events[1] {
2736 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2737 assert_eq!(fee_earned_msat, Some(1000));
2738 assert_eq!(prev_channel_id, chan_id);
2739 assert_eq!(claim_from_onchain_tx, true);
2740 assert_eq!(next_channel_id, Some(chan_2.2));
2744 match forwarded_events[2] {
2745 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2746 assert_eq!(fee_earned_msat, Some(1000));
2747 assert_eq!(prev_channel_id, chan_id);
2748 assert_eq!(claim_from_onchain_tx, true);
2749 assert_eq!(next_channel_id, Some(chan_2.2));
2753 let events = nodes[1].node.get_and_clear_pending_msg_events();
2755 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2756 assert_eq!(added_monitors.len(), 2);
2757 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2758 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2759 added_monitors.clear();
2761 assert_eq!(events.len(), 3);
2763 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2764 _ => panic!("Unexpected event"),
2767 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2768 _ => panic!("Unexpected event"),
2772 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, .. } } => {
2773 assert!(update_add_htlcs.is_empty());
2774 assert!(update_fail_htlcs.is_empty());
2775 assert_eq!(update_fulfill_htlcs.len(), 1);
2776 assert!(update_fail_malformed_htlcs.is_empty());
2777 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2779 _ => panic!("Unexpected event"),
2781 macro_rules! check_tx_local_broadcast {
2782 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2783 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2784 assert_eq!(node_txn.len(), 3);
2785 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2786 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2787 check_spends!(node_txn[1], $commitment_tx);
2788 check_spends!(node_txn[2], $commitment_tx);
2789 assert_ne!(node_txn[1].lock_time, 0);
2790 assert_ne!(node_txn[2].lock_time, 0);
2792 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2793 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2794 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2795 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2797 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2798 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2799 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2800 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2802 check_spends!(node_txn[0], $chan_tx);
2803 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2807 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2808 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2809 // timeout-claim of the output that nodes[2] just claimed via success.
2810 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2812 // Broadcast legit commitment tx from A on B's chain
2813 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2814 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2815 check_spends!(node_a_commitment_tx[0], chan_1.3);
2816 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2817 check_closed_broadcast!(nodes[1], true);
2818 check_added_monitors!(nodes[1], 1);
2819 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2820 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2821 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2822 let commitment_spend =
2823 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2824 check_spends!(node_txn[1], commitment_tx[0]);
2825 check_spends!(node_txn[2], commitment_tx[0]);
2826 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2829 check_spends!(node_txn[0], commitment_tx[0]);
2830 check_spends!(node_txn[1], commitment_tx[0]);
2831 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2835 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2836 assert_eq!(commitment_spend.input.len(), 2);
2837 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2838 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2839 assert_eq!(commitment_spend.lock_time, 0);
2840 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2841 check_spends!(node_txn[3], chan_1.3);
2842 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2843 check_spends!(node_txn[4], node_txn[3]);
2844 check_spends!(node_txn[5], node_txn[3]);
2845 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2846 // we already checked the same situation with A.
2848 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2849 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2850 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2851 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2852 check_closed_broadcast!(nodes[0], true);
2853 check_added_monitors!(nodes[0], 1);
2854 let events = nodes[0].node.get_and_clear_pending_events();
2855 assert_eq!(events.len(), 5);
2856 let mut first_claimed = false;
2857 for event in events {
2859 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2860 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2861 assert!(!first_claimed);
2862 first_claimed = true;
2864 assert_eq!(payment_preimage, our_payment_preimage_2);
2865 assert_eq!(payment_hash, payment_hash_2);
2868 Event::PaymentPathSuccessful { .. } => {},
2869 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2870 _ => panic!("Unexpected event"),
2873 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2876 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2877 // Test that in case of a unilateral close onchain, we detect the state of output and
2878 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2879 // broadcasting the right event to other nodes in payment path.
2880 // A ------------------> B ----------------------> C (timeout)
2881 // B's commitment tx C's commitment tx
2883 // B's HTLC timeout tx B's timeout tx
2885 let chanmon_cfgs = create_chanmon_cfgs(3);
2886 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2887 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2888 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2889 *nodes[0].connect_style.borrow_mut() = connect_style;
2890 *nodes[1].connect_style.borrow_mut() = connect_style;
2891 *nodes[2].connect_style.borrow_mut() = connect_style;
2893 // Create some intial channels
2894 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2895 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2897 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2898 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2899 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2901 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2903 // Broadcast legit commitment tx from C on B's chain
2904 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2905 check_spends!(commitment_tx[0], chan_2.3);
2906 nodes[2].node.fail_htlc_backwards(&payment_hash);
2907 check_added_monitors!(nodes[2], 0);
2908 expect_pending_htlcs_forwardable!(nodes[2]);
2909 check_added_monitors!(nodes[2], 1);
2911 let events = nodes[2].node.get_and_clear_pending_msg_events();
2912 assert_eq!(events.len(), 1);
2914 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, .. } } => {
2915 assert!(update_add_htlcs.is_empty());
2916 assert!(!update_fail_htlcs.is_empty());
2917 assert!(update_fulfill_htlcs.is_empty());
2918 assert!(update_fail_malformed_htlcs.is_empty());
2919 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2921 _ => panic!("Unexpected event"),
2923 mine_transaction(&nodes[2], &commitment_tx[0]);
2924 check_closed_broadcast!(nodes[2], true);
2925 check_added_monitors!(nodes[2], 1);
2926 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2927 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2928 assert_eq!(node_txn.len(), 1);
2929 check_spends!(node_txn[0], chan_2.3);
2930 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2932 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2933 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2934 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2935 mine_transaction(&nodes[1], &commitment_tx[0]);
2936 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2939 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2940 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2941 assert_eq!(node_txn[0], node_txn[3]);
2942 assert_eq!(node_txn[1], node_txn[4]);
2944 check_spends!(node_txn[2], commitment_tx[0]);
2945 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2947 check_spends!(node_txn[0], chan_2.3);
2948 check_spends!(node_txn[1], node_txn[0]);
2949 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2950 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2952 timeout_tx = node_txn[2].clone();
2956 mine_transaction(&nodes[1], &timeout_tx);
2957 check_added_monitors!(nodes[1], 1);
2958 check_closed_broadcast!(nodes[1], true);
2960 // B will rebroadcast a fee-bumped timeout transaction here.
2961 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2962 assert_eq!(node_txn.len(), 1);
2963 check_spends!(node_txn[0], commitment_tx[0]);
2966 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2968 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2969 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2970 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2971 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2972 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2973 if node_txn.len() == 1 {
2974 check_spends!(node_txn[0], chan_2.3);
2976 assert_eq!(node_txn.len(), 0);
2980 expect_pending_htlcs_forwardable!(nodes[1]);
2981 check_added_monitors!(nodes[1], 1);
2982 let events = nodes[1].node.get_and_clear_pending_msg_events();
2983 assert_eq!(events.len(), 1);
2985 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, .. } } => {
2986 assert!(update_add_htlcs.is_empty());
2987 assert!(!update_fail_htlcs.is_empty());
2988 assert!(update_fulfill_htlcs.is_empty());
2989 assert!(update_fail_malformed_htlcs.is_empty());
2990 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2992 _ => panic!("Unexpected event"),
2995 // Broadcast legit commitment tx from B on A's chain
2996 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2997 check_spends!(commitment_tx[0], chan_1.3);
2999 mine_transaction(&nodes[0], &commitment_tx[0]);
3000 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3002 check_closed_broadcast!(nodes[0], true);
3003 check_added_monitors!(nodes[0], 1);
3004 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3005 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3006 assert_eq!(node_txn.len(), 2);
3007 check_spends!(node_txn[0], chan_1.3);
3008 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3009 check_spends!(node_txn[1], commitment_tx[0]);
3010 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3014 fn test_htlc_on_chain_timeout() {
3015 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3016 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3017 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3021 fn test_simple_commitment_revoked_fail_backward() {
3022 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3023 // and fail backward accordingly.
3025 let chanmon_cfgs = create_chanmon_cfgs(3);
3026 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3027 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3028 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3030 // Create some initial channels
3031 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3032 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3034 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3035 // Get the will-be-revoked local txn from nodes[2]
3036 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3037 // Revoke the old state
3038 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3040 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3042 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3043 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3044 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3045 check_added_monitors!(nodes[1], 1);
3046 check_closed_broadcast!(nodes[1], true);
3048 expect_pending_htlcs_forwardable!(nodes[1]);
3049 check_added_monitors!(nodes[1], 1);
3050 let events = nodes[1].node.get_and_clear_pending_msg_events();
3051 assert_eq!(events.len(), 1);
3053 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, .. } } => {
3054 assert!(update_add_htlcs.is_empty());
3055 assert_eq!(update_fail_htlcs.len(), 1);
3056 assert!(update_fulfill_htlcs.is_empty());
3057 assert!(update_fail_malformed_htlcs.is_empty());
3058 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3060 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3061 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3062 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3064 _ => panic!("Unexpected event"),
3068 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3069 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3070 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3071 // commitment transaction anymore.
3072 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3073 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3074 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3075 // technically disallowed and we should probably handle it reasonably.
3076 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3077 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3079 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3080 // commitment_signed (implying it will be in the latest remote commitment transaction).
3081 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3082 // and once they revoke the previous commitment transaction (allowing us to send a new
3083 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3084 let chanmon_cfgs = create_chanmon_cfgs(3);
3085 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3086 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3087 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3089 // Create some initial channels
3090 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3091 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3093 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 });
3094 // Get the will-be-revoked local txn from nodes[2]
3095 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3096 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3097 // Revoke the old state
3098 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3100 let value = if use_dust {
3101 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3102 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3103 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3106 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3107 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3108 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3110 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3111 expect_pending_htlcs_forwardable!(nodes[2]);
3112 check_added_monitors!(nodes[2], 1);
3113 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3114 assert!(updates.update_add_htlcs.is_empty());
3115 assert!(updates.update_fulfill_htlcs.is_empty());
3116 assert!(updates.update_fail_malformed_htlcs.is_empty());
3117 assert_eq!(updates.update_fail_htlcs.len(), 1);
3118 assert!(updates.update_fee.is_none());
3119 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3120 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3121 // Drop the last RAA from 3 -> 2
3123 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3124 expect_pending_htlcs_forwardable!(nodes[2]);
3125 check_added_monitors!(nodes[2], 1);
3126 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3127 assert!(updates.update_add_htlcs.is_empty());
3128 assert!(updates.update_fulfill_htlcs.is_empty());
3129 assert!(updates.update_fail_malformed_htlcs.is_empty());
3130 assert_eq!(updates.update_fail_htlcs.len(), 1);
3131 assert!(updates.update_fee.is_none());
3132 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3133 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3134 check_added_monitors!(nodes[1], 1);
3135 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3136 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3137 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3138 check_added_monitors!(nodes[2], 1);
3140 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3141 expect_pending_htlcs_forwardable!(nodes[2]);
3142 check_added_monitors!(nodes[2], 1);
3143 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3144 assert!(updates.update_add_htlcs.is_empty());
3145 assert!(updates.update_fulfill_htlcs.is_empty());
3146 assert!(updates.update_fail_malformed_htlcs.is_empty());
3147 assert_eq!(updates.update_fail_htlcs.len(), 1);
3148 assert!(updates.update_fee.is_none());
3149 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3150 // At this point first_payment_hash has dropped out of the latest two commitment
3151 // transactions that nodes[1] is tracking...
3152 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3153 check_added_monitors!(nodes[1], 1);
3154 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3155 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3156 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3157 check_added_monitors!(nodes[2], 1);
3159 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3160 // on nodes[2]'s RAA.
3161 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3162 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3163 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3164 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3165 check_added_monitors!(nodes[1], 0);
3168 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3169 // One monitor for the new revocation preimage, no second on as we won't generate a new
3170 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3171 check_added_monitors!(nodes[1], 1);
3172 let events = nodes[1].node.get_and_clear_pending_events();
3173 assert_eq!(events.len(), 1);
3175 Event::PendingHTLCsForwardable { .. } => { },
3176 _ => panic!("Unexpected event"),
3178 // Deliberately don't process the pending fail-back so they all fail back at once after
3179 // block connection just like the !deliver_bs_raa case
3182 let mut failed_htlcs = HashSet::new();
3183 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3185 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3186 check_added_monitors!(nodes[1], 1);
3187 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3188 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3190 let events = nodes[1].node.get_and_clear_pending_events();
3191 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3193 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3194 _ => panic!("Unexepected event"),
3197 Event::PaymentPathFailed { ref payment_hash, .. } => {
3198 assert_eq!(*payment_hash, fourth_payment_hash);
3200 _ => panic!("Unexpected event"),
3202 if !deliver_bs_raa {
3204 Event::PaymentFailed { ref payment_hash, .. } => {
3205 assert_eq!(*payment_hash, fourth_payment_hash);
3207 _ => panic!("Unexpected event"),
3210 Event::PendingHTLCsForwardable { .. } => { },
3211 _ => panic!("Unexpected event"),
3214 nodes[1].node.process_pending_htlc_forwards();
3215 check_added_monitors!(nodes[1], 1);
3217 let events = nodes[1].node.get_and_clear_pending_msg_events();
3218 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3219 match events[if deliver_bs_raa { 1 } else { 0 }] {
3220 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3221 _ => panic!("Unexpected event"),
3223 match events[if deliver_bs_raa { 2 } else { 1 }] {
3224 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3225 assert_eq!(channel_id, chan_2.2);
3226 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3228 _ => panic!("Unexpected event"),
3232 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3233 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3234 assert_eq!(update_add_htlcs.len(), 1);
3235 assert!(update_fulfill_htlcs.is_empty());
3236 assert!(update_fail_htlcs.is_empty());
3237 assert!(update_fail_malformed_htlcs.is_empty());
3239 _ => panic!("Unexpected event"),
3242 match events[if deliver_bs_raa { 3 } else { 2 }] {
3243 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3244 assert!(update_add_htlcs.is_empty());
3245 assert_eq!(update_fail_htlcs.len(), 3);
3246 assert!(update_fulfill_htlcs.is_empty());
3247 assert!(update_fail_malformed_htlcs.is_empty());
3248 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3250 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3251 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3252 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3254 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3256 let events = nodes[0].node.get_and_clear_pending_events();
3257 assert_eq!(events.len(), 3);
3259 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3260 assert!(failed_htlcs.insert(payment_hash.0));
3261 // If we delivered B's RAA we got an unknown preimage error, not something
3262 // that we should update our routing table for.
3263 if !deliver_bs_raa {
3264 assert!(network_update.is_some());
3267 _ => panic!("Unexpected event"),
3270 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3271 assert!(failed_htlcs.insert(payment_hash.0));
3272 assert!(network_update.is_some());
3274 _ => panic!("Unexpected event"),
3277 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3278 assert!(failed_htlcs.insert(payment_hash.0));
3279 assert!(network_update.is_some());
3281 _ => panic!("Unexpected event"),
3284 _ => panic!("Unexpected event"),
3287 assert!(failed_htlcs.contains(&first_payment_hash.0));
3288 assert!(failed_htlcs.contains(&second_payment_hash.0));
3289 assert!(failed_htlcs.contains(&third_payment_hash.0));
3293 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3294 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3295 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3296 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3297 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3301 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3302 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3303 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3304 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3305 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3309 fn fail_backward_pending_htlc_upon_channel_failure() {
3310 let chanmon_cfgs = create_chanmon_cfgs(2);
3311 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3312 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3313 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3314 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3316 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3318 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3319 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3320 check_added_monitors!(nodes[0], 1);
3322 let payment_event = {
3323 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3324 assert_eq!(events.len(), 1);
3325 SendEvent::from_event(events.remove(0))
3327 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3328 assert_eq!(payment_event.msgs.len(), 1);
3331 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3332 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3334 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3335 check_added_monitors!(nodes[0], 0);
3337 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3340 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3342 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3344 let secp_ctx = Secp256k1::new();
3345 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3346 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3347 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3348 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3349 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3351 // Send a 0-msat update_add_htlc to fail the channel.
3352 let update_add_htlc = msgs::UpdateAddHTLC {
3358 onion_routing_packet,
3360 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3362 let events = nodes[0].node.get_and_clear_pending_events();
3363 assert_eq!(events.len(), 2);
3364 // Check that Alice fails backward the pending HTLC from the second payment.
3366 Event::PaymentPathFailed { payment_hash, .. } => {
3367 assert_eq!(payment_hash, failed_payment_hash);
3369 _ => panic!("Unexpected event"),
3372 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3373 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3375 _ => panic!("Unexpected event {:?}", events[1]),
3377 check_closed_broadcast!(nodes[0], true);
3378 check_added_monitors!(nodes[0], 1);
3382 fn test_htlc_ignore_latest_remote_commitment() {
3383 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3384 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3385 let chanmon_cfgs = create_chanmon_cfgs(2);
3386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3389 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3391 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3392 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3393 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3394 check_closed_broadcast!(nodes[0], true);
3395 check_added_monitors!(nodes[0], 1);
3396 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3398 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3399 assert_eq!(node_txn.len(), 3);
3400 assert_eq!(node_txn[0], node_txn[1]);
3402 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3403 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3404 check_closed_broadcast!(nodes[1], true);
3405 check_added_monitors!(nodes[1], 1);
3406 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3408 // Duplicate the connect_block call since this may happen due to other listeners
3409 // registering new transactions
3410 header.prev_blockhash = header.block_hash();
3411 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3415 fn test_force_close_fail_back() {
3416 // Check which HTLCs are failed-backwards on channel force-closure
3417 let chanmon_cfgs = create_chanmon_cfgs(3);
3418 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3419 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3420 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3421 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3422 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3424 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3426 let mut payment_event = {
3427 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3428 check_added_monitors!(nodes[0], 1);
3430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3431 assert_eq!(events.len(), 1);
3432 SendEvent::from_event(events.remove(0))
3435 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3436 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3438 expect_pending_htlcs_forwardable!(nodes[1]);
3440 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3441 assert_eq!(events_2.len(), 1);
3442 payment_event = SendEvent::from_event(events_2.remove(0));
3443 assert_eq!(payment_event.msgs.len(), 1);
3445 check_added_monitors!(nodes[1], 1);
3446 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3447 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3448 check_added_monitors!(nodes[2], 1);
3449 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3451 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3452 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3453 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3455 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3456 check_closed_broadcast!(nodes[2], true);
3457 check_added_monitors!(nodes[2], 1);
3458 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3460 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3461 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3462 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3463 // back to nodes[1] upon timeout otherwise.
3464 assert_eq!(node_txn.len(), 1);
3468 mine_transaction(&nodes[1], &tx);
3470 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3471 check_closed_broadcast!(nodes[1], true);
3472 check_added_monitors!(nodes[1], 1);
3473 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3475 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3477 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3478 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3480 mine_transaction(&nodes[2], &tx);
3481 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3482 assert_eq!(node_txn.len(), 1);
3483 assert_eq!(node_txn[0].input.len(), 1);
3484 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3485 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3486 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3488 check_spends!(node_txn[0], tx);
3492 fn test_dup_events_on_peer_disconnect() {
3493 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3494 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3495 // as we used to generate the event immediately upon receipt of the payment preimage in the
3496 // update_fulfill_htlc message.
3498 let chanmon_cfgs = create_chanmon_cfgs(2);
3499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3502 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3504 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3506 nodes[1].node.claim_funds(payment_preimage);
3507 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3508 check_added_monitors!(nodes[1], 1);
3509 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3510 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3511 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3513 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3514 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3516 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3517 expect_payment_path_successful!(nodes[0]);
3521 fn test_peer_disconnected_before_funding_broadcasted() {
3522 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3523 // before the funding transaction has been broadcasted.
3524 let chanmon_cfgs = create_chanmon_cfgs(2);
3525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3529 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3530 // broadcasted, even though it's created by `nodes[0]`.
3531 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3532 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3533 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3534 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3535 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3537 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3538 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3540 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3542 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3543 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3545 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3546 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3549 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3552 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3553 // disconnected before the funding transaction was broadcasted.
3554 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3557 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3558 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3562 fn test_simple_peer_disconnect() {
3563 // Test that we can reconnect when there are no lost messages
3564 let chanmon_cfgs = create_chanmon_cfgs(3);
3565 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3566 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3567 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3568 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3569 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3577 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3578 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3585 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3593 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3595 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3597 let events = nodes[0].node.get_and_clear_pending_events();
3598 assert_eq!(events.len(), 3);
3600 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3601 assert_eq!(payment_preimage, payment_preimage_3);
3602 assert_eq!(payment_hash, payment_hash_3);
3604 _ => panic!("Unexpected event"),
3607 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3608 assert_eq!(payment_hash, payment_hash_5);
3609 assert!(rejected_by_dest);
3611 _ => panic!("Unexpected event"),
3614 Event::PaymentPathSuccessful { .. } => {},
3615 _ => panic!("Unexpected event"),
3619 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3620 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3623 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3624 // Test that we can reconnect when in-flight HTLC updates get dropped
3625 let chanmon_cfgs = create_chanmon_cfgs(2);
3626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630 let mut as_channel_ready = None;
3631 if messages_delivered == 0 {
3632 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3633 as_channel_ready = Some(channel_ready);
3634 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3635 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3636 // it before the channel_reestablish message.
3638 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3641 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3643 let payment_event = {
3644 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3645 check_added_monitors!(nodes[0], 1);
3647 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3648 assert_eq!(events.len(), 1);
3649 SendEvent::from_event(events.remove(0))
3651 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3653 if messages_delivered < 2 {
3654 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3656 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3657 if messages_delivered >= 3 {
3658 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3659 check_added_monitors!(nodes[1], 1);
3660 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3662 if messages_delivered >= 4 {
3663 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3665 check_added_monitors!(nodes[0], 1);
3667 if messages_delivered >= 5 {
3668 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3669 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3670 // No commitment_signed so get_event_msg's assert(len == 1) passes
3671 check_added_monitors!(nodes[0], 1);
3673 if messages_delivered >= 6 {
3674 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3675 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3676 check_added_monitors!(nodes[1], 1);
3683 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3684 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3685 if messages_delivered < 3 {
3686 if simulate_broken_lnd {
3687 // lnd has a long-standing bug where they send a channel_ready prior to a
3688 // channel_reestablish if you reconnect prior to channel_ready time.
3690 // Here we simulate that behavior, delivering a channel_ready immediately on
3691 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3692 // in `reconnect_nodes` but we currently don't fail based on that.
3694 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3695 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3697 // Even if the channel_ready messages get exchanged, as long as nothing further was
3698 // received on either side, both sides will need to resend them.
3699 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700 } else if messages_delivered == 3 {
3701 // nodes[0] still wants its RAA + commitment_signed
3702 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3703 } else if messages_delivered == 4 {
3704 // nodes[0] still wants its commitment_signed
3705 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3706 } else if messages_delivered == 5 {
3707 // nodes[1] still wants its final RAA
3708 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3709 } else if messages_delivered == 6 {
3710 // Everything was delivered...
3711 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714 let events_1 = nodes[1].node.get_and_clear_pending_events();
3715 assert_eq!(events_1.len(), 1);
3717 Event::PendingHTLCsForwardable { .. } => { },
3718 _ => panic!("Unexpected event"),
3721 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3722 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3723 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725 nodes[1].node.process_pending_htlc_forwards();
3727 let events_2 = nodes[1].node.get_and_clear_pending_events();
3728 assert_eq!(events_2.len(), 1);
3730 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3731 assert_eq!(payment_hash_1, *payment_hash);
3732 assert_eq!(amount_msat, 1_000_000);
3734 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3735 assert!(payment_preimage.is_none());
3736 assert_eq!(payment_secret_1, *payment_secret);
3738 _ => panic!("expected PaymentPurpose::InvoicePayment")
3741 _ => panic!("Unexpected event"),
3744 nodes[1].node.claim_funds(payment_preimage_1);
3745 check_added_monitors!(nodes[1], 1);
3746 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3748 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3749 assert_eq!(events_3.len(), 1);
3750 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3751 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3752 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3753 assert!(updates.update_add_htlcs.is_empty());
3754 assert!(updates.update_fail_htlcs.is_empty());
3755 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3756 assert!(updates.update_fail_malformed_htlcs.is_empty());
3757 assert!(updates.update_fee.is_none());
3758 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3760 _ => panic!("Unexpected event"),
3763 if messages_delivered >= 1 {
3764 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3766 let events_4 = nodes[0].node.get_and_clear_pending_events();
3767 assert_eq!(events_4.len(), 1);
3769 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3770 assert_eq!(payment_preimage_1, *payment_preimage);
3771 assert_eq!(payment_hash_1, *payment_hash);
3773 _ => panic!("Unexpected event"),
3776 if messages_delivered >= 2 {
3777 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3778 check_added_monitors!(nodes[0], 1);
3779 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3781 if messages_delivered >= 3 {
3782 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3783 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3784 check_added_monitors!(nodes[1], 1);
3786 if messages_delivered >= 4 {
3787 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3788 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3789 // No commitment_signed so get_event_msg's assert(len == 1) passes
3790 check_added_monitors!(nodes[1], 1);
3792 if messages_delivered >= 5 {
3793 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3794 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3795 check_added_monitors!(nodes[0], 1);
3802 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3803 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3804 if messages_delivered < 2 {
3805 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3806 if messages_delivered < 1 {
3807 expect_payment_sent!(nodes[0], payment_preimage_1);
3809 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3811 } else if messages_delivered == 2 {
3812 // nodes[0] still wants its RAA + commitment_signed
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3814 } else if messages_delivered == 3 {
3815 // nodes[0] still wants its commitment_signed
3816 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3817 } else if messages_delivered == 4 {
3818 // nodes[1] still wants its final RAA
3819 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3820 } else if messages_delivered == 5 {
3821 // Everything was delivered...
3822 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3825 if messages_delivered == 1 || messages_delivered == 2 {
3826 expect_payment_path_successful!(nodes[0]);
3829 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3830 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3831 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3833 if messages_delivered > 2 {
3834 expect_payment_path_successful!(nodes[0]);
3837 // Channel should still work fine...
3838 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3839 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3840 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3844 fn test_drop_messages_peer_disconnect_a() {
3845 do_test_drop_messages_peer_disconnect(0, true);
3846 do_test_drop_messages_peer_disconnect(0, false);
3847 do_test_drop_messages_peer_disconnect(1, false);
3848 do_test_drop_messages_peer_disconnect(2, false);
3852 fn test_drop_messages_peer_disconnect_b() {
3853 do_test_drop_messages_peer_disconnect(3, false);
3854 do_test_drop_messages_peer_disconnect(4, false);
3855 do_test_drop_messages_peer_disconnect(5, false);
3856 do_test_drop_messages_peer_disconnect(6, false);
3860 fn test_funding_peer_disconnect() {
3861 // Test that we can lock in our funding tx while disconnected
3862 let chanmon_cfgs = create_chanmon_cfgs(2);
3863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3865 let persister: test_utils::TestPersister;
3866 let new_chain_monitor: test_utils::TestChainMonitor;
3867 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3868 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3869 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3871 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3872 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3874 confirm_transaction(&nodes[0], &tx);
3875 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3876 assert!(events_1.is_empty());
3878 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3880 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3881 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3883 confirm_transaction(&nodes[1], &tx);
3884 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3885 assert!(events_2.is_empty());
3887 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3888 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3889 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3890 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3892 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3893 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3894 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3895 assert_eq!(events_3.len(), 1);
3896 let as_channel_ready = match events_3[0] {
3897 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3898 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3901 _ => panic!("Unexpected event {:?}", events_3[0]),
3904 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3905 // announcement_signatures as well as channel_update.
3906 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3907 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3908 assert_eq!(events_4.len(), 3);
3910 let bs_channel_ready = match events_4[0] {
3911 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3912 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3913 chan_id = msg.channel_id;
3916 _ => panic!("Unexpected event {:?}", events_4[0]),
3918 let bs_announcement_sigs = match events_4[1] {
3919 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3920 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3923 _ => panic!("Unexpected event {:?}", events_4[1]),
3926 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3927 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3929 _ => panic!("Unexpected event {:?}", events_4[2]),
3932 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3933 // generates a duplicative private channel_update
3934 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3935 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3936 assert_eq!(events_5.len(), 1);
3938 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3939 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3941 _ => panic!("Unexpected event {:?}", events_5[0]),
3944 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3945 // announcement_signatures.
3946 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3947 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3948 assert_eq!(events_6.len(), 1);
3949 let as_announcement_sigs = match events_6[0] {
3950 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3951 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3954 _ => panic!("Unexpected event {:?}", events_6[0]),
3957 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3958 // broadcast the channel announcement globally, as well as re-send its (now-public)
3960 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3961 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3962 assert_eq!(events_7.len(), 1);
3963 let (chan_announcement, as_update) = match events_7[0] {
3964 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3965 (msg.clone(), update_msg.clone())
3967 _ => panic!("Unexpected event {:?}", events_7[0]),
3970 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3971 // same channel_announcement.
3972 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3973 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3974 assert_eq!(events_8.len(), 1);
3975 let bs_update = match events_8[0] {
3976 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3977 assert_eq!(*msg, chan_announcement);
3980 _ => panic!("Unexpected event {:?}", events_8[0]),
3983 // Provide the channel announcement and public updates to the network graph
3984 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3985 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3986 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3988 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3989 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3990 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3992 // Check that after deserialization and reconnection we can still generate an identical
3993 // channel_announcement from the cached signatures.
3994 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3996 let nodes_0_serialized = nodes[0].node.encode();
3997 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3998 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4000 persister = test_utils::TestPersister::new();
4001 let keys_manager = &chanmon_cfgs[0].keys_manager;
4002 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);
4003 nodes[0].chain_monitor = &new_chain_monitor;
4004 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4005 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4006 &mut chan_0_monitor_read, keys_manager).unwrap();
4007 assert!(chan_0_monitor_read.is_empty());
4009 let mut nodes_0_read = &nodes_0_serialized[..];
4010 let (_, nodes_0_deserialized_tmp) = {
4011 let mut channel_monitors = HashMap::new();
4012 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4013 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4014 default_config: UserConfig::default(),
4016 fee_estimator: node_cfgs[0].fee_estimator,
4017 chain_monitor: nodes[0].chain_monitor,
4018 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4019 logger: nodes[0].logger,
4023 nodes_0_deserialized = nodes_0_deserialized_tmp;
4024 assert!(nodes_0_read.is_empty());
4026 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4027 nodes[0].node = &nodes_0_deserialized;
4028 check_added_monitors!(nodes[0], 1);
4030 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4032 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4033 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4034 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4035 let mut found_announcement = false;
4036 for event in msgs.iter() {
4038 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4039 if *msg == chan_announcement { found_announcement = true; }
4041 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4042 _ => panic!("Unexpected event"),
4045 assert!(found_announcement);
4049 fn test_channel_ready_without_best_block_updated() {
4050 // Previously, if we were offline when a funding transaction was locked in, and then we came
4051 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4052 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4053 // channel_ready immediately instead.
4054 let chanmon_cfgs = create_chanmon_cfgs(2);
4055 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4056 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4057 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4058 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4060 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4062 let conf_height = nodes[0].best_block_info().1 + 1;
4063 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4064 let block_txn = [funding_tx];
4065 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4066 let conf_block_header = nodes[0].get_block_header(conf_height);
4067 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4069 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4070 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4071 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4075 fn test_drop_messages_peer_disconnect_dual_htlc() {
4076 // Test that we can handle reconnecting when both sides of a channel have pending
4077 // commitment_updates when we disconnect.
4078 let chanmon_cfgs = create_chanmon_cfgs(2);
4079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4081 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4082 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4084 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4086 // Now try to send a second payment which will fail to send
4087 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4088 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4089 check_added_monitors!(nodes[0], 1);
4091 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4092 assert_eq!(events_1.len(), 1);
4094 MessageSendEvent::UpdateHTLCs { .. } => {},
4095 _ => panic!("Unexpected event"),
4098 nodes[1].node.claim_funds(payment_preimage_1);
4099 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4100 check_added_monitors!(nodes[1], 1);
4102 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4103 assert_eq!(events_2.len(), 1);
4105 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
4106 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4107 assert!(update_add_htlcs.is_empty());
4108 assert_eq!(update_fulfill_htlcs.len(), 1);
4109 assert!(update_fail_htlcs.is_empty());
4110 assert!(update_fail_malformed_htlcs.is_empty());
4111 assert!(update_fee.is_none());
4113 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4114 let events_3 = nodes[0].node.get_and_clear_pending_events();
4115 assert_eq!(events_3.len(), 1);
4117 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4118 assert_eq!(*payment_preimage, payment_preimage_1);
4119 assert_eq!(*payment_hash, payment_hash_1);
4121 _ => panic!("Unexpected event"),
4124 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4125 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4126 // No commitment_signed so get_event_msg's assert(len == 1) passes
4127 check_added_monitors!(nodes[0], 1);
4129 _ => panic!("Unexpected event"),
4132 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4133 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4135 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4136 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4137 assert_eq!(reestablish_1.len(), 1);
4138 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4139 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4140 assert_eq!(reestablish_2.len(), 1);
4142 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4143 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4144 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4145 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4147 assert!(as_resp.0.is_none());
4148 assert!(bs_resp.0.is_none());
4150 assert!(bs_resp.1.is_none());
4151 assert!(bs_resp.2.is_none());
4153 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4155 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4156 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4157 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4158 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4159 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4160 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4161 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4162 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4163 // No commitment_signed so get_event_msg's assert(len == 1) passes
4164 check_added_monitors!(nodes[1], 1);
4166 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4167 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4168 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4169 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4170 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4171 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4172 assert!(bs_second_commitment_signed.update_fee.is_none());
4173 check_added_monitors!(nodes[1], 1);
4175 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4176 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4177 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4178 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4179 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4180 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4181 assert!(as_commitment_signed.update_fee.is_none());
4182 check_added_monitors!(nodes[0], 1);
4184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4185 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4186 // No commitment_signed so get_event_msg's assert(len == 1) passes
4187 check_added_monitors!(nodes[0], 1);
4189 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4190 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4191 // No commitment_signed so get_event_msg's assert(len == 1) passes
4192 check_added_monitors!(nodes[1], 1);
4194 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4195 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4196 check_added_monitors!(nodes[1], 1);
4198 expect_pending_htlcs_forwardable!(nodes[1]);
4200 let events_5 = nodes[1].node.get_and_clear_pending_events();
4201 assert_eq!(events_5.len(), 1);
4203 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4204 assert_eq!(payment_hash_2, *payment_hash);
4206 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4207 assert!(payment_preimage.is_none());
4208 assert_eq!(payment_secret_2, *payment_secret);
4210 _ => panic!("expected PaymentPurpose::InvoicePayment")
4213 _ => panic!("Unexpected event"),
4216 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4217 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4218 check_added_monitors!(nodes[0], 1);
4220 expect_payment_path_successful!(nodes[0]);
4221 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4224 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4225 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4226 // to avoid our counterparty failing the channel.
4227 let chanmon_cfgs = create_chanmon_cfgs(2);
4228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4230 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4232 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4234 let our_payment_hash = if send_partial_mpp {
4235 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4236 // Use the utility function send_payment_along_path to send the payment with MPP data which
4237 // indicates there are more HTLCs coming.
4238 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4239 let payment_id = PaymentId([42; 32]);
4240 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4241 check_added_monitors!(nodes[0], 1);
4242 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4243 assert_eq!(events.len(), 1);
4244 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4245 // hop should *not* yet generate any PaymentReceived event(s).
4246 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4249 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4252 let mut block = Block {
4253 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4256 connect_block(&nodes[0], &block);
4257 connect_block(&nodes[1], &block);
4258 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4259 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4260 block.header.prev_blockhash = block.block_hash();
4261 connect_block(&nodes[0], &block);
4262 connect_block(&nodes[1], &block);
4265 expect_pending_htlcs_forwardable!(nodes[1]);
4267 check_added_monitors!(nodes[1], 1);
4268 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4269 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4270 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4271 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4272 assert!(htlc_timeout_updates.update_fee.is_none());
4274 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4275 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4276 // 100_000 msat as u64, followed by the height at which we failed back above
4277 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4278 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4279 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4283 fn test_htlc_timeout() {
4284 do_test_htlc_timeout(true);
4285 do_test_htlc_timeout(false);
4288 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4289 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4290 let chanmon_cfgs = create_chanmon_cfgs(3);
4291 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4292 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4293 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4294 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4295 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4297 // Make sure all nodes are at the same starting height
4298 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4299 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4300 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4302 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4303 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4305 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4307 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4308 check_added_monitors!(nodes[1], 1);
4310 // Now attempt to route a second payment, which should be placed in the holding cell
4311 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4312 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4313 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4315 check_added_monitors!(nodes[0], 1);
4316 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4317 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4318 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4319 expect_pending_htlcs_forwardable!(nodes[1]);
4321 check_added_monitors!(nodes[1], 0);
4323 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4324 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4325 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4326 connect_blocks(&nodes[1], 1);
4329 expect_pending_htlcs_forwardable!(nodes[1]);
4330 check_added_monitors!(nodes[1], 1);
4331 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4332 assert_eq!(fail_commit.len(), 1);
4333 match fail_commit[0] {
4334 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4335 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4336 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4338 _ => unreachable!(),
4340 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4342 let events = nodes[1].node.get_and_clear_pending_events();
4343 assert_eq!(events.len(), 2);
4344 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4345 assert_eq!(*payment_hash, second_payment_hash);
4346 } else { panic!("Unexpected event"); }
4347 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4348 assert_eq!(*payment_hash, second_payment_hash);
4349 } else { panic!("Unexpected event"); }
4354 fn test_holding_cell_htlc_add_timeouts() {
4355 do_test_holding_cell_htlc_add_timeouts(false);
4356 do_test_holding_cell_htlc_add_timeouts(true);
4360 fn test_no_txn_manager_serialize_deserialize() {
4361 let chanmon_cfgs = create_chanmon_cfgs(2);
4362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4364 let logger: test_utils::TestLogger;
4365 let fee_estimator: test_utils::TestFeeEstimator;
4366 let persister: test_utils::TestPersister;
4367 let new_chain_monitor: test_utils::TestChainMonitor;
4368 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4371 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4373 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4375 let nodes_0_serialized = nodes[0].node.encode();
4376 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4377 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4378 .write(&mut chan_0_monitor_serialized).unwrap();
4380 logger = test_utils::TestLogger::new();
4381 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4382 persister = test_utils::TestPersister::new();
4383 let keys_manager = &chanmon_cfgs[0].keys_manager;
4384 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4385 nodes[0].chain_monitor = &new_chain_monitor;
4386 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4387 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4388 &mut chan_0_monitor_read, keys_manager).unwrap();
4389 assert!(chan_0_monitor_read.is_empty());
4391 let mut nodes_0_read = &nodes_0_serialized[..];
4392 let config = UserConfig::default();
4393 let (_, nodes_0_deserialized_tmp) = {
4394 let mut channel_monitors = HashMap::new();
4395 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4396 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4397 default_config: config,
4399 fee_estimator: &fee_estimator,
4400 chain_monitor: nodes[0].chain_monitor,
4401 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4406 nodes_0_deserialized = nodes_0_deserialized_tmp;
4407 assert!(nodes_0_read.is_empty());
4409 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4410 nodes[0].node = &nodes_0_deserialized;
4411 assert_eq!(nodes[0].node.list_channels().len(), 1);
4412 check_added_monitors!(nodes[0], 1);
4414 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4415 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4416 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4417 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4419 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4420 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4421 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4422 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4424 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4425 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4426 for node in nodes.iter() {
4427 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4428 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4429 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4432 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4436 fn test_manager_serialize_deserialize_events() {
4437 // This test makes sure the events field in ChannelManager survives de/serialization
4438 let chanmon_cfgs = create_chanmon_cfgs(2);
4439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4441 let fee_estimator: test_utils::TestFeeEstimator;
4442 let persister: test_utils::TestPersister;
4443 let logger: test_utils::TestLogger;
4444 let new_chain_monitor: test_utils::TestChainMonitor;
4445 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4446 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4448 // Start creating a channel, but stop right before broadcasting the funding transaction
4449 let channel_value = 100000;
4450 let push_msat = 10001;
4451 let a_flags = InitFeatures::known();
4452 let b_flags = InitFeatures::known();
4453 let node_a = nodes.remove(0);
4454 let node_b = nodes.remove(0);
4455 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4456 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()));
4457 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()));
4459 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4461 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4462 check_added_monitors!(node_a, 0);
4464 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()));
4466 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4467 assert_eq!(added_monitors.len(), 1);
4468 assert_eq!(added_monitors[0].0, funding_output);
4469 added_monitors.clear();
4472 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4473 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4475 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4476 assert_eq!(added_monitors.len(), 1);
4477 assert_eq!(added_monitors[0].0, funding_output);
4478 added_monitors.clear();
4480 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4485 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4486 let nodes_0_serialized = nodes[0].node.encode();
4487 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4488 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4490 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4491 logger = test_utils::TestLogger::new();
4492 persister = test_utils::TestPersister::new();
4493 let keys_manager = &chanmon_cfgs[0].keys_manager;
4494 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4495 nodes[0].chain_monitor = &new_chain_monitor;
4496 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4497 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4498 &mut chan_0_monitor_read, keys_manager).unwrap();
4499 assert!(chan_0_monitor_read.is_empty());
4501 let mut nodes_0_read = &nodes_0_serialized[..];
4502 let config = UserConfig::default();
4503 let (_, nodes_0_deserialized_tmp) = {
4504 let mut channel_monitors = HashMap::new();
4505 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4506 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4507 default_config: config,
4509 fee_estimator: &fee_estimator,
4510 chain_monitor: nodes[0].chain_monitor,
4511 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4516 nodes_0_deserialized = nodes_0_deserialized_tmp;
4517 assert!(nodes_0_read.is_empty());
4519 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4521 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4522 nodes[0].node = &nodes_0_deserialized;
4524 // After deserializing, make sure the funding_transaction is still held by the channel manager
4525 let events_4 = nodes[0].node.get_and_clear_pending_events();
4526 assert_eq!(events_4.len(), 0);
4527 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4528 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4530 // Make sure the channel is functioning as though the de/serialization never happened
4531 assert_eq!(nodes[0].node.list_channels().len(), 1);
4532 check_added_monitors!(nodes[0], 1);
4534 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4535 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4536 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4537 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4539 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4540 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4541 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4542 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4544 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4545 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4546 for node in nodes.iter() {
4547 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4548 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4549 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4552 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4556 fn test_simple_manager_serialize_deserialize() {
4557 let chanmon_cfgs = create_chanmon_cfgs(2);
4558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4560 let logger: test_utils::TestLogger;
4561 let fee_estimator: test_utils::TestFeeEstimator;
4562 let persister: test_utils::TestPersister;
4563 let new_chain_monitor: test_utils::TestChainMonitor;
4564 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4565 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4566 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4568 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4569 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4571 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4573 let nodes_0_serialized = nodes[0].node.encode();
4574 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4575 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4577 logger = test_utils::TestLogger::new();
4578 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4579 persister = test_utils::TestPersister::new();
4580 let keys_manager = &chanmon_cfgs[0].keys_manager;
4581 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4582 nodes[0].chain_monitor = &new_chain_monitor;
4583 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4584 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4585 &mut chan_0_monitor_read, keys_manager).unwrap();
4586 assert!(chan_0_monitor_read.is_empty());
4588 let mut nodes_0_read = &nodes_0_serialized[..];
4589 let (_, nodes_0_deserialized_tmp) = {
4590 let mut channel_monitors = HashMap::new();
4591 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4592 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4593 default_config: UserConfig::default(),
4595 fee_estimator: &fee_estimator,
4596 chain_monitor: nodes[0].chain_monitor,
4597 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4602 nodes_0_deserialized = nodes_0_deserialized_tmp;
4603 assert!(nodes_0_read.is_empty());
4605 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4606 nodes[0].node = &nodes_0_deserialized;
4607 check_added_monitors!(nodes[0], 1);
4609 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4611 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4612 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4616 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4617 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4618 let chanmon_cfgs = create_chanmon_cfgs(4);
4619 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4620 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4621 let logger: test_utils::TestLogger;
4622 let fee_estimator: test_utils::TestFeeEstimator;
4623 let persister: test_utils::TestPersister;
4624 let new_chain_monitor: test_utils::TestChainMonitor;
4625 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4626 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4627 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4628 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4629 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4631 let mut node_0_stale_monitors_serialized = Vec::new();
4632 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4633 let mut writer = test_utils::TestVecWriter(Vec::new());
4634 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4635 node_0_stale_monitors_serialized.push(writer.0);
4638 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4640 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4641 let nodes_0_serialized = nodes[0].node.encode();
4643 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4644 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4645 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4646 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4648 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4650 let mut node_0_monitors_serialized = Vec::new();
4651 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4652 let mut writer = test_utils::TestVecWriter(Vec::new());
4653 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4654 node_0_monitors_serialized.push(writer.0);
4657 logger = test_utils::TestLogger::new();
4658 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4659 persister = test_utils::TestPersister::new();
4660 let keys_manager = &chanmon_cfgs[0].keys_manager;
4661 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4662 nodes[0].chain_monitor = &new_chain_monitor;
4665 let mut node_0_stale_monitors = Vec::new();
4666 for serialized in node_0_stale_monitors_serialized.iter() {
4667 let mut read = &serialized[..];
4668 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4669 assert!(read.is_empty());
4670 node_0_stale_monitors.push(monitor);
4673 let mut node_0_monitors = Vec::new();
4674 for serialized in node_0_monitors_serialized.iter() {
4675 let mut read = &serialized[..];
4676 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4677 assert!(read.is_empty());
4678 node_0_monitors.push(monitor);
4681 let mut nodes_0_read = &nodes_0_serialized[..];
4682 if let Err(msgs::DecodeError::InvalidValue) =
4683 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4684 default_config: UserConfig::default(),
4686 fee_estimator: &fee_estimator,
4687 chain_monitor: nodes[0].chain_monitor,
4688 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4690 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4692 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4695 let mut nodes_0_read = &nodes_0_serialized[..];
4696 let (_, nodes_0_deserialized_tmp) =
4697 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4698 default_config: UserConfig::default(),
4700 fee_estimator: &fee_estimator,
4701 chain_monitor: nodes[0].chain_monitor,
4702 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4704 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4706 nodes_0_deserialized = nodes_0_deserialized_tmp;
4707 assert!(nodes_0_read.is_empty());
4709 { // Channel close should result in a commitment tx
4710 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4711 assert_eq!(txn.len(), 1);
4712 check_spends!(txn[0], funding_tx);
4713 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4716 for monitor in node_0_monitors.drain(..) {
4717 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4718 check_added_monitors!(nodes[0], 1);
4720 nodes[0].node = &nodes_0_deserialized;
4721 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4723 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4724 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4725 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4726 //... and we can even still claim the payment!
4727 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4729 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4730 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4731 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4732 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4733 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4734 assert_eq!(msg_events.len(), 1);
4735 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4737 &ErrorAction::SendErrorMessage { ref msg } => {
4738 assert_eq!(msg.channel_id, channel_id);
4740 _ => panic!("Unexpected event!"),
4745 macro_rules! check_spendable_outputs {
4746 ($node: expr, $keysinterface: expr) => {
4748 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4749 let mut txn = Vec::new();
4750 let mut all_outputs = Vec::new();
4751 let secp_ctx = Secp256k1::new();
4752 for event in events.drain(..) {
4754 Event::SpendableOutputs { mut outputs } => {
4755 for outp in outputs.drain(..) {
4756 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4757 all_outputs.push(outp);
4760 _ => panic!("Unexpected event"),
4763 if all_outputs.len() > 1 {
4764 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) {
4774 fn test_claim_sizeable_push_msat() {
4775 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4776 let chanmon_cfgs = create_chanmon_cfgs(2);
4777 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4778 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4779 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4781 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4782 nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4783 check_closed_broadcast!(nodes[1], true);
4784 check_added_monitors!(nodes[1], 1);
4785 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4786 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4787 assert_eq!(node_txn.len(), 1);
4788 check_spends!(node_txn[0], chan.3);
4789 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
4791 mine_transaction(&nodes[1], &node_txn[0]);
4792 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4794 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4795 assert_eq!(spend_txn.len(), 1);
4796 assert_eq!(spend_txn[0].input.len(), 1);
4797 check_spends!(spend_txn[0], node_txn[0]);
4798 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4802 fn test_claim_on_remote_sizeable_push_msat() {
4803 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4804 // to_remote output is encumbered by a P2WPKH
4805 let chanmon_cfgs = create_chanmon_cfgs(2);
4806 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4807 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4808 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4810 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4811 nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4812 check_closed_broadcast!(nodes[0], true);
4813 check_added_monitors!(nodes[0], 1);
4814 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4816 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4817 assert_eq!(node_txn.len(), 1);
4818 check_spends!(node_txn[0], chan.3);
4819 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
4821 mine_transaction(&nodes[1], &node_txn[0]);
4822 check_closed_broadcast!(nodes[1], true);
4823 check_added_monitors!(nodes[1], 1);
4824 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4825 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4827 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4828 assert_eq!(spend_txn.len(), 1);
4829 check_spends!(spend_txn[0], node_txn[0]);
4833 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4834 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4835 // to_remote output is encumbered by a P2WPKH
4837 let chanmon_cfgs = create_chanmon_cfgs(2);
4838 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4839 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4840 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4842 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4843 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4844 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4845 assert_eq!(revoked_local_txn[0].input.len(), 1);
4846 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4848 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4849 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4850 check_closed_broadcast!(nodes[1], true);
4851 check_added_monitors!(nodes[1], 1);
4852 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4854 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4855 mine_transaction(&nodes[1], &node_txn[0]);
4856 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4858 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4859 assert_eq!(spend_txn.len(), 3);
4860 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4861 check_spends!(spend_txn[1], node_txn[0]);
4862 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4866 fn test_static_spendable_outputs_preimage_tx() {
4867 let chanmon_cfgs = create_chanmon_cfgs(2);
4868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4870 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4872 // Create some initial channels
4873 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4875 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4877 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4878 assert_eq!(commitment_tx[0].input.len(), 1);
4879 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4881 // Settle A's commitment tx on B's chain
4882 nodes[1].node.claim_funds(payment_preimage);
4883 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4884 check_added_monitors!(nodes[1], 1);
4885 mine_transaction(&nodes[1], &commitment_tx[0]);
4886 check_added_monitors!(nodes[1], 1);
4887 let events = nodes[1].node.get_and_clear_pending_msg_events();
4889 MessageSendEvent::UpdateHTLCs { .. } => {},
4890 _ => panic!("Unexpected event"),
4893 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4894 _ => panic!("Unexepected event"),
4897 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4898 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4899 assert_eq!(node_txn.len(), 3);
4900 check_spends!(node_txn[0], commitment_tx[0]);
4901 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4902 check_spends!(node_txn[1], chan_1.3);
4903 check_spends!(node_txn[2], node_txn[1]);
4905 mine_transaction(&nodes[1], &node_txn[0]);
4906 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4907 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4909 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4910 assert_eq!(spend_txn.len(), 1);
4911 check_spends!(spend_txn[0], node_txn[0]);
4915 fn test_static_spendable_outputs_timeout_tx() {
4916 let chanmon_cfgs = create_chanmon_cfgs(2);
4917 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4918 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4919 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4921 // Create some initial channels
4922 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4924 // Rebalance the network a bit by relaying one payment through all the channels ...
4925 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4927 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4929 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4930 assert_eq!(commitment_tx[0].input.len(), 1);
4931 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4933 // Settle A's commitment tx on B' chain
4934 mine_transaction(&nodes[1], &commitment_tx[0]);
4935 check_added_monitors!(nodes[1], 1);
4936 let events = nodes[1].node.get_and_clear_pending_msg_events();
4938 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4939 _ => panic!("Unexpected event"),
4941 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4943 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4944 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4945 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4946 check_spends!(node_txn[0], chan_1.3.clone());
4947 check_spends!(node_txn[1], commitment_tx[0].clone());
4948 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4950 mine_transaction(&nodes[1], &node_txn[1]);
4951 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4952 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4953 expect_payment_failed!(nodes[1], our_payment_hash, true);
4955 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4956 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4957 check_spends!(spend_txn[0], commitment_tx[0]);
4958 check_spends!(spend_txn[1], node_txn[1]);
4959 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4963 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4964 let chanmon_cfgs = create_chanmon_cfgs(2);
4965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4967 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4969 // Create some initial channels
4970 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4972 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4973 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4974 assert_eq!(revoked_local_txn[0].input.len(), 1);
4975 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4977 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4979 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4980 check_closed_broadcast!(nodes[1], true);
4981 check_added_monitors!(nodes[1], 1);
4982 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4984 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4985 assert_eq!(node_txn.len(), 2);
4986 assert_eq!(node_txn[0].input.len(), 2);
4987 check_spends!(node_txn[0], revoked_local_txn[0]);
4989 mine_transaction(&nodes[1], &node_txn[0]);
4990 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4992 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4993 assert_eq!(spend_txn.len(), 1);
4994 check_spends!(spend_txn[0], node_txn[0]);
4998 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4999 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5000 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5001 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5002 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5003 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5005 // Create some initial channels
5006 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5008 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5009 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5010 assert_eq!(revoked_local_txn[0].input.len(), 1);
5011 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5013 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5015 // A will generate HTLC-Timeout from revoked commitment tx
5016 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5017 check_closed_broadcast!(nodes[0], true);
5018 check_added_monitors!(nodes[0], 1);
5019 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5020 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5022 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5023 assert_eq!(revoked_htlc_txn.len(), 2);
5024 check_spends!(revoked_htlc_txn[0], chan_1.3);
5025 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5026 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5027 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5028 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5030 // B will generate justice tx from A's revoked commitment/HTLC tx
5031 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5032 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5033 check_closed_broadcast!(nodes[1], true);
5034 check_added_monitors!(nodes[1], 1);
5035 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5037 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5038 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5039 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5040 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5041 // transactions next...
5042 assert_eq!(node_txn[0].input.len(), 3);
5043 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5045 assert_eq!(node_txn[1].input.len(), 2);
5046 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5047 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5048 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5050 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5051 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5054 assert_eq!(node_txn[2].input.len(), 1);
5055 check_spends!(node_txn[2], chan_1.3);
5057 mine_transaction(&nodes[1], &node_txn[1]);
5058 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5060 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5061 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5062 assert_eq!(spend_txn.len(), 1);
5063 assert_eq!(spend_txn[0].input.len(), 1);
5064 check_spends!(spend_txn[0], node_txn[1]);
5068 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5069 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5070 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5071 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5072 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5073 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5075 // Create some initial channels
5076 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5078 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5079 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5080 assert_eq!(revoked_local_txn[0].input.len(), 1);
5081 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5083 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5084 assert_eq!(revoked_local_txn[0].output.len(), 2);
5086 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5088 // B will generate HTLC-Success from revoked commitment tx
5089 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5090 check_closed_broadcast!(nodes[1], true);
5091 check_added_monitors!(nodes[1], 1);
5092 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5093 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5095 assert_eq!(revoked_htlc_txn.len(), 2);
5096 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5097 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5098 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5100 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5101 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5102 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5104 // A will generate justice tx from B's revoked commitment/HTLC tx
5105 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5106 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5107 check_closed_broadcast!(nodes[0], true);
5108 check_added_monitors!(nodes[0], 1);
5109 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5111 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5112 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5114 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5115 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5116 // transactions next...
5117 assert_eq!(node_txn[0].input.len(), 2);
5118 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5119 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5120 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5122 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5123 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5126 assert_eq!(node_txn[1].input.len(), 1);
5127 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5129 check_spends!(node_txn[2], chan_1.3);
5131 mine_transaction(&nodes[0], &node_txn[1]);
5132 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5134 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5135 // didn't try to generate any new transactions.
5137 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5138 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5139 assert_eq!(spend_txn.len(), 3);
5140 assert_eq!(spend_txn[0].input.len(), 1);
5141 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5142 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5143 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5144 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5148 fn test_onchain_to_onchain_claim() {
5149 // Test that in case of channel closure, we detect the state of output and claim HTLC
5150 // on downstream peer's remote commitment tx.
5151 // First, have C claim an HTLC against its own latest commitment transaction.
5152 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5154 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5157 let chanmon_cfgs = create_chanmon_cfgs(3);
5158 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5159 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5160 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5162 // Create some initial channels
5163 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5164 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5166 // Ensure all nodes are at the same height
5167 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5168 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5169 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5170 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5172 // Rebalance the network a bit by relaying one payment through all the channels ...
5173 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5174 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5176 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5177 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5178 check_spends!(commitment_tx[0], chan_2.3);
5179 nodes[2].node.claim_funds(payment_preimage);
5180 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5181 check_added_monitors!(nodes[2], 1);
5182 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5183 assert!(updates.update_add_htlcs.is_empty());
5184 assert!(updates.update_fail_htlcs.is_empty());
5185 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5186 assert!(updates.update_fail_malformed_htlcs.is_empty());
5188 mine_transaction(&nodes[2], &commitment_tx[0]);
5189 check_closed_broadcast!(nodes[2], true);
5190 check_added_monitors!(nodes[2], 1);
5191 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5193 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5194 assert_eq!(c_txn.len(), 3);
5195 assert_eq!(c_txn[0], c_txn[2]);
5196 assert_eq!(commitment_tx[0], c_txn[1]);
5197 check_spends!(c_txn[1], chan_2.3);
5198 check_spends!(c_txn[2], c_txn[1]);
5199 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5200 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5201 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5202 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5204 // 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
5205 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5206 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5207 check_added_monitors!(nodes[1], 1);
5208 let events = nodes[1].node.get_and_clear_pending_events();
5209 assert_eq!(events.len(), 2);
5211 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5212 _ => panic!("Unexpected event"),
5215 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5216 assert_eq!(fee_earned_msat, Some(1000));
5217 assert_eq!(prev_channel_id, Some(chan_1.2));
5218 assert_eq!(claim_from_onchain_tx, true);
5219 assert_eq!(next_channel_id, Some(chan_2.2));
5221 _ => panic!("Unexpected event"),
5224 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5225 // ChannelMonitor: claim tx
5226 assert_eq!(b_txn.len(), 1);
5227 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5230 check_added_monitors!(nodes[1], 1);
5231 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5232 assert_eq!(msg_events.len(), 3);
5233 match msg_events[0] {
5234 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5235 _ => panic!("Unexpected event"),
5237 match msg_events[1] {
5238 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5239 _ => panic!("Unexpected event"),
5241 match msg_events[2] {
5242 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, .. } } => {
5243 assert!(update_add_htlcs.is_empty());
5244 assert!(update_fail_htlcs.is_empty());
5245 assert_eq!(update_fulfill_htlcs.len(), 1);
5246 assert!(update_fail_malformed_htlcs.is_empty());
5247 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5249 _ => panic!("Unexpected event"),
5251 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5252 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5253 mine_transaction(&nodes[1], &commitment_tx[0]);
5254 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5255 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5256 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5257 assert_eq!(b_txn.len(), 3);
5258 check_spends!(b_txn[1], chan_1.3);
5259 check_spends!(b_txn[2], b_txn[1]);
5260 check_spends!(b_txn[0], commitment_tx[0]);
5261 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5262 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5263 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5265 check_closed_broadcast!(nodes[1], true);
5266 check_added_monitors!(nodes[1], 1);
5270 fn test_duplicate_payment_hash_one_failure_one_success() {
5271 // Topology : A --> B --> C --> D
5272 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5273 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5274 // we forward one of the payments onwards to D.
5275 let chanmon_cfgs = create_chanmon_cfgs(4);
5276 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5277 // When this test was written, the default base fee floated based on the HTLC count.
5278 // It is now fixed, so we simply set the fee to the expected value here.
5279 let mut config = test_default_channel_config();
5280 config.channel_config.forwarding_fee_base_msat = 196;
5281 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5282 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5283 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5285 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5286 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5287 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5289 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5290 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5291 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5292 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5293 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5295 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5297 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5298 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5299 // script push size limit so that the below script length checks match
5300 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5301 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5302 .with_features(InvoiceFeatures::known());
5303 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5304 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5306 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5307 assert_eq!(commitment_txn[0].input.len(), 1);
5308 check_spends!(commitment_txn[0], chan_2.3);
5310 mine_transaction(&nodes[1], &commitment_txn[0]);
5311 check_closed_broadcast!(nodes[1], true);
5312 check_added_monitors!(nodes[1], 1);
5313 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5314 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5316 let htlc_timeout_tx;
5317 { // Extract one of the two HTLC-Timeout transaction
5318 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5319 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5320 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5321 check_spends!(node_txn[0], chan_2.3);
5323 check_spends!(node_txn[1], commitment_txn[0]);
5324 assert_eq!(node_txn[1].input.len(), 1);
5326 if node_txn.len() > 3 {
5327 check_spends!(node_txn[2], commitment_txn[0]);
5328 assert_eq!(node_txn[2].input.len(), 1);
5329 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5331 check_spends!(node_txn[3], commitment_txn[0]);
5332 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5334 check_spends!(node_txn[2], commitment_txn[0]);
5335 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5338 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5339 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5340 if node_txn.len() > 3 {
5341 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5343 htlc_timeout_tx = node_txn[1].clone();
5346 nodes[2].node.claim_funds(our_payment_preimage);
5347 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5349 mine_transaction(&nodes[2], &commitment_txn[0]);
5350 check_added_monitors!(nodes[2], 2);
5351 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5352 let events = nodes[2].node.get_and_clear_pending_msg_events();
5354 MessageSendEvent::UpdateHTLCs { .. } => {},
5355 _ => panic!("Unexpected event"),
5358 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5359 _ => panic!("Unexepected event"),
5361 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5362 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)
5363 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5364 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5365 assert_eq!(htlc_success_txn[0].input.len(), 1);
5366 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5367 assert_eq!(htlc_success_txn[1].input.len(), 1);
5368 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5369 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5370 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5371 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5372 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5373 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5375 mine_transaction(&nodes[1], &htlc_timeout_tx);
5376 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5377 expect_pending_htlcs_forwardable!(nodes[1]);
5378 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5379 assert!(htlc_updates.update_add_htlcs.is_empty());
5380 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5381 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5382 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5383 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5384 check_added_monitors!(nodes[1], 1);
5386 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5387 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5389 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5391 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5393 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5394 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5395 // and nodes[2] fee) is rounded down and then claimed in full.
5396 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5397 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5398 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5399 assert!(updates.update_add_htlcs.is_empty());
5400 assert!(updates.update_fail_htlcs.is_empty());
5401 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5402 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5403 assert!(updates.update_fail_malformed_htlcs.is_empty());
5404 check_added_monitors!(nodes[1], 1);
5406 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5407 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5409 let events = nodes[0].node.get_and_clear_pending_events();
5411 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5412 assert_eq!(*payment_preimage, our_payment_preimage);
5413 assert_eq!(*payment_hash, duplicate_payment_hash);
5415 _ => panic!("Unexpected event"),
5420 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5421 let chanmon_cfgs = create_chanmon_cfgs(2);
5422 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5423 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5424 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5426 // Create some initial channels
5427 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5429 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5430 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5431 assert_eq!(local_txn.len(), 1);
5432 assert_eq!(local_txn[0].input.len(), 1);
5433 check_spends!(local_txn[0], chan_1.3);
5435 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5436 nodes[1].node.claim_funds(payment_preimage);
5437 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5438 check_added_monitors!(nodes[1], 1);
5440 mine_transaction(&nodes[1], &local_txn[0]);
5441 check_added_monitors!(nodes[1], 1);
5442 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5443 let events = nodes[1].node.get_and_clear_pending_msg_events();
5445 MessageSendEvent::UpdateHTLCs { .. } => {},
5446 _ => panic!("Unexpected event"),
5449 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5450 _ => panic!("Unexepected event"),
5453 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5454 assert_eq!(node_txn.len(), 3);
5455 assert_eq!(node_txn[0], node_txn[2]);
5456 assert_eq!(node_txn[1], local_txn[0]);
5457 assert_eq!(node_txn[0].input.len(), 1);
5458 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5459 check_spends!(node_txn[0], local_txn[0]);
5463 mine_transaction(&nodes[1], &node_tx);
5464 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5466 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5467 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5468 assert_eq!(spend_txn.len(), 1);
5469 assert_eq!(spend_txn[0].input.len(), 1);
5470 check_spends!(spend_txn[0], node_tx);
5471 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5474 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5475 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5476 // unrevoked commitment transaction.
5477 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5478 // a remote RAA before they could be failed backwards (and combinations thereof).
5479 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5480 // use the same payment hashes.
5481 // Thus, we use a six-node network:
5486 // And test where C fails back to A/B when D announces its latest commitment transaction
5487 let chanmon_cfgs = create_chanmon_cfgs(6);
5488 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5489 // When this test was written, the default base fee floated based on the HTLC count.
5490 // It is now fixed, so we simply set the fee to the expected value here.
5491 let mut config = test_default_channel_config();
5492 config.channel_config.forwarding_fee_base_msat = 196;
5493 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5494 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5495 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5497 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5498 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5499 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5500 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5501 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5503 // Rebalance and check output sanity...
5504 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5505 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5506 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5508 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5510 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
5512 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
5513 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5515 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
5517 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
5519 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5521 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5522 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5524 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());
5526 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());
5529 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5531 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5532 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
5535 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
5537 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5538 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());
5540 // Double-check that six of the new HTLC were added
5541 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5542 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5543 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5544 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5546 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5547 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5548 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5549 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5550 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5551 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5552 check_added_monitors!(nodes[4], 0);
5553 expect_pending_htlcs_forwardable!(nodes[4]);
5554 check_added_monitors!(nodes[4], 1);
5556 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5557 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5558 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5559 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5560 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5561 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5563 // Fail 3rd below-dust and 7th above-dust HTLCs
5564 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5565 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5566 check_added_monitors!(nodes[5], 0);
5567 expect_pending_htlcs_forwardable!(nodes[5]);
5568 check_added_monitors!(nodes[5], 1);
5570 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5571 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5572 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5573 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5575 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5577 expect_pending_htlcs_forwardable!(nodes[3]);
5578 check_added_monitors!(nodes[3], 1);
5579 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5580 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5581 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5582 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5583 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5584 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5585 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5586 if deliver_last_raa {
5587 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5589 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5592 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5593 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5594 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5595 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5597 // We now broadcast the latest commitment transaction, which *should* result in failures for
5598 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5599 // the non-broadcast above-dust HTLCs.
5601 // Alternatively, we may broadcast the previous commitment transaction, which should only
5602 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5603 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5605 if announce_latest {
5606 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5608 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5610 let events = nodes[2].node.get_and_clear_pending_events();
5611 let close_event = if deliver_last_raa {
5612 assert_eq!(events.len(), 2);
5615 assert_eq!(events.len(), 1);
5619 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5620 _ => panic!("Unexpected event"),
5623 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5624 check_closed_broadcast!(nodes[2], true);
5625 if deliver_last_raa {
5626 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5628 expect_pending_htlcs_forwardable!(nodes[2]);
5630 check_added_monitors!(nodes[2], 3);
5632 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5633 assert_eq!(cs_msgs.len(), 2);
5634 let mut a_done = false;
5635 for msg in cs_msgs {
5637 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5638 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5639 // should be failed-backwards here.
5640 let target = if *node_id == nodes[0].node.get_our_node_id() {
5641 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5642 for htlc in &updates.update_fail_htlcs {
5643 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 });
5645 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5650 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5651 for htlc in &updates.update_fail_htlcs {
5652 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5654 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5655 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5658 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5659 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5660 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5661 if announce_latest {
5662 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5663 if *node_id == nodes[0].node.get_our_node_id() {
5664 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5667 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5669 _ => panic!("Unexpected event"),
5673 let as_events = nodes[0].node.get_and_clear_pending_events();
5674 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5675 let mut as_failds = HashSet::new();
5676 let mut as_updates = 0;
5677 for event in as_events.iter() {
5678 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5679 assert!(as_failds.insert(*payment_hash));
5680 if *payment_hash != payment_hash_2 {
5681 assert_eq!(*rejected_by_dest, deliver_last_raa);
5683 assert!(!rejected_by_dest);
5685 if network_update.is_some() {
5688 } else { panic!("Unexpected event"); }
5690 assert!(as_failds.contains(&payment_hash_1));
5691 assert!(as_failds.contains(&payment_hash_2));
5692 if announce_latest {
5693 assert!(as_failds.contains(&payment_hash_3));
5694 assert!(as_failds.contains(&payment_hash_5));
5696 assert!(as_failds.contains(&payment_hash_6));
5698 let bs_events = nodes[1].node.get_and_clear_pending_events();
5699 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5700 let mut bs_failds = HashSet::new();
5701 let mut bs_updates = 0;
5702 for event in bs_events.iter() {
5703 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5704 assert!(bs_failds.insert(*payment_hash));
5705 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5706 assert_eq!(*rejected_by_dest, deliver_last_raa);
5708 assert!(!rejected_by_dest);
5710 if network_update.is_some() {
5713 } else { panic!("Unexpected event"); }
5715 assert!(bs_failds.contains(&payment_hash_1));
5716 assert!(bs_failds.contains(&payment_hash_2));
5717 if announce_latest {
5718 assert!(bs_failds.contains(&payment_hash_4));
5720 assert!(bs_failds.contains(&payment_hash_5));
5722 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5723 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5724 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5725 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5726 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5727 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5731 fn test_fail_backwards_latest_remote_announce_a() {
5732 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5736 fn test_fail_backwards_latest_remote_announce_b() {
5737 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5741 fn test_fail_backwards_previous_remote_announce() {
5742 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5743 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5744 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5748 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5749 let chanmon_cfgs = create_chanmon_cfgs(2);
5750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5752 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5754 // Create some initial channels
5755 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5757 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5758 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5759 assert_eq!(local_txn[0].input.len(), 1);
5760 check_spends!(local_txn[0], chan_1.3);
5762 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5763 mine_transaction(&nodes[0], &local_txn[0]);
5764 check_closed_broadcast!(nodes[0], true);
5765 check_added_monitors!(nodes[0], 1);
5766 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5767 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5769 let htlc_timeout = {
5770 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5771 assert_eq!(node_txn.len(), 2);
5772 check_spends!(node_txn[0], chan_1.3);
5773 assert_eq!(node_txn[1].input.len(), 1);
5774 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5775 check_spends!(node_txn[1], local_txn[0]);
5779 mine_transaction(&nodes[0], &htlc_timeout);
5780 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5781 expect_payment_failed!(nodes[0], our_payment_hash, true);
5783 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5784 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5785 assert_eq!(spend_txn.len(), 3);
5786 check_spends!(spend_txn[0], local_txn[0]);
5787 assert_eq!(spend_txn[1].input.len(), 1);
5788 check_spends!(spend_txn[1], htlc_timeout);
5789 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5790 assert_eq!(spend_txn[2].input.len(), 2);
5791 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5792 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5793 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5797 fn test_key_derivation_params() {
5798 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5799 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5800 // let us re-derive the channel key set to then derive a delayed_payment_key.
5802 let chanmon_cfgs = create_chanmon_cfgs(3);
5804 // We manually create the node configuration to backup the seed.
5805 let seed = [42; 32];
5806 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5807 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);
5808 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5809 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, features: InitFeatures::known() };
5810 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5811 node_cfgs.remove(0);
5812 node_cfgs.insert(0, node);
5814 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5815 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5817 // Create some initial channels
5818 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5820 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5821 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5822 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5824 // Ensure all nodes are at the same height
5825 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5826 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5827 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5828 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5830 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5831 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5832 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5833 assert_eq!(local_txn_1[0].input.len(), 1);
5834 check_spends!(local_txn_1[0], chan_1.3);
5836 // We check funding pubkey are unique
5837 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]));
5838 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]));
5839 if from_0_funding_key_0 == from_1_funding_key_0
5840 || from_0_funding_key_0 == from_1_funding_key_1
5841 || from_0_funding_key_1 == from_1_funding_key_0
5842 || from_0_funding_key_1 == from_1_funding_key_1 {
5843 panic!("Funding pubkeys aren't unique");
5846 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5847 mine_transaction(&nodes[0], &local_txn_1[0]);
5848 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5849 check_closed_broadcast!(nodes[0], true);
5850 check_added_monitors!(nodes[0], 1);
5851 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5853 let htlc_timeout = {
5854 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5855 assert_eq!(node_txn[1].input.len(), 1);
5856 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5857 check_spends!(node_txn[1], local_txn_1[0]);
5861 mine_transaction(&nodes[0], &htlc_timeout);
5862 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5863 expect_payment_failed!(nodes[0], our_payment_hash, true);
5865 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5866 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5867 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5868 assert_eq!(spend_txn.len(), 3);
5869 check_spends!(spend_txn[0], local_txn_1[0]);
5870 assert_eq!(spend_txn[1].input.len(), 1);
5871 check_spends!(spend_txn[1], htlc_timeout);
5872 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5873 assert_eq!(spend_txn[2].input.len(), 2);
5874 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5875 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5876 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5880 fn test_static_output_closing_tx() {
5881 let chanmon_cfgs = create_chanmon_cfgs(2);
5882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5884 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5886 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5888 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5889 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5891 mine_transaction(&nodes[0], &closing_tx);
5892 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5893 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5895 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5896 assert_eq!(spend_txn.len(), 1);
5897 check_spends!(spend_txn[0], closing_tx);
5899 mine_transaction(&nodes[1], &closing_tx);
5900 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5901 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5903 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5904 assert_eq!(spend_txn.len(), 1);
5905 check_spends!(spend_txn[0], closing_tx);
5908 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5909 let chanmon_cfgs = create_chanmon_cfgs(2);
5910 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5911 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5912 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5913 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5915 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5917 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5918 // present in B's local commitment transaction, but none of A's commitment transactions.
5919 nodes[1].node.claim_funds(payment_preimage);
5920 check_added_monitors!(nodes[1], 1);
5921 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5923 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5924 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5925 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5927 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5928 check_added_monitors!(nodes[0], 1);
5929 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5930 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5931 check_added_monitors!(nodes[1], 1);
5933 let starting_block = nodes[1].best_block_info();
5934 let mut block = Block {
5935 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5938 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5939 connect_block(&nodes[1], &block);
5940 block.header.prev_blockhash = block.block_hash();
5942 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5943 check_closed_broadcast!(nodes[1], true);
5944 check_added_monitors!(nodes[1], 1);
5945 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5948 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5949 let chanmon_cfgs = create_chanmon_cfgs(2);
5950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5952 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5953 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5955 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5956 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5957 check_added_monitors!(nodes[0], 1);
5959 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5961 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5962 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5963 // to "time out" the HTLC.
5965 let starting_block = nodes[1].best_block_info();
5966 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5968 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5969 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5970 header.prev_blockhash = header.block_hash();
5972 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5973 check_closed_broadcast!(nodes[0], true);
5974 check_added_monitors!(nodes[0], 1);
5975 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5978 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5979 let chanmon_cfgs = create_chanmon_cfgs(3);
5980 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5982 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5983 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5985 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5986 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5987 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5988 // actually revoked.
5989 let htlc_value = if use_dust { 50000 } else { 3000000 };
5990 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5991 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5992 expect_pending_htlcs_forwardable!(nodes[1]);
5993 check_added_monitors!(nodes[1], 1);
5995 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5996 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5997 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5998 check_added_monitors!(nodes[0], 1);
5999 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6000 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6001 check_added_monitors!(nodes[1], 1);
6002 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6003 check_added_monitors!(nodes[1], 1);
6004 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6006 if check_revoke_no_close {
6007 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6008 check_added_monitors!(nodes[0], 1);
6011 let starting_block = nodes[1].best_block_info();
6012 let mut block = Block {
6013 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6016 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6017 connect_block(&nodes[0], &block);
6018 block.header.prev_blockhash = block.block_hash();
6020 if !check_revoke_no_close {
6021 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6022 check_closed_broadcast!(nodes[0], true);
6023 check_added_monitors!(nodes[0], 1);
6024 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6026 let events = nodes[0].node.get_and_clear_pending_events();
6027 assert_eq!(events.len(), 2);
6028 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6029 assert_eq!(*payment_hash, our_payment_hash);
6030 } else { panic!("Unexpected event"); }
6031 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6032 assert_eq!(*payment_hash, our_payment_hash);
6033 } else { panic!("Unexpected event"); }
6037 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6038 // There are only a few cases to test here:
6039 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6040 // broadcastable commitment transactions result in channel closure,
6041 // * its included in an unrevoked-but-previous remote commitment transaction,
6042 // * its included in the latest remote or local commitment transactions.
6043 // We test each of the three possible commitment transactions individually and use both dust and
6045 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6046 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6047 // tested for at least one of the cases in other tests.
6049 fn htlc_claim_single_commitment_only_a() {
6050 do_htlc_claim_local_commitment_only(true);
6051 do_htlc_claim_local_commitment_only(false);
6053 do_htlc_claim_current_remote_commitment_only(true);
6054 do_htlc_claim_current_remote_commitment_only(false);
6058 fn htlc_claim_single_commitment_only_b() {
6059 do_htlc_claim_previous_remote_commitment_only(true, false);
6060 do_htlc_claim_previous_remote_commitment_only(false, false);
6061 do_htlc_claim_previous_remote_commitment_only(true, true);
6062 do_htlc_claim_previous_remote_commitment_only(false, true);
6067 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
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);
6072 // Force duplicate randomness for every get-random call
6073 for node in nodes.iter() {
6074 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6077 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6078 let channel_value_satoshis=10000;
6079 let push_msat=10001;
6080 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6081 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6082 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6083 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6085 // Create a second channel with the same random values. This used to panic due to a colliding
6086 // channel_id, but now panics due to a colliding outbound SCID alias.
6087 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6091 fn bolt2_open_channel_sending_node_checks_part2() {
6092 let chanmon_cfgs = create_chanmon_cfgs(2);
6093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6097 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6098 let channel_value_satoshis=2^24;
6099 let push_msat=10001;
6100 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6102 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6103 let channel_value_satoshis=10000;
6104 // Test when push_msat is equal to 1000 * funding_satoshis.
6105 let push_msat=1000*channel_value_satoshis+1;
6106 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6108 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6109 let channel_value_satoshis=10000;
6110 let push_msat=10001;
6111 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
6112 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6113 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6115 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6116 // 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
6117 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6119 // 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.
6120 assert!(BREAKDOWN_TIMEOUT>0);
6121 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6123 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6124 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6125 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6127 // 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.
6128 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6129 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6130 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6131 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6132 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6136 fn bolt2_open_channel_sane_dust_limit() {
6137 let chanmon_cfgs = create_chanmon_cfgs(2);
6138 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6139 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6140 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6142 let channel_value_satoshis=1000000;
6143 let push_msat=10001;
6144 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6145 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6146 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6147 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6149 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6150 let events = nodes[1].node.get_and_clear_pending_msg_events();
6151 let err_msg = match events[0] {
6152 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6155 _ => panic!("Unexpected event"),
6157 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6160 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6161 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6162 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6163 // is no longer affordable once it's freed.
6165 fn test_fail_holding_cell_htlc_upon_free() {
6166 let chanmon_cfgs = create_chanmon_cfgs(2);
6167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6169 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6170 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6172 // First nodes[0] generates an update_fee, setting the channel's
6173 // pending_update_fee.
6175 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6176 *feerate_lock += 20;
6178 nodes[0].node.timer_tick_occurred();
6179 check_added_monitors!(nodes[0], 1);
6181 let events = nodes[0].node.get_and_clear_pending_msg_events();
6182 assert_eq!(events.len(), 1);
6183 let (update_msg, commitment_signed) = match events[0] {
6184 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6185 (update_fee.as_ref(), commitment_signed)
6187 _ => panic!("Unexpected event"),
6190 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6192 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6193 let channel_reserve = chan_stat.channel_reserve_msat;
6194 let feerate = get_feerate!(nodes[0], chan.2);
6195 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6197 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6198 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6199 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6201 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6202 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6203 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6204 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6206 // Flush the pending fee update.
6207 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6208 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6209 check_added_monitors!(nodes[1], 1);
6210 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6211 check_added_monitors!(nodes[0], 1);
6213 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6214 // HTLC, but now that the fee has been raised the payment will now fail, causing
6215 // us to surface its failure to the user.
6216 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6217 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6218 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);
6219 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 {}",
6220 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6221 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6223 // Check that the payment failed to be sent out.
6224 let events = nodes[0].node.get_and_clear_pending_events();
6225 assert_eq!(events.len(), 1);
6227 &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, .. } => {
6228 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6229 assert_eq!(our_payment_hash.clone(), *payment_hash);
6230 assert_eq!(*rejected_by_dest, false);
6231 assert_eq!(*all_paths_failed, true);
6232 assert_eq!(*network_update, None);
6233 assert_eq!(*short_channel_id, None);
6234 assert_eq!(*error_code, None);
6235 assert_eq!(*error_data, None);
6237 _ => panic!("Unexpected event"),
6241 // Test that if multiple HTLCs are released from the holding cell and one is
6242 // valid but the other is no longer valid upon release, the valid HTLC can be
6243 // successfully completed while the other one fails as expected.
6245 fn test_free_and_fail_holding_cell_htlcs() {
6246 let chanmon_cfgs = create_chanmon_cfgs(2);
6247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6249 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6250 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6252 // First nodes[0] generates an update_fee, setting the channel's
6253 // pending_update_fee.
6255 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6256 *feerate_lock += 200;
6258 nodes[0].node.timer_tick_occurred();
6259 check_added_monitors!(nodes[0], 1);
6261 let events = nodes[0].node.get_and_clear_pending_msg_events();
6262 assert_eq!(events.len(), 1);
6263 let (update_msg, commitment_signed) = match events[0] {
6264 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6265 (update_fee.as_ref(), commitment_signed)
6267 _ => panic!("Unexpected event"),
6270 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6272 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6273 let channel_reserve = chan_stat.channel_reserve_msat;
6274 let feerate = get_feerate!(nodes[0], chan.2);
6275 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6277 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6279 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6280 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6281 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6283 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6284 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6285 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6286 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6287 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6288 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6289 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6291 // Flush the pending fee update.
6292 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6293 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6294 check_added_monitors!(nodes[1], 1);
6295 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6296 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6297 check_added_monitors!(nodes[0], 2);
6299 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6300 // but now that the fee has been raised the second payment will now fail, causing us
6301 // to surface its failure to the user. The first payment should succeed.
6302 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6303 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6304 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);
6305 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 {}",
6306 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6307 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6309 // Check that the second payment failed to be sent out.
6310 let events = nodes[0].node.get_and_clear_pending_events();
6311 assert_eq!(events.len(), 1);
6313 &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, .. } => {
6314 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6315 assert_eq!(payment_hash_2.clone(), *payment_hash);
6316 assert_eq!(*rejected_by_dest, false);
6317 assert_eq!(*all_paths_failed, true);
6318 assert_eq!(*network_update, None);
6319 assert_eq!(*short_channel_id, None);
6320 assert_eq!(*error_code, None);
6321 assert_eq!(*error_data, None);
6323 _ => panic!("Unexpected event"),
6326 // Complete the first payment and the RAA from the fee update.
6327 let (payment_event, send_raa_event) = {
6328 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6329 assert_eq!(msgs.len(), 2);
6330 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6332 let raa = match send_raa_event {
6333 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6334 _ => panic!("Unexpected event"),
6336 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6337 check_added_monitors!(nodes[1], 1);
6338 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6339 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6340 let events = nodes[1].node.get_and_clear_pending_events();
6341 assert_eq!(events.len(), 1);
6343 Event::PendingHTLCsForwardable { .. } => {},
6344 _ => panic!("Unexpected event"),
6346 nodes[1].node.process_pending_htlc_forwards();
6347 let events = nodes[1].node.get_and_clear_pending_events();
6348 assert_eq!(events.len(), 1);
6350 Event::PaymentReceived { .. } => {},
6351 _ => panic!("Unexpected event"),
6353 nodes[1].node.claim_funds(payment_preimage_1);
6354 check_added_monitors!(nodes[1], 1);
6355 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6357 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6358 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6359 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6360 expect_payment_sent!(nodes[0], payment_preimage_1);
6363 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6364 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6365 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6368 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6369 let chanmon_cfgs = create_chanmon_cfgs(3);
6370 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6371 // When this test was written, the default base fee floated based on the HTLC count.
6372 // It is now fixed, so we simply set the fee to the expected value here.
6373 let mut config = test_default_channel_config();
6374 config.channel_config.forwarding_fee_base_msat = 196;
6375 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6376 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6377 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6378 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6380 // First nodes[1] generates an update_fee, setting the channel's
6381 // pending_update_fee.
6383 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6384 *feerate_lock += 20;
6386 nodes[1].node.timer_tick_occurred();
6387 check_added_monitors!(nodes[1], 1);
6389 let events = nodes[1].node.get_and_clear_pending_msg_events();
6390 assert_eq!(events.len(), 1);
6391 let (update_msg, commitment_signed) = match events[0] {
6392 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6393 (update_fee.as_ref(), commitment_signed)
6395 _ => panic!("Unexpected event"),
6398 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6400 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6401 let channel_reserve = chan_stat.channel_reserve_msat;
6402 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6403 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6405 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6407 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6408 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6409 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6410 let payment_event = {
6411 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6412 check_added_monitors!(nodes[0], 1);
6414 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6415 assert_eq!(events.len(), 1);
6417 SendEvent::from_event(events.remove(0))
6419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6420 check_added_monitors!(nodes[1], 0);
6421 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6422 expect_pending_htlcs_forwardable!(nodes[1]);
6424 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6425 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6427 // Flush the pending fee update.
6428 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6429 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6430 check_added_monitors!(nodes[2], 1);
6431 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6432 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6433 check_added_monitors!(nodes[1], 2);
6435 // A final RAA message is generated to finalize the fee update.
6436 let events = nodes[1].node.get_and_clear_pending_msg_events();
6437 assert_eq!(events.len(), 1);
6439 let raa_msg = match &events[0] {
6440 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6443 _ => panic!("Unexpected event"),
6446 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6447 check_added_monitors!(nodes[2], 1);
6448 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6450 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6451 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6452 assert_eq!(process_htlc_forwards_event.len(), 1);
6453 match &process_htlc_forwards_event[0] {
6454 &Event::PendingHTLCsForwardable { .. } => {},
6455 _ => panic!("Unexpected event"),
6458 // In response, we call ChannelManager's process_pending_htlc_forwards
6459 nodes[1].node.process_pending_htlc_forwards();
6460 check_added_monitors!(nodes[1], 1);
6462 // This causes the HTLC to be failed backwards.
6463 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6464 assert_eq!(fail_event.len(), 1);
6465 let (fail_msg, commitment_signed) = match &fail_event[0] {
6466 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6467 assert_eq!(updates.update_add_htlcs.len(), 0);
6468 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6469 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6470 assert_eq!(updates.update_fail_htlcs.len(), 1);
6471 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6473 _ => panic!("Unexpected event"),
6476 // Pass the failure messages back to nodes[0].
6477 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6478 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6480 // Complete the HTLC failure+removal process.
6481 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6482 check_added_monitors!(nodes[0], 1);
6483 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6484 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6485 check_added_monitors!(nodes[1], 2);
6486 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6487 assert_eq!(final_raa_event.len(), 1);
6488 let raa = match &final_raa_event[0] {
6489 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6490 _ => panic!("Unexpected event"),
6492 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6493 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6494 check_added_monitors!(nodes[0], 1);
6497 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6498 // 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.
6499 //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.
6502 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6503 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6504 let chanmon_cfgs = create_chanmon_cfgs(2);
6505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6507 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6508 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6510 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6511 route.paths[0][0].fee_msat = 100;
6513 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6514 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6515 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6516 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6520 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6521 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6522 let chanmon_cfgs = create_chanmon_cfgs(2);
6523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6525 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6526 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6528 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6529 route.paths[0][0].fee_msat = 0;
6530 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6531 assert_eq!(err, "Cannot send 0-msat HTLC"));
6533 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6534 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6538 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6539 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6540 let chanmon_cfgs = create_chanmon_cfgs(2);
6541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6543 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6544 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6546 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6547 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6548 check_added_monitors!(nodes[0], 1);
6549 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6550 updates.update_add_htlcs[0].amount_msat = 0;
6552 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6553 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6554 check_closed_broadcast!(nodes[1], true).unwrap();
6555 check_added_monitors!(nodes[1], 1);
6556 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6560 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6561 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6562 //It is enforced when constructing a route.
6563 let chanmon_cfgs = create_chanmon_cfgs(2);
6564 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6565 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6566 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6567 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6569 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6570 .with_features(InvoiceFeatures::known());
6571 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6572 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6573 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6574 assert_eq!(err, &"Channel CLTV overflowed?"));
6578 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6579 //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.
6580 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6581 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6582 let chanmon_cfgs = create_chanmon_cfgs(2);
6583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6585 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6586 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6587 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6589 for i in 0..max_accepted_htlcs {
6590 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6591 let payment_event = {
6592 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6593 check_added_monitors!(nodes[0], 1);
6595 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6596 assert_eq!(events.len(), 1);
6597 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6598 assert_eq!(htlcs[0].htlc_id, i);
6602 SendEvent::from_event(events.remove(0))
6604 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6605 check_added_monitors!(nodes[1], 0);
6606 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6608 expect_pending_htlcs_forwardable!(nodes[1]);
6609 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6611 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6612 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6613 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6615 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6616 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6620 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6621 //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.
6622 let chanmon_cfgs = create_chanmon_cfgs(2);
6623 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6624 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6625 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6626 let channel_value = 100000;
6627 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6628 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6630 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6632 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6633 // Manually create a route over our max in flight (which our router normally automatically
6635 route.paths[0][0].fee_msat = max_in_flight + 1;
6636 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6637 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)));
6639 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6640 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);
6642 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6645 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6647 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6648 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6649 let chanmon_cfgs = create_chanmon_cfgs(2);
6650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6654 let htlc_minimum_msat: u64;
6656 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6657 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6658 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6661 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6662 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6663 check_added_monitors!(nodes[0], 1);
6664 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6665 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6666 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6667 assert!(nodes[1].node.list_channels().is_empty());
6668 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6669 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()));
6670 check_added_monitors!(nodes[1], 1);
6671 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6675 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6676 //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
6677 let chanmon_cfgs = create_chanmon_cfgs(2);
6678 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6679 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6680 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6681 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6683 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6684 let channel_reserve = chan_stat.channel_reserve_msat;
6685 let feerate = get_feerate!(nodes[0], chan.2);
6686 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6687 // The 2* and +1 are for the fee spike reserve.
6688 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6690 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6691 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6692 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6693 check_added_monitors!(nodes[0], 1);
6694 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6696 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6697 // at this time channel-initiatee receivers are not required to enforce that senders
6698 // respect the fee_spike_reserve.
6699 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6700 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6702 assert!(nodes[1].node.list_channels().is_empty());
6703 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6704 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6705 check_added_monitors!(nodes[1], 1);
6706 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6710 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6711 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6712 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6713 let chanmon_cfgs = create_chanmon_cfgs(2);
6714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6716 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6717 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6719 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6720 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6721 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6722 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6723 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6724 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6726 let mut msg = msgs::UpdateAddHTLC {
6730 payment_hash: our_payment_hash,
6731 cltv_expiry: htlc_cltv,
6732 onion_routing_packet: onion_packet.clone(),
6735 for i in 0..super::channel::OUR_MAX_HTLCS {
6736 msg.htlc_id = i as u64;
6737 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6739 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6740 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6742 assert!(nodes[1].node.list_channels().is_empty());
6743 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6744 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6745 check_added_monitors!(nodes[1], 1);
6746 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6750 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6751 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6752 let chanmon_cfgs = create_chanmon_cfgs(2);
6753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6755 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6756 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6758 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6759 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6760 check_added_monitors!(nodes[0], 1);
6761 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6762 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6763 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6765 assert!(nodes[1].node.list_channels().is_empty());
6766 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6767 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6768 check_added_monitors!(nodes[1], 1);
6769 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6773 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6774 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6775 let chanmon_cfgs = create_chanmon_cfgs(2);
6776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6778 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6780 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6781 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6782 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6783 check_added_monitors!(nodes[0], 1);
6784 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6785 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6786 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6788 assert!(nodes[1].node.list_channels().is_empty());
6789 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6790 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6791 check_added_monitors!(nodes[1], 1);
6792 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6796 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6797 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6798 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6799 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6800 let chanmon_cfgs = create_chanmon_cfgs(2);
6801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6803 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6805 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6806 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6807 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6808 check_added_monitors!(nodes[0], 1);
6809 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6810 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6812 //Disconnect and Reconnect
6813 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6814 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6815 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6816 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6817 assert_eq!(reestablish_1.len(), 1);
6818 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6819 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6820 assert_eq!(reestablish_2.len(), 1);
6821 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6822 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6823 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6824 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6827 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6828 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6829 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6830 check_added_monitors!(nodes[1], 1);
6831 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6833 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6835 assert!(nodes[1].node.list_channels().is_empty());
6836 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6837 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6838 check_added_monitors!(nodes[1], 1);
6839 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6843 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6844 //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.
6846 let chanmon_cfgs = create_chanmon_cfgs(2);
6847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6849 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6850 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6851 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6852 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6854 check_added_monitors!(nodes[0], 1);
6855 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6856 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6858 let update_msg = msgs::UpdateFulfillHTLC{
6861 payment_preimage: our_payment_preimage,
6864 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6866 assert!(nodes[0].node.list_channels().is_empty());
6867 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6868 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()));
6869 check_added_monitors!(nodes[0], 1);
6870 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6874 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6875 //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.
6877 let chanmon_cfgs = create_chanmon_cfgs(2);
6878 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6879 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6880 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6881 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6883 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6884 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6885 check_added_monitors!(nodes[0], 1);
6886 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6887 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6889 let update_msg = msgs::UpdateFailHTLC{
6892 reason: msgs::OnionErrorPacket { data: Vec::new()},
6895 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6897 assert!(nodes[0].node.list_channels().is_empty());
6898 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6899 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()));
6900 check_added_monitors!(nodes[0], 1);
6901 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6905 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6906 //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.
6908 let chanmon_cfgs = create_chanmon_cfgs(2);
6909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6911 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6912 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6914 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6915 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6916 check_added_monitors!(nodes[0], 1);
6917 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6918 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6919 let update_msg = msgs::UpdateFailMalformedHTLC{
6922 sha256_of_onion: [1; 32],
6923 failure_code: 0x8000,
6926 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6928 assert!(nodes[0].node.list_channels().is_empty());
6929 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6930 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()));
6931 check_added_monitors!(nodes[0], 1);
6932 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6936 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6937 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6939 let chanmon_cfgs = create_chanmon_cfgs(2);
6940 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6941 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6942 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6943 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6945 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6947 nodes[1].node.claim_funds(our_payment_preimage);
6948 check_added_monitors!(nodes[1], 1);
6949 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6951 let events = nodes[1].node.get_and_clear_pending_msg_events();
6952 assert_eq!(events.len(), 1);
6953 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6955 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, .. } } => {
6956 assert!(update_add_htlcs.is_empty());
6957 assert_eq!(update_fulfill_htlcs.len(), 1);
6958 assert!(update_fail_htlcs.is_empty());
6959 assert!(update_fail_malformed_htlcs.is_empty());
6960 assert!(update_fee.is_none());
6961 update_fulfill_htlcs[0].clone()
6963 _ => panic!("Unexpected event"),
6967 update_fulfill_msg.htlc_id = 1;
6969 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6971 assert!(nodes[0].node.list_channels().is_empty());
6972 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6973 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6974 check_added_monitors!(nodes[0], 1);
6975 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6979 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6980 //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.
6982 let chanmon_cfgs = create_chanmon_cfgs(2);
6983 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6984 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6985 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6986 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6988 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6990 nodes[1].node.claim_funds(our_payment_preimage);
6991 check_added_monitors!(nodes[1], 1);
6992 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6994 let events = nodes[1].node.get_and_clear_pending_msg_events();
6995 assert_eq!(events.len(), 1);
6996 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6998 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, .. } } => {
6999 assert!(update_add_htlcs.is_empty());
7000 assert_eq!(update_fulfill_htlcs.len(), 1);
7001 assert!(update_fail_htlcs.is_empty());
7002 assert!(update_fail_malformed_htlcs.is_empty());
7003 assert!(update_fee.is_none());
7004 update_fulfill_htlcs[0].clone()
7006 _ => panic!("Unexpected event"),
7010 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7012 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7014 assert!(nodes[0].node.list_channels().is_empty());
7015 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7016 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7017 check_added_monitors!(nodes[0], 1);
7018 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7022 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7023 //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.
7025 let chanmon_cfgs = create_chanmon_cfgs(2);
7026 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7028 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7029 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7031 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7032 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7033 check_added_monitors!(nodes[0], 1);
7035 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7036 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7038 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7039 check_added_monitors!(nodes[1], 0);
7040 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7042 let events = nodes[1].node.get_and_clear_pending_msg_events();
7044 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7046 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, .. } } => {
7047 assert!(update_add_htlcs.is_empty());
7048 assert!(update_fulfill_htlcs.is_empty());
7049 assert!(update_fail_htlcs.is_empty());
7050 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7051 assert!(update_fee.is_none());
7052 update_fail_malformed_htlcs[0].clone()
7054 _ => panic!("Unexpected event"),
7057 update_msg.failure_code &= !0x8000;
7058 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7060 assert!(nodes[0].node.list_channels().is_empty());
7061 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7062 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7063 check_added_monitors!(nodes[0], 1);
7064 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7068 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7069 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7070 // * 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.
7072 let chanmon_cfgs = create_chanmon_cfgs(3);
7073 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7074 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7075 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7076 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7077 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7079 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7082 let mut payment_event = {
7083 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7084 check_added_monitors!(nodes[0], 1);
7085 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7086 assert_eq!(events.len(), 1);
7087 SendEvent::from_event(events.remove(0))
7089 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7090 check_added_monitors!(nodes[1], 0);
7091 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7092 expect_pending_htlcs_forwardable!(nodes[1]);
7093 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7094 assert_eq!(events_2.len(), 1);
7095 check_added_monitors!(nodes[1], 1);
7096 payment_event = SendEvent::from_event(events_2.remove(0));
7097 assert_eq!(payment_event.msgs.len(), 1);
7100 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7101 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7102 check_added_monitors!(nodes[2], 0);
7103 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7105 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7106 assert_eq!(events_3.len(), 1);
7107 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7109 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 } } => {
7110 assert!(update_add_htlcs.is_empty());
7111 assert!(update_fulfill_htlcs.is_empty());
7112 assert!(update_fail_htlcs.is_empty());
7113 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7114 assert!(update_fee.is_none());
7115 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7117 _ => panic!("Unexpected event"),
7121 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7123 check_added_monitors!(nodes[1], 0);
7124 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7125 expect_pending_htlcs_forwardable!(nodes[1]);
7126 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7127 assert_eq!(events_4.len(), 1);
7129 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7131 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, .. } } => {
7132 assert!(update_add_htlcs.is_empty());
7133 assert!(update_fulfill_htlcs.is_empty());
7134 assert_eq!(update_fail_htlcs.len(), 1);
7135 assert!(update_fail_malformed_htlcs.is_empty());
7136 assert!(update_fee.is_none());
7138 _ => panic!("Unexpected event"),
7141 check_added_monitors!(nodes[1], 1);
7144 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7145 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7146 // 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
7147 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7149 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7150 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7151 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7152 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7153 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7154 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7156 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7158 // We route 2 dust-HTLCs between A and B
7159 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7160 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7161 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7163 // Cache one local commitment tx as previous
7164 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7166 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7167 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7168 check_added_monitors!(nodes[1], 0);
7169 expect_pending_htlcs_forwardable!(nodes[1]);
7170 check_added_monitors!(nodes[1], 1);
7172 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7173 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7174 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7175 check_added_monitors!(nodes[0], 1);
7177 // Cache one local commitment tx as lastest
7178 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7180 let events = nodes[0].node.get_and_clear_pending_msg_events();
7182 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7183 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7185 _ => panic!("Unexpected event"),
7188 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7189 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7191 _ => panic!("Unexpected event"),
7194 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7195 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7196 if announce_latest {
7197 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7199 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7202 check_closed_broadcast!(nodes[0], true);
7203 check_added_monitors!(nodes[0], 1);
7204 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7206 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7207 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7208 let events = nodes[0].node.get_and_clear_pending_events();
7209 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7210 assert_eq!(events.len(), 2);
7211 let mut first_failed = false;
7212 for event in events {
7214 Event::PaymentPathFailed { payment_hash, .. } => {
7215 if payment_hash == payment_hash_1 {
7216 assert!(!first_failed);
7217 first_failed = true;
7219 assert_eq!(payment_hash, payment_hash_2);
7222 _ => panic!("Unexpected event"),
7228 fn test_failure_delay_dust_htlc_local_commitment() {
7229 do_test_failure_delay_dust_htlc_local_commitment(true);
7230 do_test_failure_delay_dust_htlc_local_commitment(false);
7233 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7234 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7235 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7236 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7237 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7238 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7239 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7241 let chanmon_cfgs = create_chanmon_cfgs(3);
7242 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7243 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7244 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7245 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7247 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7249 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7250 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7252 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7253 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7255 // We revoked bs_commitment_tx
7257 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7258 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7261 let mut timeout_tx = Vec::new();
7263 // We fail dust-HTLC 1 by broadcast of local commitment tx
7264 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7265 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7266 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7267 expect_payment_failed!(nodes[0], dust_hash, true);
7269 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7270 check_closed_broadcast!(nodes[0], true);
7271 check_added_monitors!(nodes[0], 1);
7272 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7273 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7274 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7275 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7276 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7277 mine_transaction(&nodes[0], &timeout_tx[0]);
7278 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7279 expect_payment_failed!(nodes[0], non_dust_hash, true);
7281 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7282 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7283 check_closed_broadcast!(nodes[0], true);
7284 check_added_monitors!(nodes[0], 1);
7285 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7286 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7287 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7288 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7290 expect_payment_failed!(nodes[0], dust_hash, true);
7291 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7292 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7293 mine_transaction(&nodes[0], &timeout_tx[0]);
7294 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7295 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7296 expect_payment_failed!(nodes[0], non_dust_hash, true);
7298 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7300 let events = nodes[0].node.get_and_clear_pending_events();
7301 assert_eq!(events.len(), 2);
7304 Event::PaymentPathFailed { payment_hash, .. } => {
7305 if payment_hash == dust_hash { first = true; }
7306 else { first = false; }
7308 _ => panic!("Unexpected event"),
7311 Event::PaymentPathFailed { payment_hash, .. } => {
7312 if first { assert_eq!(payment_hash, non_dust_hash); }
7313 else { assert_eq!(payment_hash, dust_hash); }
7315 _ => panic!("Unexpected event"),
7322 fn test_sweep_outbound_htlc_failure_update() {
7323 do_test_sweep_outbound_htlc_failure_update(false, true);
7324 do_test_sweep_outbound_htlc_failure_update(false, false);
7325 do_test_sweep_outbound_htlc_failure_update(true, false);
7329 fn test_user_configurable_csv_delay() {
7330 // We test our channel constructors yield errors when we pass them absurd csv delay
7332 let mut low_our_to_self_config = UserConfig::default();
7333 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7334 let mut high_their_to_self_config = UserConfig::default();
7335 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7336 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7337 let chanmon_cfgs = create_chanmon_cfgs(2);
7338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7340 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7342 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7343 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7344 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7345 &low_our_to_self_config, 0, 42)
7348 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())); },
7349 _ => panic!("Unexpected event"),
7351 } else { assert!(false) }
7353 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7354 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7355 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7356 open_channel.to_self_delay = 200;
7357 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7358 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7359 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7362 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())); },
7363 _ => panic!("Unexpected event"),
7365 } else { assert!(false); }
7367 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7368 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7369 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()));
7370 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7371 accept_channel.to_self_delay = 200;
7372 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7374 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7376 &ErrorAction::SendErrorMessage { ref msg } => {
7377 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()));
7378 reason_msg = msg.data.clone();
7382 } else { panic!(); }
7383 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7385 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7386 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7387 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7388 open_channel.to_self_delay = 200;
7389 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7390 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7391 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7394 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())); },
7395 _ => panic!("Unexpected event"),
7397 } else { assert!(false); }
7401 fn test_data_loss_protect() {
7402 // We want to be sure that :
7403 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7404 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7405 // * we close channel in case of detecting other being fallen behind
7406 // * we are able to claim our own outputs thanks to to_remote being static
7407 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7413 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7414 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7415 // during signing due to revoked tx
7416 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7417 let keys_manager = &chanmon_cfgs[0].keys_manager;
7420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7422 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7424 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7426 // Cache node A state before any channel update
7427 let previous_node_state = nodes[0].node.encode();
7428 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7429 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7431 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7432 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7434 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7435 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7437 // Restore node A from previous state
7438 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7439 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7440 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7441 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7442 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7443 persister = test_utils::TestPersister::new();
7444 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7446 let mut channel_monitors = HashMap::new();
7447 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7448 <(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 {
7449 keys_manager: keys_manager,
7450 fee_estimator: &fee_estimator,
7451 chain_monitor: &monitor,
7453 tx_broadcaster: &tx_broadcaster,
7454 default_config: UserConfig::default(),
7458 nodes[0].node = &node_state_0;
7459 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7460 nodes[0].chain_monitor = &monitor;
7461 nodes[0].chain_source = &chain_source;
7463 check_added_monitors!(nodes[0], 1);
7465 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7466 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7468 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7470 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7471 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7472 check_added_monitors!(nodes[0], 1);
7475 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7476 assert_eq!(node_txn.len(), 0);
7479 let mut reestablish_1 = Vec::with_capacity(1);
7480 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7481 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7482 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7483 reestablish_1.push(msg.clone());
7484 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7485 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7487 &ErrorAction::SendErrorMessage { ref msg } => {
7488 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");
7490 _ => panic!("Unexpected event!"),
7493 panic!("Unexpected event")
7497 // Check we close channel detecting A is fallen-behind
7498 // Check that we sent the warning message when we detected that A has fallen behind,
7499 // and give the possibility for A to recover from the warning.
7500 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7501 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7502 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7504 // Check A is able to claim to_remote output
7505 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7506 // The node B should not broadcast the transaction to force close the channel!
7507 assert!(node_txn.is_empty());
7508 // B should now detect that there is something wrong and should force close the channel.
7509 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";
7510 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7512 // after the warning message sent by B, we should not able to
7513 // use the channel, or reconnect with success to the channel.
7514 assert!(nodes[0].node.list_usable_channels().is_empty());
7515 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7516 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7517 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7519 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7520 let mut err_msgs_0 = Vec::with_capacity(1);
7521 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7522 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7524 &ErrorAction::SendErrorMessage { ref msg } => {
7525 assert_eq!(msg.data, "Failed to find corresponding channel");
7526 err_msgs_0.push(msg.clone());
7528 _ => panic!("Unexpected event!"),
7531 panic!("Unexpected event!");
7534 assert_eq!(err_msgs_0.len(), 1);
7535 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7536 assert!(nodes[1].node.list_usable_channels().is_empty());
7537 check_added_monitors!(nodes[1], 1);
7538 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7539 check_closed_broadcast!(nodes[1], false);
7543 fn test_check_htlc_underpaying() {
7544 // Send payment through A -> B but A is maliciously
7545 // sending a probe payment (i.e less than expected value0
7546 // to B, B should refuse payment.
7548 let chanmon_cfgs = create_chanmon_cfgs(2);
7549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7551 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7553 // Create some initial channels
7554 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7556 let scorer = test_utils::TestScorer::with_penalty(0);
7557 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7558 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7559 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();
7560 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7561 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7562 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7563 check_added_monitors!(nodes[0], 1);
7565 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7566 assert_eq!(events.len(), 1);
7567 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7568 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7569 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7571 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7572 // and then will wait a second random delay before failing the HTLC back:
7573 expect_pending_htlcs_forwardable!(nodes[1]);
7574 expect_pending_htlcs_forwardable!(nodes[1]);
7576 // Node 3 is expecting payment of 100_000 but received 10_000,
7577 // it should fail htlc like we didn't know the preimage.
7578 nodes[1].node.process_pending_htlc_forwards();
7580 let events = nodes[1].node.get_and_clear_pending_msg_events();
7581 assert_eq!(events.len(), 1);
7582 let (update_fail_htlc, commitment_signed) = match events[0] {
7583 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 } } => {
7584 assert!(update_add_htlcs.is_empty());
7585 assert!(update_fulfill_htlcs.is_empty());
7586 assert_eq!(update_fail_htlcs.len(), 1);
7587 assert!(update_fail_malformed_htlcs.is_empty());
7588 assert!(update_fee.is_none());
7589 (update_fail_htlcs[0].clone(), commitment_signed)
7591 _ => panic!("Unexpected event"),
7593 check_added_monitors!(nodes[1], 1);
7595 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7596 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7598 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7599 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7600 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7601 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7605 fn test_announce_disable_channels() {
7606 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7607 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7609 let chanmon_cfgs = create_chanmon_cfgs(2);
7610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7612 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7614 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7615 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7616 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7619 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7620 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7622 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7623 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7624 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7625 assert_eq!(msg_events.len(), 3);
7626 let mut chans_disabled = HashMap::new();
7627 for e in msg_events {
7629 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7630 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7631 // Check that each channel gets updated exactly once
7632 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7633 panic!("Generated ChannelUpdate for wrong chan!");
7636 _ => panic!("Unexpected event"),
7640 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7641 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7642 assert_eq!(reestablish_1.len(), 3);
7643 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7644 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7645 assert_eq!(reestablish_2.len(), 3);
7647 // Reestablish chan_1
7648 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7649 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7650 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7651 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7652 // Reestablish chan_2
7653 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7654 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7655 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7656 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7657 // Reestablish chan_3
7658 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7659 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7661 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7663 nodes[0].node.timer_tick_occurred();
7664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7665 nodes[0].node.timer_tick_occurred();
7666 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7667 assert_eq!(msg_events.len(), 3);
7668 for e in msg_events {
7670 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7671 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7672 match chans_disabled.remove(&msg.contents.short_channel_id) {
7673 // Each update should have a higher timestamp than the previous one, replacing
7675 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7676 None => panic!("Generated ChannelUpdate for wrong chan!"),
7679 _ => panic!("Unexpected event"),
7682 // Check that each channel gets updated exactly once
7683 assert!(chans_disabled.is_empty());
7687 fn test_bump_penalty_txn_on_revoked_commitment() {
7688 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7689 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7691 let chanmon_cfgs = create_chanmon_cfgs(2);
7692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7694 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7696 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7698 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7699 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7700 .with_features(InvoiceFeatures::known());
7701 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7702 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7704 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7705 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7706 assert_eq!(revoked_txn[0].output.len(), 4);
7707 assert_eq!(revoked_txn[0].input.len(), 1);
7708 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7709 let revoked_txid = revoked_txn[0].txid();
7711 let mut penalty_sum = 0;
7712 for outp in revoked_txn[0].output.iter() {
7713 if outp.script_pubkey.is_v0_p2wsh() {
7714 penalty_sum += outp.value;
7718 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7719 let header_114 = connect_blocks(&nodes[1], 14);
7721 // Actually revoke tx by claiming a HTLC
7722 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7723 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7724 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7725 check_added_monitors!(nodes[1], 1);
7727 // One or more justice tx should have been broadcast, check it
7731 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7732 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7733 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7734 assert_eq!(node_txn[0].output.len(), 1);
7735 check_spends!(node_txn[0], revoked_txn[0]);
7736 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7737 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7738 penalty_1 = node_txn[0].txid();
7742 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7743 connect_blocks(&nodes[1], 15);
7744 let mut penalty_2 = penalty_1;
7745 let mut feerate_2 = 0;
7747 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7748 assert_eq!(node_txn.len(), 1);
7749 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7750 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7751 assert_eq!(node_txn[0].output.len(), 1);
7752 check_spends!(node_txn[0], revoked_txn[0]);
7753 penalty_2 = node_txn[0].txid();
7754 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7755 assert_ne!(penalty_2, penalty_1);
7756 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7757 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7758 // Verify 25% bump heuristic
7759 assert!(feerate_2 * 100 >= feerate_1 * 125);
7763 assert_ne!(feerate_2, 0);
7765 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7766 connect_blocks(&nodes[1], 1);
7768 let mut feerate_3 = 0;
7770 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7771 assert_eq!(node_txn.len(), 1);
7772 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7773 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7774 assert_eq!(node_txn[0].output.len(), 1);
7775 check_spends!(node_txn[0], revoked_txn[0]);
7776 penalty_3 = node_txn[0].txid();
7777 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7778 assert_ne!(penalty_3, penalty_2);
7779 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7780 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7781 // Verify 25% bump heuristic
7782 assert!(feerate_3 * 100 >= feerate_2 * 125);
7786 assert_ne!(feerate_3, 0);
7788 nodes[1].node.get_and_clear_pending_events();
7789 nodes[1].node.get_and_clear_pending_msg_events();
7793 fn test_bump_penalty_txn_on_revoked_htlcs() {
7794 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7795 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7797 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7798 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7801 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7803 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7804 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7805 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7806 let scorer = test_utils::TestScorer::with_penalty(0);
7807 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7808 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7809 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7810 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7811 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7812 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7813 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7814 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7816 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7817 assert_eq!(revoked_local_txn[0].input.len(), 1);
7818 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7820 // Revoke local commitment tx
7821 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7823 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7824 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7825 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7826 check_closed_broadcast!(nodes[1], true);
7827 check_added_monitors!(nodes[1], 1);
7828 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7829 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7831 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7832 assert_eq!(revoked_htlc_txn.len(), 3);
7833 check_spends!(revoked_htlc_txn[1], chan.3);
7835 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7836 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7837 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7839 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7840 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7841 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7842 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7844 // Broadcast set of revoked txn on A
7845 let hash_128 = connect_blocks(&nodes[0], 40);
7846 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7847 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7848 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7849 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7850 let events = nodes[0].node.get_and_clear_pending_events();
7851 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7853 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7854 _ => panic!("Unexpected event"),
7860 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7861 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7862 // Verify claim tx are spending revoked HTLC txn
7864 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7865 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7866 // which are included in the same block (they are broadcasted because we scan the
7867 // transactions linearly and generate claims as we go, they likely should be removed in the
7869 assert_eq!(node_txn[0].input.len(), 1);
7870 check_spends!(node_txn[0], revoked_local_txn[0]);
7871 assert_eq!(node_txn[1].input.len(), 1);
7872 check_spends!(node_txn[1], revoked_local_txn[0]);
7873 assert_eq!(node_txn[2].input.len(), 1);
7874 check_spends!(node_txn[2], revoked_local_txn[0]);
7876 // Each of the three justice transactions claim a separate (single) output of the three
7877 // available, which we check here:
7878 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7879 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7880 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7882 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7883 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7885 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7886 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7887 // a remote commitment tx has already been confirmed).
7888 check_spends!(node_txn[3], chan.3);
7890 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7891 // output, checked above).
7892 assert_eq!(node_txn[4].input.len(), 2);
7893 assert_eq!(node_txn[4].output.len(), 1);
7894 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7896 first = node_txn[4].txid();
7897 // Store both feerates for later comparison
7898 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7899 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7900 penalty_txn = vec![node_txn[2].clone()];
7904 // Connect one more block to see if bumped penalty are issued for HTLC txn
7905 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7906 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7907 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7908 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7910 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7911 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7913 check_spends!(node_txn[0], revoked_local_txn[0]);
7914 check_spends!(node_txn[1], revoked_local_txn[0]);
7915 // Note that these are both bogus - they spend outputs already claimed in block 129:
7916 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7917 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7919 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7920 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7926 // Few more blocks to confirm penalty txn
7927 connect_blocks(&nodes[0], 4);
7928 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7929 let header_144 = connect_blocks(&nodes[0], 9);
7931 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7932 assert_eq!(node_txn.len(), 1);
7934 assert_eq!(node_txn[0].input.len(), 2);
7935 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7936 // Verify bumped tx is different and 25% bump heuristic
7937 assert_ne!(first, node_txn[0].txid());
7938 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7939 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7940 assert!(feerate_2 * 100 > feerate_1 * 125);
7941 let txn = vec![node_txn[0].clone()];
7945 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7946 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7947 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7948 connect_blocks(&nodes[0], 20);
7950 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7951 // We verify than no new transaction has been broadcast because previously
7952 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7953 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7954 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7955 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7956 // up bumped justice generation.
7957 assert_eq!(node_txn.len(), 0);
7960 check_closed_broadcast!(nodes[0], true);
7961 check_added_monitors!(nodes[0], 1);
7965 fn test_bump_penalty_txn_on_remote_commitment() {
7966 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7967 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7970 // Provide preimage for one
7971 // Check aggregation
7973 let chanmon_cfgs = create_chanmon_cfgs(2);
7974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7976 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7978 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7979 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7980 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7982 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7983 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7984 assert_eq!(remote_txn[0].output.len(), 4);
7985 assert_eq!(remote_txn[0].input.len(), 1);
7986 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7988 // Claim a HTLC without revocation (provide B monitor with preimage)
7989 nodes[1].node.claim_funds(payment_preimage);
7990 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7991 mine_transaction(&nodes[1], &remote_txn[0]);
7992 check_added_monitors!(nodes[1], 2);
7993 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7995 // One or more claim tx should have been broadcast, check it
7999 let feerate_timeout;
8000 let feerate_preimage;
8002 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8003 // 9 transactions including:
8004 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8005 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8006 // 2 * HTLC-Success (one RBF bump we'll check later)
8008 assert_eq!(node_txn.len(), 8);
8009 assert_eq!(node_txn[0].input.len(), 1);
8010 assert_eq!(node_txn[6].input.len(), 1);
8011 check_spends!(node_txn[0], remote_txn[0]);
8012 check_spends!(node_txn[6], remote_txn[0]);
8014 check_spends!(node_txn[1], chan.3);
8015 check_spends!(node_txn[2], node_txn[1]);
8017 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8018 preimage_bump = node_txn[3].clone();
8019 check_spends!(node_txn[3], remote_txn[0]);
8021 assert_eq!(node_txn[1], node_txn[4]);
8022 assert_eq!(node_txn[2], node_txn[5]);
8024 preimage_bump = node_txn[7].clone();
8025 check_spends!(node_txn[7], remote_txn[0]);
8026 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8028 assert_eq!(node_txn[1], node_txn[3]);
8029 assert_eq!(node_txn[2], node_txn[4]);
8032 timeout = node_txn[6].txid();
8033 let index = node_txn[6].input[0].previous_output.vout;
8034 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8035 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8037 preimage = node_txn[0].txid();
8038 let index = node_txn[0].input[0].previous_output.vout;
8039 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8040 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8044 assert_ne!(feerate_timeout, 0);
8045 assert_ne!(feerate_preimage, 0);
8047 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8048 connect_blocks(&nodes[1], 15);
8050 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8051 assert_eq!(node_txn.len(), 1);
8052 assert_eq!(node_txn[0].input.len(), 1);
8053 assert_eq!(preimage_bump.input.len(), 1);
8054 check_spends!(node_txn[0], remote_txn[0]);
8055 check_spends!(preimage_bump, remote_txn[0]);
8057 let index = preimage_bump.input[0].previous_output.vout;
8058 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8059 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8060 assert!(new_feerate * 100 > feerate_timeout * 125);
8061 assert_ne!(timeout, preimage_bump.txid());
8063 let index = node_txn[0].input[0].previous_output.vout;
8064 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8065 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8066 assert!(new_feerate * 100 > feerate_preimage * 125);
8067 assert_ne!(preimage, node_txn[0].txid());
8072 nodes[1].node.get_and_clear_pending_events();
8073 nodes[1].node.get_and_clear_pending_msg_events();
8077 fn test_counterparty_raa_skip_no_crash() {
8078 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8079 // commitment transaction, we would have happily carried on and provided them the next
8080 // commitment transaction based on one RAA forward. This would probably eventually have led to
8081 // channel closure, but it would not have resulted in funds loss. Still, our
8082 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8083 // check simply that the channel is closed in response to such an RAA, but don't check whether
8084 // we decide to punish our counterparty for revoking their funds (as we don't currently
8086 let chanmon_cfgs = create_chanmon_cfgs(2);
8087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8089 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8090 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8092 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8093 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8095 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8097 // Make signer believe we got a counterparty signature, so that it allows the revocation
8098 keys.get_enforcement_state().last_holder_commitment -= 1;
8099 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8101 // Must revoke without gaps
8102 keys.get_enforcement_state().last_holder_commitment -= 1;
8103 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8105 keys.get_enforcement_state().last_holder_commitment -= 1;
8106 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8107 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8109 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8110 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8111 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8112 check_added_monitors!(nodes[1], 1);
8113 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8117 fn test_bump_txn_sanitize_tracking_maps() {
8118 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8119 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8121 let chanmon_cfgs = create_chanmon_cfgs(2);
8122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8126 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8127 // Lock HTLC in both directions
8128 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8129 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8131 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8132 assert_eq!(revoked_local_txn[0].input.len(), 1);
8133 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8135 // Revoke local commitment tx
8136 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8138 // Broadcast set of revoked txn on A
8139 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8140 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8141 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8143 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8144 check_closed_broadcast!(nodes[0], true);
8145 check_added_monitors!(nodes[0], 1);
8146 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8148 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8149 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8150 check_spends!(node_txn[0], revoked_local_txn[0]);
8151 check_spends!(node_txn[1], revoked_local_txn[0]);
8152 check_spends!(node_txn[2], revoked_local_txn[0]);
8153 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8157 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8158 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8159 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8161 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8162 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8163 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8168 fn test_pending_claimed_htlc_no_balance_underflow() {
8169 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8170 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8171 let chanmon_cfgs = create_chanmon_cfgs(2);
8172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8174 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8175 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8177 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8178 nodes[1].node.claim_funds(payment_preimage);
8179 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8180 check_added_monitors!(nodes[1], 1);
8181 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8183 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8184 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8185 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8186 check_added_monitors!(nodes[0], 1);
8187 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8189 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8190 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8191 // can get our balance.
8193 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8194 // the public key of the only hop. This works around ChannelDetails not showing the
8195 // almost-claimed HTLC as available balance.
8196 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8197 route.payment_params = None; // This is all wrong, but unnecessary
8198 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8199 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8200 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8202 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8206 fn test_channel_conf_timeout() {
8207 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8208 // confirm within 2016 blocks, as recommended by BOLT 2.
8209 let chanmon_cfgs = create_chanmon_cfgs(2);
8210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8212 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8214 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8216 // The outbound node should wait forever for confirmation:
8217 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8218 // copied here instead of directly referencing the constant.
8219 connect_blocks(&nodes[0], 2016);
8220 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8222 // The inbound node should fail the channel after exactly 2016 blocks
8223 connect_blocks(&nodes[1], 2015);
8224 check_added_monitors!(nodes[1], 0);
8225 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8227 connect_blocks(&nodes[1], 1);
8228 check_added_monitors!(nodes[1], 1);
8229 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8230 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8231 assert_eq!(close_ev.len(), 1);
8233 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8234 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8235 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8237 _ => panic!("Unexpected event"),
8242 fn test_override_channel_config() {
8243 let chanmon_cfgs = create_chanmon_cfgs(2);
8244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8246 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8248 // Node0 initiates a channel to node1 using the override config.
8249 let mut override_config = UserConfig::default();
8250 override_config.channel_handshake_config.our_to_self_delay = 200;
8252 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8254 // Assert the channel created by node0 is using the override config.
8255 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8256 assert_eq!(res.channel_flags, 0);
8257 assert_eq!(res.to_self_delay, 200);
8261 fn test_override_0msat_htlc_minimum() {
8262 let mut zero_config = UserConfig::default();
8263 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8264 let chanmon_cfgs = create_chanmon_cfgs(2);
8265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8269 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8270 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8271 assert_eq!(res.htlc_minimum_msat, 1);
8273 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8274 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8275 assert_eq!(res.htlc_minimum_msat, 1);
8279 fn test_channel_update_has_correct_htlc_maximum_msat() {
8280 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8281 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8282 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8283 // 90% of the `channel_value`.
8284 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8286 let mut config_30_percent = UserConfig::default();
8287 config_30_percent.channel_handshake_config.announced_channel = true;
8288 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8289 let mut config_50_percent = UserConfig::default();
8290 config_50_percent.channel_handshake_config.announced_channel = true;
8291 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8292 let mut config_95_percent = UserConfig::default();
8293 config_95_percent.channel_handshake_config.announced_channel = true;
8294 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8295 let mut config_100_percent = UserConfig::default();
8296 config_100_percent.channel_handshake_config.announced_channel = true;
8297 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8299 let chanmon_cfgs = create_chanmon_cfgs(4);
8300 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8301 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)]);
8302 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8304 let channel_value_satoshis = 100000;
8305 let channel_value_msat = channel_value_satoshis * 1000;
8306 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8307 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8308 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8310 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());
8311 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());
8313 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8314 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8315 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8316 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8317 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8318 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8320 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8321 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8323 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8324 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8325 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8327 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8331 fn test_manually_accept_inbound_channel_request() {
8332 let mut manually_accept_conf = UserConfig::default();
8333 manually_accept_conf.manually_accept_inbound_channels = true;
8334 let chanmon_cfgs = create_chanmon_cfgs(2);
8335 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8336 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8337 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8339 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8340 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8342 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8344 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8345 // accepting the inbound channel request.
8346 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8348 let events = nodes[1].node.get_and_clear_pending_events();
8350 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8351 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8353 _ => panic!("Unexpected event"),
8356 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8357 assert_eq!(accept_msg_ev.len(), 1);
8359 match accept_msg_ev[0] {
8360 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8361 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8363 _ => panic!("Unexpected event"),
8366 nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8368 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8369 assert_eq!(close_msg_ev.len(), 1);
8371 let events = nodes[1].node.get_and_clear_pending_events();
8373 Event::ChannelClosed { user_channel_id, .. } => {
8374 assert_eq!(user_channel_id, 23);
8376 _ => panic!("Unexpected event"),
8381 fn test_manually_reject_inbound_channel_request() {
8382 let mut manually_accept_conf = UserConfig::default();
8383 manually_accept_conf.manually_accept_inbound_channels = true;
8384 let chanmon_cfgs = create_chanmon_cfgs(2);
8385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8387 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8389 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8390 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8392 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8394 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8395 // rejecting the inbound channel request.
8396 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8398 let events = nodes[1].node.get_and_clear_pending_events();
8400 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8401 nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8403 _ => panic!("Unexpected event"),
8406 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8407 assert_eq!(close_msg_ev.len(), 1);
8409 match close_msg_ev[0] {
8410 MessageSendEvent::HandleError { ref node_id, .. } => {
8411 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8413 _ => panic!("Unexpected event"),
8415 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8419 fn test_reject_funding_before_inbound_channel_accepted() {
8420 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8421 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8422 // the node operator before the counterparty sends a `FundingCreated` message. If a
8423 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8424 // and the channel should be closed.
8425 let mut manually_accept_conf = UserConfig::default();
8426 manually_accept_conf.manually_accept_inbound_channels = true;
8427 let chanmon_cfgs = create_chanmon_cfgs(2);
8428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8432 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8433 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8434 let temp_channel_id = res.temporary_channel_id;
8436 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8438 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8439 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8441 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8442 nodes[1].node.get_and_clear_pending_events();
8444 // Get the `AcceptChannel` message of `nodes[1]` without calling
8445 // `ChannelManager::accept_inbound_channel`, which generates a
8446 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8447 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8448 // succeed when `nodes[0]` is passed to it.
8451 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8452 let accept_chan_msg = channel.get_accept_channel_message();
8453 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8456 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8458 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8459 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8461 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8462 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8464 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8465 assert_eq!(close_msg_ev.len(), 1);
8467 let expected_err = "FundingCreated message received before the channel was accepted";
8468 match close_msg_ev[0] {
8469 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8470 assert_eq!(msg.channel_id, temp_channel_id);
8471 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8472 assert_eq!(msg.data, expected_err);
8474 _ => panic!("Unexpected event"),
8477 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8481 fn test_can_not_accept_inbound_channel_twice() {
8482 let mut manually_accept_conf = UserConfig::default();
8483 manually_accept_conf.manually_accept_inbound_channels = true;
8484 let chanmon_cfgs = create_chanmon_cfgs(2);
8485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8487 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8489 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8490 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8492 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8494 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8495 // accepting the inbound channel request.
8496 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8498 let events = nodes[1].node.get_and_clear_pending_events();
8500 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8501 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8502 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8504 Err(APIError::APIMisuseError { err }) => {
8505 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8507 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8508 Err(_) => panic!("Unexpected Error"),
8511 _ => panic!("Unexpected event"),
8514 // Ensure that the channel wasn't closed after attempting to accept it twice.
8515 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8516 assert_eq!(accept_msg_ev.len(), 1);
8518 match accept_msg_ev[0] {
8519 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8520 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8522 _ => panic!("Unexpected event"),
8527 fn test_can_not_accept_unknown_inbound_channel() {
8528 let chanmon_cfg = create_chanmon_cfgs(2);
8529 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8530 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8531 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8533 let unknown_channel_id = [0; 32];
8534 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8536 Err(APIError::ChannelUnavailable { err }) => {
8537 assert_eq!(err, "Can't accept a channel that doesn't exist");
8539 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8540 Err(_) => panic!("Unexpected Error"),
8545 fn test_simple_mpp() {
8546 // Simple test of sending a multi-path payment.
8547 let chanmon_cfgs = create_chanmon_cfgs(4);
8548 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8549 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8550 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8552 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8553 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8554 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8555 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8557 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8558 let path = route.paths[0].clone();
8559 route.paths.push(path);
8560 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8561 route.paths[0][0].short_channel_id = chan_1_id;
8562 route.paths[0][1].short_channel_id = chan_3_id;
8563 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8564 route.paths[1][0].short_channel_id = chan_2_id;
8565 route.paths[1][1].short_channel_id = chan_4_id;
8566 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8567 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8571 fn test_preimage_storage() {
8572 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8573 let chanmon_cfgs = create_chanmon_cfgs(2);
8574 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8575 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8576 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8578 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8581 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8582 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8583 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8584 check_added_monitors!(nodes[0], 1);
8585 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8586 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8587 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8588 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8590 // Note that after leaving the above scope we have no knowledge of any arguments or return
8591 // values from previous calls.
8592 expect_pending_htlcs_forwardable!(nodes[1]);
8593 let events = nodes[1].node.get_and_clear_pending_events();
8594 assert_eq!(events.len(), 1);
8596 Event::PaymentReceived { ref purpose, .. } => {
8598 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8599 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8601 _ => panic!("expected PaymentPurpose::InvoicePayment")
8604 _ => panic!("Unexpected event"),
8609 #[allow(deprecated)]
8610 fn test_secret_timeout() {
8611 // Simple test of payment secret storage time outs. After
8612 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8613 let chanmon_cfgs = create_chanmon_cfgs(2);
8614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8616 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8618 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8620 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8622 // We should fail to register the same payment hash twice, at least until we've connected a
8623 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8624 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8625 assert_eq!(err, "Duplicate payment hash");
8626 } else { panic!(); }
8628 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8630 header: BlockHeader {
8632 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8633 merkle_root: Default::default(),
8634 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8638 connect_block(&nodes[1], &block);
8639 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8640 assert_eq!(err, "Duplicate payment hash");
8641 } else { panic!(); }
8643 // If we then connect the second block, we should be able to register the same payment hash
8644 // again (this time getting a new payment secret).
8645 block.header.prev_blockhash = block.header.block_hash();
8646 block.header.time += 1;
8647 connect_block(&nodes[1], &block);
8648 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8649 assert_ne!(payment_secret_1, our_payment_secret);
8652 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8653 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8654 check_added_monitors!(nodes[0], 1);
8655 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8656 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8657 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8658 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8660 // Note that after leaving the above scope we have no knowledge of any arguments or return
8661 // values from previous calls.
8662 expect_pending_htlcs_forwardable!(nodes[1]);
8663 let events = nodes[1].node.get_and_clear_pending_events();
8664 assert_eq!(events.len(), 1);
8666 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8667 assert!(payment_preimage.is_none());
8668 assert_eq!(payment_secret, our_payment_secret);
8669 // We don't actually have the payment preimage with which to claim this payment!
8671 _ => panic!("Unexpected event"),
8676 fn test_bad_secret_hash() {
8677 // Simple test of unregistered payment hash/invalid payment secret handling
8678 let chanmon_cfgs = create_chanmon_cfgs(2);
8679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8681 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8683 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8685 let random_payment_hash = PaymentHash([42; 32]);
8686 let random_payment_secret = PaymentSecret([43; 32]);
8687 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8688 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8690 // All the below cases should end up being handled exactly identically, so we macro the
8691 // resulting events.
8692 macro_rules! handle_unknown_invalid_payment_data {
8694 check_added_monitors!(nodes[0], 1);
8695 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8696 let payment_event = SendEvent::from_event(events.pop().unwrap());
8697 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8698 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8700 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8701 // again to process the pending backwards-failure of the HTLC
8702 expect_pending_htlcs_forwardable!(nodes[1]);
8703 expect_pending_htlcs_forwardable!(nodes[1]);
8704 check_added_monitors!(nodes[1], 1);
8706 // We should fail the payment back
8707 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8708 match events.pop().unwrap() {
8709 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8710 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8711 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8713 _ => panic!("Unexpected event"),
8718 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8719 // Error data is the HTLC value (100,000) and current block height
8720 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8722 // Send a payment with the right payment hash but the wrong payment secret
8723 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8724 handle_unknown_invalid_payment_data!();
8725 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8727 // Send a payment with a random payment hash, but the right payment secret
8728 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8729 handle_unknown_invalid_payment_data!();
8730 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8732 // Send a payment with a random payment hash and random payment secret
8733 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8734 handle_unknown_invalid_payment_data!();
8735 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8739 fn test_update_err_monitor_lockdown() {
8740 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8741 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8742 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8744 // This scenario may happen in a watchtower setup, where watchtower process a block height
8745 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8746 // commitment at same time.
8748 let chanmon_cfgs = create_chanmon_cfgs(2);
8749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8751 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8753 // Create some initial channel
8754 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8755 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8757 // Rebalance the network to generate htlc in the two directions
8758 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8760 // Route a HTLC from node 0 to node 1 (but don't settle)
8761 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8763 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8764 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8765 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8766 let persister = test_utils::TestPersister::new();
8768 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8769 let mut w = test_utils::TestVecWriter(Vec::new());
8770 monitor.write(&mut w).unwrap();
8771 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8772 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8773 assert!(new_monitor == *monitor);
8774 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);
8775 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8778 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8779 let block = Block { header, txdata: vec![] };
8780 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8781 // transaction lock time requirements here.
8782 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8783 watchtower.chain_monitor.block_connected(&block, 200);
8785 // Try to update ChannelMonitor
8786 nodes[1].node.claim_funds(preimage);
8787 check_added_monitors!(nodes[1], 1);
8788 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8790 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8791 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8792 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8793 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8794 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8795 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8796 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8797 } else { assert!(false); }
8798 } else { assert!(false); };
8799 // Our local monitor is in-sync and hasn't processed yet timeout
8800 check_added_monitors!(nodes[0], 1);
8801 let events = nodes[0].node.get_and_clear_pending_events();
8802 assert_eq!(events.len(), 1);
8806 fn test_concurrent_monitor_claim() {
8807 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8808 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8809 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8810 // state N+1 confirms. Alice claims output from state N+1.
8812 let chanmon_cfgs = create_chanmon_cfgs(2);
8813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8815 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8817 // Create some initial channel
8818 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8819 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8821 // Rebalance the network to generate htlc in the two directions
8822 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8824 // Route a HTLC from node 0 to node 1 (but don't settle)
8825 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8827 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8828 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8829 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8830 let persister = test_utils::TestPersister::new();
8831 let watchtower_alice = {
8832 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8833 let mut w = test_utils::TestVecWriter(Vec::new());
8834 monitor.write(&mut w).unwrap();
8835 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8836 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8837 assert!(new_monitor == *monitor);
8838 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);
8839 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8842 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8843 let block = Block { header, txdata: vec![] };
8844 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8845 // transaction lock time requirements here.
8846 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));
8847 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8849 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8851 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8852 assert_eq!(txn.len(), 2);
8856 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8857 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8858 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8859 let persister = test_utils::TestPersister::new();
8860 let watchtower_bob = {
8861 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8862 let mut w = test_utils::TestVecWriter(Vec::new());
8863 monitor.write(&mut w).unwrap();
8864 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8865 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8866 assert!(new_monitor == *monitor);
8867 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);
8868 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8871 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8872 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8874 // Route another payment to generate another update with still previous HTLC pending
8875 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8877 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8879 check_added_monitors!(nodes[1], 1);
8881 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8882 assert_eq!(updates.update_add_htlcs.len(), 1);
8883 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8884 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8885 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8886 // Watchtower Alice should already have seen the block and reject the update
8887 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8888 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8889 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8890 } else { assert!(false); }
8891 } else { assert!(false); };
8892 // Our local monitor is in-sync and hasn't processed yet timeout
8893 check_added_monitors!(nodes[0], 1);
8895 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8896 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8897 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8899 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8902 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8903 assert_eq!(txn.len(), 2);
8904 bob_state_y = txn[0].clone();
8908 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8909 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8910 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);
8912 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8913 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8914 // the onchain detection of the HTLC output
8915 assert_eq!(htlc_txn.len(), 2);
8916 check_spends!(htlc_txn[0], bob_state_y);
8917 check_spends!(htlc_txn[1], bob_state_y);
8922 fn test_pre_lockin_no_chan_closed_update() {
8923 // Test that if a peer closes a channel in response to a funding_created message we don't
8924 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8927 // Doing so would imply a channel monitor update before the initial channel monitor
8928 // registration, violating our API guarantees.
8930 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8931 // then opening a second channel with the same funding output as the first (which is not
8932 // rejected because the first channel does not exist in the ChannelManager) and closing it
8933 // before receiving funding_signed.
8934 let chanmon_cfgs = create_chanmon_cfgs(2);
8935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8939 // Create an initial channel
8940 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8941 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8942 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8943 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8944 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8946 // Move the first channel through the funding flow...
8947 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8949 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8950 check_added_monitors!(nodes[0], 0);
8952 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8953 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8954 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8955 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8956 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8960 fn test_htlc_no_detection() {
8961 // This test is a mutation to underscore the detection logic bug we had
8962 // before #653. HTLC value routed is above the remaining balance, thus
8963 // inverting HTLC and `to_remote` output. HTLC will come second and
8964 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8965 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8966 // outputs order detection for correct spending children filtring.
8968 let chanmon_cfgs = create_chanmon_cfgs(2);
8969 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8970 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8971 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8973 // Create some initial channels
8974 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8976 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8977 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8978 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8979 assert_eq!(local_txn[0].input.len(), 1);
8980 assert_eq!(local_txn[0].output.len(), 3);
8981 check_spends!(local_txn[0], chan_1.3);
8983 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8984 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8985 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8986 // We deliberately connect the local tx twice as this should provoke a failure calling
8987 // this test before #653 fix.
8988 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);
8989 check_closed_broadcast!(nodes[0], true);
8990 check_added_monitors!(nodes[0], 1);
8991 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8992 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8994 let htlc_timeout = {
8995 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8996 assert_eq!(node_txn[1].input.len(), 1);
8997 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8998 check_spends!(node_txn[1], local_txn[0]);
9002 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9003 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9004 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9005 expect_payment_failed!(nodes[0], our_payment_hash, true);
9008 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9009 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9010 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9011 // Carol, Alice would be the upstream node, and Carol the downstream.)
9013 // Steps of the test:
9014 // 1) Alice sends a HTLC to Carol through Bob.
9015 // 2) Carol doesn't settle the HTLC.
9016 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9017 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9018 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9019 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9020 // 5) Carol release the preimage to Bob off-chain.
9021 // 6) Bob claims the offered output on the broadcasted commitment.
9022 let chanmon_cfgs = create_chanmon_cfgs(3);
9023 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9024 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9025 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9027 // Create some initial channels
9028 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9029 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9031 // Steps (1) and (2):
9032 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9033 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9035 // Check that Alice's commitment transaction now contains an output for this HTLC.
9036 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9037 check_spends!(alice_txn[0], chan_ab.3);
9038 assert_eq!(alice_txn[0].output.len(), 2);
9039 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9040 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9041 assert_eq!(alice_txn.len(), 2);
9043 // Steps (3) and (4):
9044 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9045 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9046 let mut force_closing_node = 0; // Alice force-closes
9047 let mut counterparty_node = 1; // Bob if Alice force-closes
9050 if !broadcast_alice {
9051 force_closing_node = 1;
9052 counterparty_node = 0;
9054 nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9055 check_closed_broadcast!(nodes[force_closing_node], true);
9056 check_added_monitors!(nodes[force_closing_node], 1);
9057 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9058 if go_onchain_before_fulfill {
9059 let txn_to_broadcast = match broadcast_alice {
9060 true => alice_txn.clone(),
9061 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9063 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9064 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9065 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9066 if broadcast_alice {
9067 check_closed_broadcast!(nodes[1], true);
9068 check_added_monitors!(nodes[1], 1);
9069 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9071 assert_eq!(bob_txn.len(), 1);
9072 check_spends!(bob_txn[0], chan_ab.3);
9076 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9077 // process of removing the HTLC from their commitment transactions.
9078 nodes[2].node.claim_funds(payment_preimage);
9079 check_added_monitors!(nodes[2], 1);
9080 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9082 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9083 assert!(carol_updates.update_add_htlcs.is_empty());
9084 assert!(carol_updates.update_fail_htlcs.is_empty());
9085 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9086 assert!(carol_updates.update_fee.is_none());
9087 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9089 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9090 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9091 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9092 if !go_onchain_before_fulfill && broadcast_alice {
9093 let events = nodes[1].node.get_and_clear_pending_msg_events();
9094 assert_eq!(events.len(), 1);
9096 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9097 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9099 _ => panic!("Unexpected event"),
9102 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9103 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9104 // Carol<->Bob's updated commitment transaction info.
9105 check_added_monitors!(nodes[1], 2);
9107 let events = nodes[1].node.get_and_clear_pending_msg_events();
9108 assert_eq!(events.len(), 2);
9109 let bob_revocation = match events[0] {
9110 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9111 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9114 _ => panic!("Unexpected event"),
9116 let bob_updates = match events[1] {
9117 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9118 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9121 _ => panic!("Unexpected event"),
9124 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9125 check_added_monitors!(nodes[2], 1);
9126 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9127 check_added_monitors!(nodes[2], 1);
9129 let events = nodes[2].node.get_and_clear_pending_msg_events();
9130 assert_eq!(events.len(), 1);
9131 let carol_revocation = match events[0] {
9132 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9133 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9136 _ => panic!("Unexpected event"),
9138 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9139 check_added_monitors!(nodes[1], 1);
9141 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9142 // here's where we put said channel's commitment tx on-chain.
9143 let mut txn_to_broadcast = alice_txn.clone();
9144 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9145 if !go_onchain_before_fulfill {
9146 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9147 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9148 // If Bob was the one to force-close, he will have already passed these checks earlier.
9149 if broadcast_alice {
9150 check_closed_broadcast!(nodes[1], true);
9151 check_added_monitors!(nodes[1], 1);
9152 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9154 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9155 if broadcast_alice {
9156 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9157 // new block being connected. The ChannelManager being notified triggers a monitor update,
9158 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9159 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9161 assert_eq!(bob_txn.len(), 3);
9162 check_spends!(bob_txn[1], chan_ab.3);
9164 assert_eq!(bob_txn.len(), 2);
9165 check_spends!(bob_txn[0], chan_ab.3);
9170 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9171 // broadcasted commitment transaction.
9173 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9174 if go_onchain_before_fulfill {
9175 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9176 assert_eq!(bob_txn.len(), 2);
9178 let script_weight = match broadcast_alice {
9179 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9180 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9182 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9183 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9184 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9185 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9186 if broadcast_alice && !go_onchain_before_fulfill {
9187 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9188 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9190 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9191 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9197 fn test_onchain_htlc_settlement_after_close() {
9198 do_test_onchain_htlc_settlement_after_close(true, true);
9199 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9200 do_test_onchain_htlc_settlement_after_close(true, false);
9201 do_test_onchain_htlc_settlement_after_close(false, false);
9205 fn test_duplicate_chan_id() {
9206 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9207 // already open we reject it and keep the old channel.
9209 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9210 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9211 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9212 // updating logic for the existing channel.
9213 let chanmon_cfgs = create_chanmon_cfgs(2);
9214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9216 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9218 // Create an initial channel
9219 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9220 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9221 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9222 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()));
9224 // Try to create a second channel with the same temporary_channel_id as the first and check
9225 // that it is rejected.
9226 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9228 let events = nodes[1].node.get_and_clear_pending_msg_events();
9229 assert_eq!(events.len(), 1);
9231 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9232 // Technically, at this point, nodes[1] would be justified in thinking both the
9233 // first (valid) and second (invalid) channels are closed, given they both have
9234 // the same non-temporary channel_id. However, currently we do not, so we just
9235 // move forward with it.
9236 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9237 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9239 _ => panic!("Unexpected event"),
9243 // Move the first channel through the funding flow...
9244 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9246 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9247 check_added_monitors!(nodes[0], 0);
9249 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9250 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9252 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9253 assert_eq!(added_monitors.len(), 1);
9254 assert_eq!(added_monitors[0].0, funding_output);
9255 added_monitors.clear();
9257 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9259 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9260 let channel_id = funding_outpoint.to_channel_id();
9262 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9265 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9266 // Technically this is allowed by the spec, but we don't support it and there's little reason
9267 // to. Still, it shouldn't cause any other issues.
9268 open_chan_msg.temporary_channel_id = channel_id;
9269 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9271 let events = nodes[1].node.get_and_clear_pending_msg_events();
9272 assert_eq!(events.len(), 1);
9274 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9275 // Technically, at this point, nodes[1] would be justified in thinking both
9276 // channels are closed, but currently we do not, so we just move forward with it.
9277 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9278 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9280 _ => panic!("Unexpected event"),
9284 // Now try to create a second channel which has a duplicate funding output.
9285 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9286 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9287 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9288 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()));
9289 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9291 let funding_created = {
9292 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9293 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9294 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9295 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9296 // channelmanager in a possibly nonsense state instead).
9297 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9298 let logger = test_utils::TestLogger::new();
9299 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9301 check_added_monitors!(nodes[0], 0);
9302 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9303 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9304 // still needs to be cleared here.
9305 check_added_monitors!(nodes[1], 1);
9307 // ...still, nodes[1] will reject the duplicate channel.
9309 let events = nodes[1].node.get_and_clear_pending_msg_events();
9310 assert_eq!(events.len(), 1);
9312 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9313 // Technically, at this point, nodes[1] would be justified in thinking both
9314 // channels are closed, but currently we do not, so we just move forward with it.
9315 assert_eq!(msg.channel_id, channel_id);
9316 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9318 _ => panic!("Unexpected event"),
9322 // finally, finish creating the original channel and send a payment over it to make sure
9323 // everything is functional.
9324 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9326 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9327 assert_eq!(added_monitors.len(), 1);
9328 assert_eq!(added_monitors[0].0, funding_output);
9329 added_monitors.clear();
9332 let events_4 = nodes[0].node.get_and_clear_pending_events();
9333 assert_eq!(events_4.len(), 0);
9334 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9335 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9337 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9338 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9339 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9340 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9344 fn test_error_chans_closed() {
9345 // Test that we properly handle error messages, closing appropriate channels.
9347 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9348 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9349 // we can test various edge cases around it to ensure we don't regress.
9350 let chanmon_cfgs = create_chanmon_cfgs(3);
9351 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9352 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9353 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9355 // Create some initial channels
9356 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9357 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9358 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9360 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9361 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9362 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9364 // Closing a channel from a different peer has no effect
9365 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9366 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9368 // Closing one channel doesn't impact others
9369 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9370 check_added_monitors!(nodes[0], 1);
9371 check_closed_broadcast!(nodes[0], false);
9372 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9373 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9374 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9375 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);
9376 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);
9378 // A null channel ID should close all channels
9379 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9380 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9381 check_added_monitors!(nodes[0], 2);
9382 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9383 let events = nodes[0].node.get_and_clear_pending_msg_events();
9384 assert_eq!(events.len(), 2);
9386 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9387 assert_eq!(msg.contents.flags & 2, 2);
9389 _ => panic!("Unexpected event"),
9392 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9393 assert_eq!(msg.contents.flags & 2, 2);
9395 _ => panic!("Unexpected event"),
9397 // Note that at this point users of a standard PeerHandler will end up calling
9398 // peer_disconnected with no_connection_possible set to false, duplicating the
9399 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9400 // users with their own peer handling logic. We duplicate the call here, however.
9401 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9402 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9404 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9405 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9406 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9410 fn test_invalid_funding_tx() {
9411 // Test that we properly handle invalid funding transactions sent to us from a peer.
9413 // Previously, all other major lightning implementations had failed to properly sanitize
9414 // funding transactions from their counterparties, leading to a multi-implementation critical
9415 // security vulnerability (though we always sanitized properly, we've previously had
9416 // un-released crashes in the sanitization process).
9417 let chanmon_cfgs = create_chanmon_cfgs(2);
9418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9420 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9422 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9423 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()));
9424 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()));
9426 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9427 for output in tx.output.iter_mut() {
9428 // Make the confirmed funding transaction have a bogus script_pubkey
9429 output.script_pubkey = bitcoin::Script::new();
9432 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9433 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()));
9434 check_added_monitors!(nodes[1], 1);
9436 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()));
9437 check_added_monitors!(nodes[0], 1);
9439 let events_1 = nodes[0].node.get_and_clear_pending_events();
9440 assert_eq!(events_1.len(), 0);
9442 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9443 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9444 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9446 let expected_err = "funding tx had wrong script/value or output index";
9447 confirm_transaction_at(&nodes[1], &tx, 1);
9448 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9449 check_added_monitors!(nodes[1], 1);
9450 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9451 assert_eq!(events_2.len(), 1);
9452 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9453 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9454 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9455 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9456 } else { panic!(); }
9457 } else { panic!(); }
9458 assert_eq!(nodes[1].node.list_channels().len(), 0);
9461 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9462 // In the first version of the chain::Confirm interface, after a refactor was made to not
9463 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9464 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9465 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9466 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9467 // spending transaction until height N+1 (or greater). This was due to the way
9468 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9469 // spending transaction at the height the input transaction was confirmed at, not whether we
9470 // should broadcast a spending transaction at the current height.
9471 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9472 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9473 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9474 // until we learned about an additional block.
9476 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9477 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9478 let chanmon_cfgs = create_chanmon_cfgs(3);
9479 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9480 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9481 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9482 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9484 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9485 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9486 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9487 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9488 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9490 nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9491 check_closed_broadcast!(nodes[1], true);
9492 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9493 check_added_monitors!(nodes[1], 1);
9494 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9495 assert_eq!(node_txn.len(), 1);
9497 let conf_height = nodes[1].best_block_info().1;
9498 if !test_height_before_timelock {
9499 connect_blocks(&nodes[1], 24 * 6);
9501 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9502 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9503 if test_height_before_timelock {
9504 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9505 // generate any events or broadcast any transactions
9506 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9507 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9509 // We should broadcast an HTLC transaction spending our funding transaction first
9510 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9511 assert_eq!(spending_txn.len(), 2);
9512 assert_eq!(spending_txn[0], node_txn[0]);
9513 check_spends!(spending_txn[1], node_txn[0]);
9514 // We should also generate a SpendableOutputs event with the to_self output (as its
9516 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9517 assert_eq!(descriptor_spend_txn.len(), 1);
9519 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9520 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9521 // additional block built on top of the current chain.
9522 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9523 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9524 expect_pending_htlcs_forwardable!(nodes[1]);
9525 check_added_monitors!(nodes[1], 1);
9527 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9528 assert!(updates.update_add_htlcs.is_empty());
9529 assert!(updates.update_fulfill_htlcs.is_empty());
9530 assert_eq!(updates.update_fail_htlcs.len(), 1);
9531 assert!(updates.update_fail_malformed_htlcs.is_empty());
9532 assert!(updates.update_fee.is_none());
9533 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9534 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9535 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9540 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9541 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9542 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9546 fn test_forwardable_regen() {
9547 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9548 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9550 // We test it for both payment receipt and payment forwarding.
9552 let chanmon_cfgs = create_chanmon_cfgs(3);
9553 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9554 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9555 let persister: test_utils::TestPersister;
9556 let new_chain_monitor: test_utils::TestChainMonitor;
9557 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9558 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9559 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9560 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9562 // First send a payment to nodes[1]
9563 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9564 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9565 check_added_monitors!(nodes[0], 1);
9567 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9568 assert_eq!(events.len(), 1);
9569 let payment_event = SendEvent::from_event(events.pop().unwrap());
9570 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9571 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9573 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9575 // Next send a payment which is forwarded by nodes[1]
9576 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9577 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9578 check_added_monitors!(nodes[0], 1);
9580 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9581 assert_eq!(events.len(), 1);
9582 let payment_event = SendEvent::from_event(events.pop().unwrap());
9583 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9584 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9586 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9588 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9590 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9591 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9592 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9594 let nodes_1_serialized = nodes[1].node.encode();
9595 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9596 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9597 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9598 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9600 persister = test_utils::TestPersister::new();
9601 let keys_manager = &chanmon_cfgs[1].keys_manager;
9602 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);
9603 nodes[1].chain_monitor = &new_chain_monitor;
9605 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9606 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9607 &mut chan_0_monitor_read, keys_manager).unwrap();
9608 assert!(chan_0_monitor_read.is_empty());
9609 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9610 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9611 &mut chan_1_monitor_read, keys_manager).unwrap();
9612 assert!(chan_1_monitor_read.is_empty());
9614 let mut nodes_1_read = &nodes_1_serialized[..];
9615 let (_, nodes_1_deserialized_tmp) = {
9616 let mut channel_monitors = HashMap::new();
9617 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9618 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9619 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9620 default_config: UserConfig::default(),
9622 fee_estimator: node_cfgs[1].fee_estimator,
9623 chain_monitor: nodes[1].chain_monitor,
9624 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9625 logger: nodes[1].logger,
9629 nodes_1_deserialized = nodes_1_deserialized_tmp;
9630 assert!(nodes_1_read.is_empty());
9632 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9633 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9634 nodes[1].node = &nodes_1_deserialized;
9635 check_added_monitors!(nodes[1], 2);
9637 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9638 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9639 // the commitment state.
9640 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9642 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9644 expect_pending_htlcs_forwardable!(nodes[1]);
9645 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9646 check_added_monitors!(nodes[1], 1);
9648 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9649 assert_eq!(events.len(), 1);
9650 let payment_event = SendEvent::from_event(events.pop().unwrap());
9651 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9652 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9653 expect_pending_htlcs_forwardable!(nodes[2]);
9654 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9656 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9657 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9660 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9661 let chanmon_cfgs = create_chanmon_cfgs(2);
9662 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9663 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9664 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9666 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9668 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9669 .with_features(InvoiceFeatures::known());
9670 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9672 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9675 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9676 check_added_monitors!(nodes[0], 1);
9677 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9678 assert_eq!(events.len(), 1);
9679 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9680 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9681 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9683 expect_pending_htlcs_forwardable!(nodes[1]);
9684 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9687 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9688 check_added_monitors!(nodes[0], 1);
9689 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9690 assert_eq!(events.len(), 1);
9691 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9692 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9693 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9694 // At this point, nodes[1] would notice it has too much value for the payment. It will
9695 // assume the second is a privacy attack (no longer particularly relevant
9696 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9697 // the first HTLC delivered above.
9700 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9701 nodes[1].node.process_pending_htlc_forwards();
9703 if test_for_second_fail_panic {
9704 // Now we go fail back the first HTLC from the user end.
9705 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9707 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9708 nodes[1].node.process_pending_htlc_forwards();
9710 check_added_monitors!(nodes[1], 1);
9711 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9712 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9714 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9715 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9716 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9718 let failure_events = nodes[0].node.get_and_clear_pending_events();
9719 assert_eq!(failure_events.len(), 2);
9720 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9721 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9723 // Let the second HTLC fail and claim the first
9724 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9725 nodes[1].node.process_pending_htlc_forwards();
9727 check_added_monitors!(nodes[1], 1);
9728 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9729 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9730 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9732 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9734 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9739 fn test_dup_htlc_second_fail_panic() {
9740 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9741 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9742 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9743 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9744 do_test_dup_htlc_second_rejected(true);
9748 fn test_dup_htlc_second_rejected() {
9749 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9750 // simply reject the second HTLC but are still able to claim the first HTLC.
9751 do_test_dup_htlc_second_rejected(false);
9755 fn test_inconsistent_mpp_params() {
9756 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9757 // such HTLC and allow the second to stay.
9758 let chanmon_cfgs = create_chanmon_cfgs(4);
9759 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9760 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9761 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9763 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9764 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9765 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9766 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9768 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9769 .with_features(InvoiceFeatures::known());
9770 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9771 assert_eq!(route.paths.len(), 2);
9772 route.paths.sort_by(|path_a, _| {
9773 // Sort the path so that the path through nodes[1] comes first
9774 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9775 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9777 let payment_params_opt = Some(payment_params);
9779 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9781 let cur_height = nodes[0].best_block_info().1;
9782 let payment_id = PaymentId([42; 32]);
9784 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();
9785 check_added_monitors!(nodes[0], 1);
9787 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9788 assert_eq!(events.len(), 1);
9789 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9791 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9794 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();
9795 check_added_monitors!(nodes[0], 1);
9797 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9798 assert_eq!(events.len(), 1);
9799 let payment_event = SendEvent::from_event(events.pop().unwrap());
9801 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9802 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9804 expect_pending_htlcs_forwardable!(nodes[2]);
9805 check_added_monitors!(nodes[2], 1);
9807 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9808 assert_eq!(events.len(), 1);
9809 let payment_event = SendEvent::from_event(events.pop().unwrap());
9811 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9812 check_added_monitors!(nodes[3], 0);
9813 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9815 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9816 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9817 // post-payment_secrets) and fail back the new HTLC.
9819 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9820 nodes[3].node.process_pending_htlc_forwards();
9821 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9822 nodes[3].node.process_pending_htlc_forwards();
9824 check_added_monitors!(nodes[3], 1);
9826 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9827 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9828 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9830 expect_pending_htlcs_forwardable!(nodes[2]);
9831 check_added_monitors!(nodes[2], 1);
9833 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9834 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9835 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9837 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9839 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();
9840 check_added_monitors!(nodes[0], 1);
9842 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9843 assert_eq!(events.len(), 1);
9844 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9846 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9850 fn test_keysend_payments_to_public_node() {
9851 let chanmon_cfgs = create_chanmon_cfgs(2);
9852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9856 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9857 let network_graph = nodes[0].network_graph;
9858 let payer_pubkey = nodes[0].node.get_our_node_id();
9859 let payee_pubkey = nodes[1].node.get_our_node_id();
9860 let route_params = RouteParameters {
9861 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9862 final_value_msat: 10000,
9863 final_cltv_expiry_delta: 40,
9865 let scorer = test_utils::TestScorer::with_penalty(0);
9866 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9867 let route = find_route(&payer_pubkey, &route_params, &network_graph.read_only(), None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9869 let test_preimage = PaymentPreimage([42; 32]);
9870 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9871 check_added_monitors!(nodes[0], 1);
9872 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9873 assert_eq!(events.len(), 1);
9874 let event = events.pop().unwrap();
9875 let path = vec![&nodes[1]];
9876 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9877 claim_payment(&nodes[0], &path, test_preimage);
9881 fn test_keysend_payments_to_private_node() {
9882 let chanmon_cfgs = create_chanmon_cfgs(2);
9883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9885 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9887 let payer_pubkey = nodes[0].node.get_our_node_id();
9888 let payee_pubkey = nodes[1].node.get_our_node_id();
9889 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9890 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9892 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9893 let route_params = RouteParameters {
9894 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9895 final_value_msat: 10000,
9896 final_cltv_expiry_delta: 40,
9898 let network_graph = nodes[0].network_graph;
9899 let first_hops = nodes[0].node.list_usable_channels();
9900 let scorer = test_utils::TestScorer::with_penalty(0);
9901 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9902 let route = find_route(
9903 &payer_pubkey, &route_params, &network_graph.read_only(),
9904 Some(&first_hops.iter().collect::<Vec<_>>()), nodes[0].logger, &scorer, &random_seed_bytes
9907 let test_preimage = PaymentPreimage([42; 32]);
9908 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9909 check_added_monitors!(nodes[0], 1);
9910 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9911 assert_eq!(events.len(), 1);
9912 let event = events.pop().unwrap();
9913 let path = vec![&nodes[1]];
9914 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9915 claim_payment(&nodes[0], &path, test_preimage);
9919 fn test_double_partial_claim() {
9920 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9921 // time out, the sender resends only some of the MPP parts, then the user processes the
9922 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9924 let chanmon_cfgs = create_chanmon_cfgs(4);
9925 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9926 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9927 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9929 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9930 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9931 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9932 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9934 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9935 assert_eq!(route.paths.len(), 2);
9936 route.paths.sort_by(|path_a, _| {
9937 // Sort the path so that the path through nodes[1] comes first
9938 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9939 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9942 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9943 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9944 // amount of time to respond to.
9946 // Connect some blocks to time out the payment
9947 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9948 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9950 expect_pending_htlcs_forwardable!(nodes[3]);
9952 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9954 // nodes[1] now retries one of the two paths...
9955 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9956 check_added_monitors!(nodes[0], 2);
9958 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9959 assert_eq!(events.len(), 2);
9960 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9962 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9963 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9964 nodes[3].node.claim_funds(payment_preimage);
9965 check_added_monitors!(nodes[3], 0);
9966 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9969 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9970 // Test what happens if a node receives an MPP payment, claims it, but crashes before
9971 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9972 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9973 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9974 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9975 // not have the preimage tied to the still-pending HTLC.
9977 // To get to the correct state, on startup we should propagate the preimage to the
9978 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9979 // receiving the preimage without a state update.
9981 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9982 // definitely claimed.
9983 let chanmon_cfgs = create_chanmon_cfgs(4);
9984 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9985 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9987 let persister: test_utils::TestPersister;
9988 let new_chain_monitor: test_utils::TestChainMonitor;
9989 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9991 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9993 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9994 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9995 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9996 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9998 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9999 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10000 assert_eq!(route.paths.len(), 2);
10001 route.paths.sort_by(|path_a, _| {
10002 // Sort the path so that the path through nodes[1] comes first
10003 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10004 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10007 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10008 check_added_monitors!(nodes[0], 2);
10010 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10011 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10012 assert_eq!(send_events.len(), 2);
10013 do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
10014 do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
10016 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10017 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10018 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10019 if !persist_both_monitors {
10020 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10021 if outpoint.to_channel_id() == chan_id_not_persisted {
10022 assert!(original_monitor.0.is_empty());
10023 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10028 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10029 nodes[3].node.write(&mut original_manager).unwrap();
10031 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10033 nodes[3].node.claim_funds(payment_preimage);
10034 check_added_monitors!(nodes[3], 2);
10035 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10037 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10038 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10039 // with the old ChannelManager.
10040 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10041 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10042 if outpoint.to_channel_id() == chan_id_persisted {
10043 assert!(updated_monitor.0.is_empty());
10044 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10047 // If `persist_both_monitors` is set, get the second monitor here as well
10048 if persist_both_monitors {
10049 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10050 if outpoint.to_channel_id() == chan_id_not_persisted {
10051 assert!(original_monitor.0.is_empty());
10052 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10057 // Now restart nodes[3].
10058 persister = test_utils::TestPersister::new();
10059 let keys_manager = &chanmon_cfgs[3].keys_manager;
10060 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[3].chain_source), nodes[3].tx_broadcaster.clone(), nodes[3].logger, node_cfgs[3].fee_estimator, &persister, keys_manager);
10061 nodes[3].chain_monitor = &new_chain_monitor;
10062 let mut monitors = Vec::new();
10063 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10064 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10065 monitors.push(deserialized_monitor);
10068 let config = UserConfig::default();
10069 nodes_3_deserialized = {
10070 let mut channel_monitors = HashMap::new();
10071 for monitor in monitors.iter_mut() {
10072 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10074 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10075 default_config: config,
10077 fee_estimator: node_cfgs[3].fee_estimator,
10078 chain_monitor: nodes[3].chain_monitor,
10079 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10080 logger: nodes[3].logger,
10084 nodes[3].node = &nodes_3_deserialized;
10086 for monitor in monitors {
10087 // On startup the preimage should have been copied into the non-persisted monitor:
10088 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10089 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10091 check_added_monitors!(nodes[3], 2);
10093 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10094 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10096 // During deserialization, we should have closed one channel and broadcast its latest
10097 // commitment transaction. We should also still have the original PaymentReceived event we
10098 // never finished processing.
10099 let events = nodes[3].node.get_and_clear_pending_events();
10100 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10101 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10102 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10103 if persist_both_monitors {
10104 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10107 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10108 // ChannelManager prior to handling the original one.
10109 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10110 events[if persist_both_monitors { 3 } else { 2 }]
10112 assert_eq!(payment_hash, our_payment_hash);
10113 } else { panic!(); }
10115 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10116 if !persist_both_monitors {
10117 // If one of the two channels is still live, reveal the payment preimage over it.
10119 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10120 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10121 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10122 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10124 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10125 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10126 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10128 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10130 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10131 // claim should fly.
10132 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10133 check_added_monitors!(nodes[3], 1);
10134 assert_eq!(ds_msgs.len(), 2);
10135 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10137 let cs_updates = match ds_msgs[0] {
10138 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10139 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10140 check_added_monitors!(nodes[2], 1);
10141 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10142 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10143 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10149 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10150 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10151 expect_payment_sent!(nodes[0], payment_preimage);
10156 fn test_partial_claim_before_restart() {
10157 do_test_partial_claim_before_restart(false);
10158 do_test_partial_claim_before_restart(true);
10161 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10162 #[derive(Clone, Copy, PartialEq)]
10163 enum ExposureEvent {
10164 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10166 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10168 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10169 AtUpdateFeeOutbound,
10172 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10173 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10176 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10177 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10178 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10179 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10180 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10181 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10182 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10183 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10185 let chanmon_cfgs = create_chanmon_cfgs(2);
10186 let mut config = test_default_channel_config();
10187 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10190 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10192 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10193 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10194 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10195 open_channel.max_accepted_htlcs = 60;
10197 open_channel.dust_limit_satoshis = 546;
10199 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10200 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10201 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10203 let opt_anchors = false;
10205 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10208 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10209 chan.holder_dust_limit_satoshis = 546;
10213 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10214 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()));
10215 check_added_monitors!(nodes[1], 1);
10217 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()));
10218 check_added_monitors!(nodes[0], 1);
10220 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10221 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10222 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10224 let dust_buffer_feerate = {
10225 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10226 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10227 chan.get_dust_buffer_feerate(None) as u64
10229 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;
10230 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10232 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;
10233 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10235 let dust_htlc_on_counterparty_tx: u64 = 25;
10236 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10239 if dust_outbound_balance {
10240 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10241 // Outbound dust balance: 4372 sats
10242 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10243 for i in 0..dust_outbound_htlc_on_holder_tx {
10244 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10245 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10248 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10249 // Inbound dust balance: 4372 sats
10250 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10251 for _ in 0..dust_inbound_htlc_on_holder_tx {
10252 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10256 if dust_outbound_balance {
10257 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10258 // Outbound dust balance: 5000 sats
10259 for i in 0..dust_htlc_on_counterparty_tx {
10260 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10261 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10264 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10265 // Inbound dust balance: 5000 sats
10266 for _ in 0..dust_htlc_on_counterparty_tx {
10267 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10272 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10273 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10274 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 });
10275 let mut config = UserConfig::default();
10276 // With default dust exposure: 5000 sats
10278 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10279 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10280 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
10282 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
10284 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10285 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 });
10286 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10287 check_added_monitors!(nodes[1], 1);
10288 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10289 assert_eq!(events.len(), 1);
10290 let payment_event = SendEvent::from_event(events.remove(0));
10291 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10292 // With default dust exposure: 5000 sats
10294 // Outbound dust balance: 6399 sats
10295 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10296 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10297 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat), 1);
10299 // Outbound dust balance: 5200 sats
10300 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
10302 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10303 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10304 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10306 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10307 *feerate_lock = *feerate_lock * 10;
10309 nodes[0].node.timer_tick_occurred();
10310 check_added_monitors!(nodes[0], 1);
10311 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);
10314 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10315 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10316 added_monitors.clear();
10320 fn test_max_dust_htlc_exposure() {
10321 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10322 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10323 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10324 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10325 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10326 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10327 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10328 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10329 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10330 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10331 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10332 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10336 fn test_non_final_funding_tx() {
10337 let chanmon_cfgs = create_chanmon_cfgs(2);
10338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10340 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10342 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10343 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10344 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10345 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10346 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10348 let best_height = nodes[0].node.best_block.read().unwrap().height();
10350 let chan_id = *nodes[0].network_chan_count.borrow();
10351 let events = nodes[0].node.get_and_clear_pending_events();
10352 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10353 assert_eq!(events.len(), 1);
10354 let mut tx = match events[0] {
10355 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10356 // Timelock the transaction _beyond_ the best client height + 2.
10357 Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10358 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10361 _ => panic!("Unexpected event"),
10363 // Transaction should fail as it's evaluated as non-final for propagation.
10364 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10365 Err(APIError::APIMisuseError { err }) => {
10366 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10371 // However, transaction should be accepted if it's in a +2 headroom from best block.
10373 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10374 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());