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::chaininterface::LowerBoundedFeeEstimator;
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{BaseSign, KeysInterface};
21 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 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};
23 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
24 use ln::channel::{Channel, ChannelError};
25 use ln::{chan_utils, onion_utils};
26 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use routing::gossip::NetworkGraph;
28 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use util::errors::APIError;
36 use util::ser::{Writeable, ReadableArgs};
37 use util::config::UserConfig;
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use sync::{Arc, Mutex};
61 use ln::functional_test_utils::*;
62 use ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
179 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
180 chan.holder_selected_channel_reserve_satoshis = 0;
181 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
184 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
185 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
186 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
188 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
189 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
190 if send_from_initiator {
191 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
192 // Note that for outbound channels we have to consider the commitment tx fee and the
193 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
194 // well as an additional HTLC.
195 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
197 send_payment(&nodes[1], &[&nodes[0]], push_amt);
202 fn test_counterparty_no_reserve() {
203 do_test_counterparty_no_reserve(true);
204 do_test_counterparty_no_reserve(false);
208 fn test_async_inbound_update_fee() {
209 let chanmon_cfgs = create_chanmon_cfgs(2);
210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
212 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
213 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
216 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
220 // send (1) commitment_signed -.
221 // <- update_add_htlc/commitment_signed
222 // send (2) RAA (awaiting remote revoke) -.
223 // (1) commitment_signed is delivered ->
224 // .- send (3) RAA (awaiting remote revoke)
225 // (2) RAA is delivered ->
226 // .- send (4) commitment_signed
227 // <- (3) RAA is delivered
228 // send (5) commitment_signed -.
229 // <- (4) commitment_signed is delivered
231 // (5) commitment_signed is delivered ->
233 // (6) RAA is delivered ->
235 // First nodes[0] generates an update_fee
237 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
240 nodes[0].node.timer_tick_occurred();
241 check_added_monitors!(nodes[0], 1);
243 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244 assert_eq!(events_0.len(), 1);
245 let (update_msg, commitment_signed) = match events_0[0] { // (1)
246 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
247 (update_fee.as_ref(), commitment_signed)
249 _ => panic!("Unexpected event"),
252 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
254 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
256 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
257 check_added_monitors!(nodes[1], 1);
259 let payment_event = {
260 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261 assert_eq!(events_1.len(), 1);
262 SendEvent::from_event(events_1.remove(0))
264 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265 assert_eq!(payment_event.msgs.len(), 1);
267 // ...now when the messages get delivered everyone should be happy
268 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 // deliver(1), generate (3):
275 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
276 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
277 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
278 check_added_monitors!(nodes[1], 1);
280 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
281 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
282 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
283 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
284 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
285 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
286 assert!(bs_update.update_fee.is_none()); // (4)
287 check_added_monitors!(nodes[1], 1);
289 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
290 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
291 assert!(as_update.update_add_htlcs.is_empty()); // (5)
292 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
293 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
294 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
295 assert!(as_update.update_fee.is_none()); // (5)
296 check_added_monitors!(nodes[0], 1);
298 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
299 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
300 // only (6) so get_event_msg's assert(len == 1) passes
301 check_added_monitors!(nodes[0], 1);
303 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
304 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
305 check_added_monitors!(nodes[1], 1);
307 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
308 check_added_monitors!(nodes[0], 1);
310 let events_2 = nodes[0].node.get_and_clear_pending_events();
311 assert_eq!(events_2.len(), 1);
313 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
314 _ => panic!("Unexpected event"),
317 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
318 check_added_monitors!(nodes[1], 1);
322 fn test_update_fee_unordered_raa() {
323 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
324 // crash in an earlier version of the update_fee patch)
325 let chanmon_cfgs = create_chanmon_cfgs(2);
326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
329 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
332 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
334 // First nodes[0] generates an update_fee
336 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
339 nodes[0].node.timer_tick_occurred();
340 check_added_monitors!(nodes[0], 1);
342 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
343 assert_eq!(events_0.len(), 1);
344 let update_msg = match events_0[0] { // (1)
345 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
348 _ => panic!("Unexpected event"),
351 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
353 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
354 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
355 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
356 check_added_monitors!(nodes[1], 1);
358 let payment_event = {
359 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
360 assert_eq!(events_1.len(), 1);
361 SendEvent::from_event(events_1.remove(0))
363 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
364 assert_eq!(payment_event.msgs.len(), 1);
366 // ...now when the messages get delivered everyone should be happy
367 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
369 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
371 check_added_monitors!(nodes[0], 1);
373 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
374 check_added_monitors!(nodes[1], 1);
376 // We can't continue, sadly, because our (1) now has a bogus signature
380 fn test_multi_flight_update_fee() {
381 let chanmon_cfgs = create_chanmon_cfgs(2);
382 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
383 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
384 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
385 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
388 // update_fee/commitment_signed ->
389 // .- send (1) RAA and (2) commitment_signed
390 // update_fee (never committed) ->
392 // We have to manually generate the above update_fee, it is allowed by the protocol but we
393 // don't track which updates correspond to which revoke_and_ack responses so we're in
394 // AwaitingRAA mode and will not generate the update_fee yet.
395 // <- (1) RAA delivered
396 // (3) is generated and send (4) CS -.
397 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
398 // know the per_commitment_point to use for it.
399 // <- (2) commitment_signed delivered
401 // B should send no response here
402 // (4) commitment_signed delivered ->
403 // <- RAA/commitment_signed delivered
406 // First nodes[0] generates an update_fee
409 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
410 initial_feerate = *feerate_lock;
411 *feerate_lock = initial_feerate + 20;
413 nodes[0].node.timer_tick_occurred();
414 check_added_monitors!(nodes[0], 1);
416 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
417 assert_eq!(events_0.len(), 1);
418 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
419 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
420 (update_fee.as_ref().unwrap(), commitment_signed)
422 _ => panic!("Unexpected event"),
425 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
426 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
427 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
428 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
429 check_added_monitors!(nodes[1], 1);
431 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
434 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
435 *feerate_lock = initial_feerate + 40;
437 nodes[0].node.timer_tick_occurred();
438 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
439 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
441 // Create the (3) update_fee message that nodes[0] will generate before it does...
442 let mut update_msg_2 = msgs::UpdateFee {
443 channel_id: update_msg_1.channel_id.clone(),
444 feerate_per_kw: (initial_feerate + 30) as u32,
447 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
451 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453 // Deliver (1), generating (3) and (4)
454 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
455 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
456 check_added_monitors!(nodes[0], 1);
457 assert!(as_second_update.update_add_htlcs.is_empty());
458 assert!(as_second_update.update_fulfill_htlcs.is_empty());
459 assert!(as_second_update.update_fail_htlcs.is_empty());
460 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
461 // Check that the update_fee newly generated matches what we delivered:
462 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
463 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
465 // Deliver (2) commitment_signed
466 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
467 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
468 check_added_monitors!(nodes[0], 1);
469 // No commitment_signed so get_event_msg's assert(len == 1) passes
471 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
472 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
473 check_added_monitors!(nodes[1], 1);
476 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
477 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
478 check_added_monitors!(nodes[1], 1);
480 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
481 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
482 check_added_monitors!(nodes[0], 1);
484 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
485 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
486 // No commitment_signed so get_event_msg's assert(len == 1) passes
487 check_added_monitors!(nodes[0], 1);
489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
490 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
491 check_added_monitors!(nodes[1], 1);
494 fn do_test_sanity_on_in_flight_opens(steps: u8) {
495 // Previously, we had issues deserializing channels when we hadn't connected the first block
496 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
497 // serialization round-trips and simply do steps towards opening a channel and then drop the
500 let chanmon_cfgs = create_chanmon_cfgs(2);
501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
503 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
505 if steps & 0b1000_0000 != 0{
507 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
510 connect_block(&nodes[0], &block);
511 connect_block(&nodes[1], &block);
514 if steps & 0x0f == 0 { return; }
515 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
516 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
518 if steps & 0x0f == 1 { return; }
519 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
520 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
522 if steps & 0x0f == 2 { return; }
523 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
525 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
527 if steps & 0x0f == 3 { return; }
528 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
529 check_added_monitors!(nodes[0], 0);
530 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
532 if steps & 0x0f == 4 { return; }
533 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
535 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
536 assert_eq!(added_monitors.len(), 1);
537 assert_eq!(added_monitors[0].0, funding_output);
538 added_monitors.clear();
540 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
542 if steps & 0x0f == 5 { return; }
543 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
545 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
546 assert_eq!(added_monitors.len(), 1);
547 assert_eq!(added_monitors[0].0, funding_output);
548 added_monitors.clear();
551 let events_4 = nodes[0].node.get_and_clear_pending_events();
552 assert_eq!(events_4.len(), 0);
554 if steps & 0x0f == 6 { return; }
555 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
557 if steps & 0x0f == 7 { return; }
558 confirm_transaction_at(&nodes[0], &tx, 2);
559 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
560 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
564 fn test_sanity_on_in_flight_opens() {
565 do_test_sanity_on_in_flight_opens(0);
566 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
567 do_test_sanity_on_in_flight_opens(1);
568 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
569 do_test_sanity_on_in_flight_opens(2);
570 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(3);
572 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(4);
574 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(5);
576 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(6);
578 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(7);
580 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(8);
582 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
586 fn test_update_fee_vanilla() {
587 let chanmon_cfgs = create_chanmon_cfgs(2);
588 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
594 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
597 nodes[0].node.timer_tick_occurred();
598 check_added_monitors!(nodes[0], 1);
600 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
601 assert_eq!(events_0.len(), 1);
602 let (update_msg, commitment_signed) = match events_0[0] {
603 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
604 (update_fee.as_ref(), commitment_signed)
606 _ => panic!("Unexpected event"),
608 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
610 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
611 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
612 check_added_monitors!(nodes[1], 1);
614 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
615 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
616 check_added_monitors!(nodes[0], 1);
618 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
619 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
620 // No commitment_signed so get_event_msg's assert(len == 1) passes
621 check_added_monitors!(nodes[0], 1);
623 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
624 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
625 check_added_monitors!(nodes[1], 1);
629 fn test_update_fee_that_funder_cannot_afford() {
630 let chanmon_cfgs = create_chanmon_cfgs(2);
631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
633 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
634 let channel_value = 5000;
636 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
637 let channel_id = chan.2;
638 let secp_ctx = Secp256k1::new();
639 let default_config = UserConfig::default();
640 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
642 let opt_anchors = false;
644 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
645 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
646 // calculate two different feerates here - the expected local limit as well as the expected
648 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
649 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
651 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
652 *feerate_lock = feerate;
654 nodes[0].node.timer_tick_occurred();
655 check_added_monitors!(nodes[0], 1);
656 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
658 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
660 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
662 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
664 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
666 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
667 assert_eq!(commitment_tx.output.len(), 2);
668 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
669 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
670 actual_fee = channel_value - actual_fee;
671 assert_eq!(total_fee, actual_fee);
675 // Increment the feerate by a small constant, accounting for rounding errors
676 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
679 nodes[0].node.timer_tick_occurred();
680 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
681 check_added_monitors!(nodes[0], 0);
683 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
685 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
686 // needed to sign the new commitment tx and (2) sign the new commitment tx.
687 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
688 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
689 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
690 let chan_signer = local_chan.get_signer();
691 let pubkeys = chan_signer.pubkeys();
692 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
693 pubkeys.funding_pubkey)
695 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
696 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
697 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
698 let chan_signer = remote_chan.get_signer();
699 let pubkeys = chan_signer.pubkeys();
700 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
701 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
702 pubkeys.funding_pubkey)
705 // Assemble the set of keys we can use for signatures for our commitment_signed message.
706 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
707 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
710 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
711 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
712 let local_chan_signer = local_chan.get_signer();
713 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
714 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
715 INITIAL_COMMITMENT_NUMBER - 1,
717 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
718 opt_anchors, local_funding, remote_funding,
719 commit_tx_keys.clone(),
720 non_buffer_feerate + 4,
722 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
724 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
727 let commit_signed_msg = msgs::CommitmentSigned {
730 htlc_signatures: res.1
733 let update_fee = msgs::UpdateFee {
735 feerate_per_kw: non_buffer_feerate + 4,
738 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
740 //While producing the commitment_signed response after handling a received update_fee request the
741 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
742 //Should produce and error.
743 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
744 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
745 check_added_monitors!(nodes[1], 1);
746 check_closed_broadcast!(nodes[1], true);
747 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
751 fn test_update_fee_with_fundee_update_add_htlc() {
752 let chanmon_cfgs = create_chanmon_cfgs(2);
753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
755 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
756 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
759 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
762 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
765 nodes[0].node.timer_tick_occurred();
766 check_added_monitors!(nodes[0], 1);
768 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
769 assert_eq!(events_0.len(), 1);
770 let (update_msg, commitment_signed) = match events_0[0] {
771 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
772 (update_fee.as_ref(), commitment_signed)
774 _ => panic!("Unexpected event"),
776 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
779 check_added_monitors!(nodes[1], 1);
781 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
783 // nothing happens since node[1] is in AwaitingRemoteRevoke
784 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
786 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
787 assert_eq!(added_monitors.len(), 0);
788 added_monitors.clear();
790 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
791 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792 // node[1] has nothing to do
794 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
795 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
796 check_added_monitors!(nodes[0], 1);
798 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
799 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800 // No commitment_signed so get_event_msg's assert(len == 1) passes
801 check_added_monitors!(nodes[0], 1);
802 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803 check_added_monitors!(nodes[1], 1);
804 // AwaitingRemoteRevoke ends here
806 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
808 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
809 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
810 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
811 assert_eq!(commitment_update.update_fee.is_none(), true);
813 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
814 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
815 check_added_monitors!(nodes[0], 1);
816 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
818 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
819 check_added_monitors!(nodes[1], 1);
820 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
822 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
823 check_added_monitors!(nodes[1], 1);
824 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
825 // No commitment_signed so get_event_msg's assert(len == 1) passes
827 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
828 check_added_monitors!(nodes[0], 1);
829 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
831 expect_pending_htlcs_forwardable!(nodes[0]);
833 let events = nodes[0].node.get_and_clear_pending_events();
834 assert_eq!(events.len(), 1);
836 Event::PaymentReceived { .. } => { },
837 _ => panic!("Unexpected event"),
840 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
842 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
843 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
844 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
845 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
846 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
850 fn test_update_fee() {
851 let chanmon_cfgs = create_chanmon_cfgs(2);
852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
855 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
856 let channel_id = chan.2;
859 // (1) update_fee/commitment_signed ->
860 // <- (2) revoke_and_ack
861 // .- send (3) commitment_signed
862 // (4) update_fee/commitment_signed ->
863 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
864 // <- (3) commitment_signed delivered
865 // send (6) revoke_and_ack -.
866 // <- (5) deliver revoke_and_ack
867 // (6) deliver revoke_and_ack ->
868 // .- send (7) commitment_signed in response to (4)
869 // <- (7) deliver commitment_signed
872 // Create and deliver (1)...
875 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
876 feerate = *feerate_lock;
877 *feerate_lock = feerate + 20;
879 nodes[0].node.timer_tick_occurred();
880 check_added_monitors!(nodes[0], 1);
882 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
883 assert_eq!(events_0.len(), 1);
884 let (update_msg, commitment_signed) = match events_0[0] {
885 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
886 (update_fee.as_ref(), commitment_signed)
888 _ => panic!("Unexpected event"),
890 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
892 // Generate (2) and (3):
893 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
894 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895 check_added_monitors!(nodes[1], 1);
898 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
899 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
900 check_added_monitors!(nodes[0], 1);
902 // Create and deliver (4)...
904 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905 *feerate_lock = feerate + 30;
907 nodes[0].node.timer_tick_occurred();
908 check_added_monitors!(nodes[0], 1);
909 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
910 assert_eq!(events_0.len(), 1);
911 let (update_msg, commitment_signed) = match events_0[0] {
912 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
913 (update_fee.as_ref(), commitment_signed)
915 _ => panic!("Unexpected event"),
918 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
919 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
920 check_added_monitors!(nodes[1], 1);
922 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
923 // No commitment_signed so get_event_msg's assert(len == 1) passes
925 // Handle (3), creating (6):
926 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
927 check_added_monitors!(nodes[0], 1);
928 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
929 // No commitment_signed so get_event_msg's assert(len == 1) passes
932 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
933 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
934 check_added_monitors!(nodes[0], 1);
936 // Deliver (6), creating (7):
937 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
938 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
939 assert!(commitment_update.update_add_htlcs.is_empty());
940 assert!(commitment_update.update_fulfill_htlcs.is_empty());
941 assert!(commitment_update.update_fail_htlcs.is_empty());
942 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
943 assert!(commitment_update.update_fee.is_none());
944 check_added_monitors!(nodes[1], 1);
947 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
948 check_added_monitors!(nodes[0], 1);
949 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
950 // No commitment_signed so get_event_msg's assert(len == 1) passes
952 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
953 check_added_monitors!(nodes[1], 1);
954 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
956 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
957 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
958 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
959 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
960 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
964 fn fake_network_test() {
965 // Simple test which builds a network of ChannelManagers, connects them to each other, and
966 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
967 let chanmon_cfgs = create_chanmon_cfgs(4);
968 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
969 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
970 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
972 // Create some initial channels
973 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
974 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
975 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
977 // Rebalance the network a bit by relaying one payment through all the channels...
978 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
979 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
983 // Send some more payments
984 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
985 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
986 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
988 // Test failure packets
989 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
990 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
992 // Add a new channel that skips 3
993 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
995 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
996 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
997 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
999 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1003 // Do some rebalance loop payments, simultaneously
1004 let mut hops = Vec::with_capacity(3);
1005 hops.push(RouteHop {
1006 pubkey: nodes[2].node.get_our_node_id(),
1007 node_features: NodeFeatures::empty(),
1008 short_channel_id: chan_2.0.contents.short_channel_id,
1009 channel_features: ChannelFeatures::empty(),
1011 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1013 hops.push(RouteHop {
1014 pubkey: nodes[3].node.get_our_node_id(),
1015 node_features: NodeFeatures::empty(),
1016 short_channel_id: chan_3.0.contents.short_channel_id,
1017 channel_features: ChannelFeatures::empty(),
1019 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1021 hops.push(RouteHop {
1022 pubkey: nodes[1].node.get_our_node_id(),
1023 node_features: NodeFeatures::known(),
1024 short_channel_id: chan_4.0.contents.short_channel_id,
1025 channel_features: ChannelFeatures::known(),
1027 cltv_expiry_delta: TEST_FINAL_CLTV,
1029 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1030 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1031 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1033 let mut hops = Vec::with_capacity(3);
1034 hops.push(RouteHop {
1035 pubkey: nodes[3].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_4.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1042 hops.push(RouteHop {
1043 pubkey: nodes[2].node.get_our_node_id(),
1044 node_features: NodeFeatures::empty(),
1045 short_channel_id: chan_3.0.contents.short_channel_id,
1046 channel_features: ChannelFeatures::empty(),
1048 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1050 hops.push(RouteHop {
1051 pubkey: nodes[1].node.get_our_node_id(),
1052 node_features: NodeFeatures::known(),
1053 short_channel_id: chan_2.0.contents.short_channel_id,
1054 channel_features: ChannelFeatures::known(),
1056 cltv_expiry_delta: TEST_FINAL_CLTV,
1058 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1059 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1060 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1062 // Claim the rebalances...
1063 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1064 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1066 // Close down the channels...
1067 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1068 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1069 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1070 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1071 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1072 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1073 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1074 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1075 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1076 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1077 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1082 fn holding_cell_htlc_counting() {
1083 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1084 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1085 // commitment dance rounds.
1086 let chanmon_cfgs = create_chanmon_cfgs(3);
1087 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1088 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1089 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1090 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1091 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1093 let mut payments = Vec::new();
1094 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1095 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1096 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1097 payments.push((payment_preimage, payment_hash));
1099 check_added_monitors!(nodes[1], 1);
1101 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1102 assert_eq!(events.len(), 1);
1103 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1104 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1106 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1107 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1109 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1112 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1113 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1114 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1117 // This should also be true if we try to forward a payment.
1118 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1120 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1121 check_added_monitors!(nodes[0], 1);
1124 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1125 assert_eq!(events.len(), 1);
1126 let payment_event = SendEvent::from_event(events.pop().unwrap());
1127 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1129 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1130 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1131 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1132 // fails), the second will process the resulting failure and fail the HTLC backward.
1133 expect_pending_htlcs_forwardable!(nodes[1]);
1134 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1135 check_added_monitors!(nodes[1], 1);
1137 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1138 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1139 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1141 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1143 // Now forward all the pending HTLCs and claim them back
1144 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1145 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1146 check_added_monitors!(nodes[2], 1);
1148 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1149 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1150 check_added_monitors!(nodes[1], 1);
1151 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1153 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1154 check_added_monitors!(nodes[1], 1);
1155 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1157 for ref update in as_updates.update_add_htlcs.iter() {
1158 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1160 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1161 check_added_monitors!(nodes[2], 1);
1162 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1163 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1166 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1167 check_added_monitors!(nodes[1], 1);
1168 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169 check_added_monitors!(nodes[1], 1);
1170 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1173 check_added_monitors!(nodes[2], 1);
1175 expect_pending_htlcs_forwardable!(nodes[2]);
1177 let events = nodes[2].node.get_and_clear_pending_events();
1178 assert_eq!(events.len(), payments.len());
1179 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1181 &Event::PaymentReceived { ref payment_hash, .. } => {
1182 assert_eq!(*payment_hash, *hash);
1184 _ => panic!("Unexpected event"),
1188 for (preimage, _) in payments.drain(..) {
1189 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1192 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1196 fn duplicate_htlc_test() {
1197 // Test that we accept duplicate payment_hash HTLCs across the network and that
1198 // claiming/failing them are all separate and don't affect each other
1199 let chanmon_cfgs = create_chanmon_cfgs(6);
1200 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1201 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1202 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1204 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1205 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1206 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1207 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1208 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1209 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1211 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1213 *nodes[0].network_payment_count.borrow_mut() -= 1;
1214 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1216 *nodes[0].network_payment_count.borrow_mut() -= 1;
1217 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1219 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1220 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1221 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1225 fn test_duplicate_htlc_different_direction_onchain() {
1226 // Test that ChannelMonitor doesn't generate 2 preimage txn
1227 // when we have 2 HTLCs with same preimage that go across a node
1228 // in opposite directions, even with the same payment secret.
1229 let chanmon_cfgs = create_chanmon_cfgs(2);
1230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1232 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1234 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1237 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1239 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1241 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1242 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1243 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1245 // Provide preimage to node 0 by claiming payment
1246 nodes[0].node.claim_funds(payment_preimage);
1247 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1248 check_added_monitors!(nodes[0], 1);
1250 // Broadcast node 1 commitment txn
1251 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1253 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1254 let mut has_both_htlcs = 0; // check htlcs match ones committed
1255 for outp in remote_txn[0].output.iter() {
1256 if outp.value == 800_000 / 1000 {
1257 has_both_htlcs += 1;
1258 } else if outp.value == 900_000 / 1000 {
1259 has_both_htlcs += 1;
1262 assert_eq!(has_both_htlcs, 2);
1264 mine_transaction(&nodes[0], &remote_txn[0]);
1265 check_added_monitors!(nodes[0], 1);
1266 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1267 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1269 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1270 assert_eq!(claim_txn.len(), 8);
1272 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1274 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1275 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1277 let bump_tx = if claim_txn[1] == claim_txn[4] {
1278 assert_eq!(claim_txn[1], claim_txn[4]);
1279 assert_eq!(claim_txn[2], claim_txn[5]);
1281 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1283 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1286 assert_eq!(claim_txn[1], claim_txn[3]);
1287 assert_eq!(claim_txn[2], claim_txn[4]);
1289 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1291 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1296 assert_eq!(claim_txn[0].input.len(), 1);
1297 assert_eq!(bump_tx.input.len(), 1);
1298 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1300 assert_eq!(claim_txn[0].input.len(), 1);
1301 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1302 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1304 assert_eq!(claim_txn[6].input.len(), 1);
1305 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1306 check_spends!(claim_txn[6], remote_txn[0]);
1307 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1309 let events = nodes[0].node.get_and_clear_pending_msg_events();
1310 assert_eq!(events.len(), 3);
1313 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1314 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1315 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1316 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1318 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, .. } } => {
1319 assert!(update_add_htlcs.is_empty());
1320 assert!(update_fail_htlcs.is_empty());
1321 assert_eq!(update_fulfill_htlcs.len(), 1);
1322 assert!(update_fail_malformed_htlcs.is_empty());
1323 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1325 _ => panic!("Unexpected event"),
1331 fn test_basic_channel_reserve() {
1332 let chanmon_cfgs = create_chanmon_cfgs(2);
1333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1335 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1336 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1338 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1339 let channel_reserve = chan_stat.channel_reserve_msat;
1341 // The 2* and +1 are for the fee spike reserve.
1342 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1343 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1344 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1345 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1347 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1349 &APIError::ChannelUnavailable{ref err} =>
1350 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1351 _ => panic!("Unexpected error variant"),
1354 _ => panic!("Unexpected error variant"),
1356 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1357 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);
1359 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1363 fn test_fee_spike_violation_fails_htlc() {
1364 let chanmon_cfgs = create_chanmon_cfgs(2);
1365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1367 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1368 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1370 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1371 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1372 let secp_ctx = Secp256k1::new();
1373 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1375 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1377 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1378 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1379 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1380 let msg = msgs::UpdateAddHTLC {
1383 amount_msat: htlc_msat,
1384 payment_hash: payment_hash,
1385 cltv_expiry: htlc_cltv,
1386 onion_routing_packet: onion_packet,
1389 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1391 // Now manually create the commitment_signed message corresponding to the update_add
1392 // nodes[0] just sent. In the code for construction of this message, "local" refers
1393 // to the sender of the message, and "remote" refers to the receiver.
1395 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1397 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1399 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1400 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1401 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1402 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1403 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1404 let chan_signer = local_chan.get_signer();
1405 // Make the signer believe we validated another commitment, so we can release the secret
1406 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1408 let pubkeys = chan_signer.pubkeys();
1409 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1410 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1411 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1412 chan_signer.pubkeys().funding_pubkey)
1414 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1415 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1416 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1417 let chan_signer = remote_chan.get_signer();
1418 let pubkeys = chan_signer.pubkeys();
1419 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1420 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1421 chan_signer.pubkeys().funding_pubkey)
1424 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1425 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1426 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1428 // Build the remote commitment transaction so we can sign it, and then later use the
1429 // signature for the commitment_signed message.
1430 let local_chan_balance = 1313;
1432 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1434 amount_msat: 3460001,
1435 cltv_expiry: htlc_cltv,
1437 transaction_output_index: Some(1),
1440 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1443 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1444 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1445 let local_chan_signer = local_chan.get_signer();
1446 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1450 local_chan.opt_anchors(), local_funding, remote_funding,
1451 commit_tx_keys.clone(),
1453 &mut vec![(accepted_htlc_info, ())],
1454 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1456 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1459 let commit_signed_msg = msgs::CommitmentSigned {
1462 htlc_signatures: res.1
1465 // Send the commitment_signed message to the nodes[1].
1466 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1467 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1469 // Send the RAA to nodes[1].
1470 let raa_msg = msgs::RevokeAndACK {
1472 per_commitment_secret: local_secret,
1473 next_per_commitment_point: next_local_point
1475 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1477 let events = nodes[1].node.get_and_clear_pending_msg_events();
1478 assert_eq!(events.len(), 1);
1479 // Make sure the HTLC failed in the way we expect.
1481 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1482 assert_eq!(update_fail_htlcs.len(), 1);
1483 update_fail_htlcs[0].clone()
1485 _ => panic!("Unexpected event"),
1487 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1488 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1490 check_added_monitors!(nodes[1], 2);
1494 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1495 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1496 // Set the fee rate for the channel very high, to the point where the fundee
1497 // sending any above-dust amount would result in a channel reserve violation.
1498 // In this test we check that we would be prevented from sending an HTLC in
1500 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1503 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1504 let default_config = UserConfig::default();
1505 let opt_anchors = false;
1507 let mut push_amt = 100_000_000;
1508 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1510 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1512 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1514 // Sending exactly enough to hit the reserve amount should be accepted
1515 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1516 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1519 // However one more HTLC should be significantly over the reserve amount and fail.
1520 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1521 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1522 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1523 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1524 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);
1528 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1529 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1530 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1531 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1532 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1533 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1534 let default_config = UserConfig::default();
1535 let opt_anchors = false;
1537 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1538 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1539 // transaction fee with 0 HTLCs (183 sats)).
1540 let mut push_amt = 100_000_000;
1541 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1542 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1543 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1545 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1546 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1547 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1550 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1551 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1552 let secp_ctx = Secp256k1::new();
1553 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1554 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1555 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1556 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1557 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1558 let msg = msgs::UpdateAddHTLC {
1560 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1561 amount_msat: htlc_msat,
1562 payment_hash: payment_hash,
1563 cltv_expiry: htlc_cltv,
1564 onion_routing_packet: onion_packet,
1567 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1568 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1569 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);
1570 assert_eq!(nodes[0].node.list_channels().len(), 0);
1571 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1572 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1573 check_added_monitors!(nodes[0], 1);
1574 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() });
1578 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1579 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1580 // calculating our commitment transaction fee (this was previously broken).
1581 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1582 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1586 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1587 let default_config = UserConfig::default();
1588 let opt_anchors = false;
1590 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1591 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1592 // transaction fee with 0 HTLCs (183 sats)).
1593 let mut push_amt = 100_000_000;
1594 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1595 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1596 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1598 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1599 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1600 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1601 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1602 // commitment transaction fee.
1603 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1605 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1606 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1607 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1610 // One more than the dust amt should fail, however.
1611 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1612 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1613 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1617 fn test_chan_init_feerate_unaffordability() {
1618 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1619 // channel reserve and feerate requirements.
1620 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1621 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1624 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1625 let default_config = UserConfig::default();
1626 let opt_anchors = false;
1628 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1630 let mut push_amt = 100_000_000;
1631 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1632 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1633 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1635 // During open, we don't have a "counterparty channel reserve" to check against, so that
1636 // requirement only comes into play on the open_channel handling side.
1637 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1638 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1639 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1640 open_channel_msg.push_msat += 1;
1641 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1643 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1644 assert_eq!(msg_events.len(), 1);
1645 match msg_events[0] {
1646 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1647 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1649 _ => panic!("Unexpected event"),
1654 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1655 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1656 // calculating our counterparty's commitment transaction fee (this was previously broken).
1657 let chanmon_cfgs = create_chanmon_cfgs(2);
1658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1660 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1661 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1663 let payment_amt = 46000; // Dust amount
1664 // In the previous code, these first four payments would succeed.
1665 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1671 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1674 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1677 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1678 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1679 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1685 let chanmon_cfgs = create_chanmon_cfgs(3);
1686 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1687 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1688 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1689 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1690 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1693 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1694 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1695 let feerate = get_feerate!(nodes[0], chan.2);
1696 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1698 // Add a 2* and +1 for the fee spike reserve.
1699 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1700 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;
1701 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1703 // Add a pending HTLC.
1704 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1705 let payment_event_1 = {
1706 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1707 check_added_monitors!(nodes[0], 1);
1709 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1710 assert_eq!(events.len(), 1);
1711 SendEvent::from_event(events.remove(0))
1713 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1715 // Attempt to trigger a channel reserve violation --> payment failure.
1716 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1717 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;
1718 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1719 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1721 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1722 let secp_ctx = Secp256k1::new();
1723 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1724 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1725 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1726 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1727 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1728 let msg = msgs::UpdateAddHTLC {
1731 amount_msat: htlc_msat + 1,
1732 payment_hash: our_payment_hash_1,
1733 cltv_expiry: htlc_cltv,
1734 onion_routing_packet: onion_packet,
1737 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1738 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1739 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1740 assert_eq!(nodes[1].node.list_channels().len(), 1);
1741 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1742 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1743 check_added_monitors!(nodes[1], 1);
1744 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1748 fn test_inbound_outbound_capacity_is_not_zero() {
1749 let chanmon_cfgs = create_chanmon_cfgs(2);
1750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1754 let channels0 = node_chanmgrs[0].list_channels();
1755 let channels1 = node_chanmgrs[1].list_channels();
1756 let default_config = UserConfig::default();
1757 assert_eq!(channels0.len(), 1);
1758 assert_eq!(channels1.len(), 1);
1760 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1761 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1762 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1764 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1765 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1768 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1769 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1773 fn test_channel_reserve_holding_cell_htlcs() {
1774 let chanmon_cfgs = create_chanmon_cfgs(3);
1775 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1776 // When this test was written, the default base fee floated based on the HTLC count.
1777 // It is now fixed, so we simply set the fee to the expected value here.
1778 let mut config = test_default_channel_config();
1779 config.channel_config.forwarding_fee_base_msat = 239;
1780 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1781 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1782 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1783 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1785 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1786 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1788 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1789 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1791 macro_rules! expect_forward {
1793 let mut events = $node.node.get_and_clear_pending_msg_events();
1794 assert_eq!(events.len(), 1);
1795 check_added_monitors!($node, 1);
1796 let payment_event = SendEvent::from_event(events.remove(0));
1801 let feemsat = 239; // set above
1802 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1803 let feerate = get_feerate!(nodes[0], chan_1.2);
1804 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1806 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1808 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1810 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1811 .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1812 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1813 route.paths[0].last_mut().unwrap().fee_msat += 1;
1814 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1816 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1817 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)));
1818 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1819 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);
1822 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1823 // nodes[0]'s wealth
1825 let amt_msat = recv_value_0 + total_fee_msat;
1826 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1827 // Also, ensure that each payment has enough to be over the dust limit to
1828 // ensure it'll be included in each commit tx fee calculation.
1829 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1830 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1831 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1835 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1836 .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1837 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1838 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1839 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1841 let (stat01_, stat11_, stat12_, stat22_) = (
1842 get_channel_value_stat!(nodes[0], chan_1.2),
1843 get_channel_value_stat!(nodes[1], chan_1.2),
1844 get_channel_value_stat!(nodes[1], chan_2.2),
1845 get_channel_value_stat!(nodes[2], chan_2.2),
1848 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1849 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1850 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1851 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1852 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1855 // adding pending output.
1856 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1857 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1858 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1859 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1860 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1861 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1862 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1863 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1864 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1866 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1867 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1868 let amt_msat_1 = recv_value_1 + total_fee_msat;
1870 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);
1871 let payment_event_1 = {
1872 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1873 check_added_monitors!(nodes[0], 1);
1875 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1876 assert_eq!(events.len(), 1);
1877 SendEvent::from_event(events.remove(0))
1879 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1881 // channel reserve test with htlc pending output > 0
1882 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1884 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1885 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1886 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1887 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1890 // split the rest to test holding cell
1891 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1892 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1893 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1894 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1896 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1897 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);
1900 // now see if they go through on both sides
1901 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);
1902 // but this will stuck in the holding cell
1903 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1904 check_added_monitors!(nodes[0], 0);
1905 let events = nodes[0].node.get_and_clear_pending_events();
1906 assert_eq!(events.len(), 0);
1908 // test with outbound holding cell amount > 0
1910 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1911 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1912 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1913 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914 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);
1917 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);
1918 // this will also stuck in the holding cell
1919 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1920 check_added_monitors!(nodes[0], 0);
1921 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1922 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1924 // flush the pending htlc
1925 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1926 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1927 check_added_monitors!(nodes[1], 1);
1929 // the pending htlc should be promoted to committed
1930 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1931 check_added_monitors!(nodes[0], 1);
1932 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1934 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1935 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936 // No commitment_signed so get_event_msg's assert(len == 1) passes
1937 check_added_monitors!(nodes[0], 1);
1939 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1940 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1941 check_added_monitors!(nodes[1], 1);
1943 expect_pending_htlcs_forwardable!(nodes[1]);
1945 let ref payment_event_11 = expect_forward!(nodes[1]);
1946 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1947 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1949 expect_pending_htlcs_forwardable!(nodes[2]);
1950 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1952 // flush the htlcs in the holding cell
1953 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1954 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1955 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1956 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1957 expect_pending_htlcs_forwardable!(nodes[1]);
1959 let ref payment_event_3 = expect_forward!(nodes[1]);
1960 assert_eq!(payment_event_3.msgs.len(), 2);
1961 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1962 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1964 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1965 expect_pending_htlcs_forwardable!(nodes[2]);
1967 let events = nodes[2].node.get_and_clear_pending_events();
1968 assert_eq!(events.len(), 2);
1970 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1971 assert_eq!(our_payment_hash_21, *payment_hash);
1972 assert_eq!(recv_value_21, amount_msat);
1974 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1975 assert!(payment_preimage.is_none());
1976 assert_eq!(our_payment_secret_21, *payment_secret);
1978 _ => panic!("expected PaymentPurpose::InvoicePayment")
1981 _ => panic!("Unexpected event"),
1984 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1985 assert_eq!(our_payment_hash_22, *payment_hash);
1986 assert_eq!(recv_value_22, amount_msat);
1988 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1989 assert!(payment_preimage.is_none());
1990 assert_eq!(our_payment_secret_22, *payment_secret);
1992 _ => panic!("expected PaymentPurpose::InvoicePayment")
1995 _ => panic!("Unexpected event"),
1998 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1999 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2000 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2002 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2003 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2004 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2006 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2007 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);
2008 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2009 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2010 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2012 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2013 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2017 fn channel_reserve_in_flight_removes() {
2018 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2019 // can send to its counterparty, but due to update ordering, the other side may not yet have
2020 // considered those HTLCs fully removed.
2021 // This tests that we don't count HTLCs which will not be included in the next remote
2022 // commitment transaction towards the reserve value (as it implies no commitment transaction
2023 // will be generated which violates the remote reserve value).
2024 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2026 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2027 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2028 // you only consider the value of the first HTLC, it may not),
2029 // * start routing a third HTLC from A to B,
2030 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2031 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2032 // * deliver the first fulfill from B
2033 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2035 // * deliver A's response CS and RAA.
2036 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2037 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2038 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2039 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2040 let chanmon_cfgs = create_chanmon_cfgs(2);
2041 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2042 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2043 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2044 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2046 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2047 // Route the first two HTLCs.
2048 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2049 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2050 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2052 // Start routing the third HTLC (this is just used to get everyone in the right state).
2053 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2055 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2056 check_added_monitors!(nodes[0], 1);
2057 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2058 assert_eq!(events.len(), 1);
2059 SendEvent::from_event(events.remove(0))
2062 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2063 // initial fulfill/CS.
2064 nodes[1].node.claim_funds(payment_preimage_1);
2065 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2066 check_added_monitors!(nodes[1], 1);
2067 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2069 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2070 // remove the second HTLC when we send the HTLC back from B to A.
2071 nodes[1].node.claim_funds(payment_preimage_2);
2072 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2073 check_added_monitors!(nodes[1], 1);
2074 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2076 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2077 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2078 check_added_monitors!(nodes[0], 1);
2079 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2082 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2083 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2084 check_added_monitors!(nodes[1], 1);
2085 // B is already AwaitingRAA, so cant generate a CS here
2086 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2088 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2089 check_added_monitors!(nodes[1], 1);
2090 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2092 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2093 check_added_monitors!(nodes[0], 1);
2094 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2096 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2097 check_added_monitors!(nodes[1], 1);
2098 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2100 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2101 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2102 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2103 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2104 // on-chain as necessary).
2105 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2107 check_added_monitors!(nodes[0], 1);
2108 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2109 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2111 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2112 check_added_monitors!(nodes[1], 1);
2113 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2115 expect_pending_htlcs_forwardable!(nodes[1]);
2116 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2118 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2119 // resolve the second HTLC from A's point of view.
2120 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121 check_added_monitors!(nodes[0], 1);
2122 expect_payment_path_successful!(nodes[0]);
2123 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2125 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2126 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2127 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2129 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2130 check_added_monitors!(nodes[1], 1);
2131 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2132 assert_eq!(events.len(), 1);
2133 SendEvent::from_event(events.remove(0))
2136 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2137 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2138 check_added_monitors!(nodes[0], 1);
2139 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2141 // Now just resolve all the outstanding messages/HTLCs for completeness...
2143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144 check_added_monitors!(nodes[1], 1);
2145 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2148 check_added_monitors!(nodes[1], 1);
2150 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2151 check_added_monitors!(nodes[0], 1);
2152 expect_payment_path_successful!(nodes[0]);
2153 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2155 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2156 check_added_monitors!(nodes[1], 1);
2157 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2159 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160 check_added_monitors!(nodes[0], 1);
2162 expect_pending_htlcs_forwardable!(nodes[0]);
2163 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2165 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2166 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2170 fn channel_monitor_network_test() {
2171 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2172 // tests that ChannelMonitor is able to recover from various states.
2173 let chanmon_cfgs = create_chanmon_cfgs(5);
2174 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2175 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2176 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2178 // Create some initial channels
2179 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2180 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2181 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2182 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2184 // Make sure all nodes are at the same starting height
2185 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2186 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2187 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2188 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2189 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2191 // Rebalance the network a bit by relaying one payment through all the channels...
2192 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2197 // Simple case with no pending HTLCs:
2198 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2199 check_added_monitors!(nodes[1], 1);
2200 check_closed_broadcast!(nodes[1], true);
2202 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2203 assert_eq!(node_txn.len(), 1);
2204 mine_transaction(&nodes[0], &node_txn[0]);
2205 check_added_monitors!(nodes[0], 1);
2206 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2208 check_closed_broadcast!(nodes[0], true);
2209 assert_eq!(nodes[0].node.list_channels().len(), 0);
2210 assert_eq!(nodes[1].node.list_channels().len(), 1);
2211 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2212 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2214 // One pending HTLC is discarded by the force-close:
2215 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2217 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2218 // broadcasted until we reach the timelock time).
2219 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2220 check_closed_broadcast!(nodes[1], true);
2221 check_added_monitors!(nodes[1], 1);
2223 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2224 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2225 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2226 mine_transaction(&nodes[2], &node_txn[0]);
2227 check_added_monitors!(nodes[2], 1);
2228 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2230 check_closed_broadcast!(nodes[2], true);
2231 assert_eq!(nodes[1].node.list_channels().len(), 0);
2232 assert_eq!(nodes[2].node.list_channels().len(), 1);
2233 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2234 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2236 macro_rules! claim_funds {
2237 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2239 $node.node.claim_funds($preimage);
2240 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2241 check_added_monitors!($node, 1);
2243 let events = $node.node.get_and_clear_pending_msg_events();
2244 assert_eq!(events.len(), 1);
2246 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247 assert!(update_add_htlcs.is_empty());
2248 assert!(update_fail_htlcs.is_empty());
2249 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2251 _ => panic!("Unexpected event"),
2257 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2260 check_added_monitors!(nodes[2], 1);
2261 check_closed_broadcast!(nodes[2], true);
2262 let node2_commitment_txid;
2264 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267 node2_commitment_txid = node_txn[0].txid();
2269 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2271 mine_transaction(&nodes[3], &node_txn[0]);
2272 check_added_monitors!(nodes[3], 1);
2273 check_preimage_claim(&nodes[3], &node_txn);
2275 check_closed_broadcast!(nodes[3], true);
2276 assert_eq!(nodes[2].node.list_channels().len(), 0);
2277 assert_eq!(nodes[3].node.list_channels().len(), 1);
2278 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2281 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282 // confusing us in the following tests.
2283 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2285 // One pending HTLC to time out:
2286 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2287 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2290 let (close_chan_update_1, close_chan_update_2) = {
2291 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293 assert_eq!(events.len(), 2);
2294 let close_chan_update_1 = match events[0] {
2295 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2298 _ => panic!("Unexpected event"),
2301 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2304 _ => panic!("Unexpected event"),
2306 check_added_monitors!(nodes[3], 1);
2308 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2310 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311 node_txn.retain(|tx| {
2312 if tx.input[0].previous_output.txid == node2_commitment_txid {
2318 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2320 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2323 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325 assert_eq!(events.len(), 2);
2326 let close_chan_update_2 = match events[0] {
2327 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2330 _ => panic!("Unexpected event"),
2333 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2336 _ => panic!("Unexpected event"),
2338 check_added_monitors!(nodes[4], 1);
2339 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2341 mine_transaction(&nodes[4], &node_txn[0]);
2342 check_preimage_claim(&nodes[4], &node_txn);
2343 (close_chan_update_1, close_chan_update_2)
2345 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2346 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2347 assert_eq!(nodes[3].node.list_channels().len(), 0);
2348 assert_eq!(nodes[4].node.list_channels().len(), 0);
2350 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2351 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2352 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2356 fn test_justice_tx() {
2357 // Test justice txn built on revoked HTLC-Success tx, against both sides
2358 let mut alice_config = UserConfig::default();
2359 alice_config.channel_handshake_config.announced_channel = true;
2360 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2361 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2362 let mut bob_config = UserConfig::default();
2363 bob_config.channel_handshake_config.announced_channel = true;
2364 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2365 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2366 let user_cfgs = [Some(alice_config), Some(bob_config)];
2367 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2368 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2369 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2372 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2373 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2374 // Create some new channels:
2375 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2377 // A pending HTLC which will be revoked:
2378 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2379 // Get the will-be-revoked local txn from nodes[0]
2380 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2381 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2382 assert_eq!(revoked_local_txn[0].input.len(), 1);
2383 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2384 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2385 assert_eq!(revoked_local_txn[1].input.len(), 1);
2386 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2387 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2388 // Revoke the old state
2389 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2392 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2394 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2396 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2398 check_spends!(node_txn[0], revoked_local_txn[0]);
2399 node_txn.swap_remove(0);
2400 node_txn.truncate(1);
2402 check_added_monitors!(nodes[1], 1);
2403 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2406 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408 // Verify broadcast of revoked HTLC-timeout
2409 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410 check_added_monitors!(nodes[0], 1);
2411 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412 // Broadcast revoked HTLC-timeout on node 1
2413 mine_transaction(&nodes[1], &node_txn[1]);
2414 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2416 get_announce_close_broadcast_events(&nodes, 0, 1);
2418 assert_eq!(nodes[0].node.list_channels().len(), 0);
2419 assert_eq!(nodes[1].node.list_channels().len(), 0);
2421 // We test justice_tx build by A on B's revoked HTLC-Success tx
2422 // Create some new channels:
2423 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2425 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 // A pending HTLC which will be revoked:
2430 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431 // Get the will-be-revoked local txn from B
2432 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434 assert_eq!(revoked_local_txn[0].input.len(), 1);
2435 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437 // Revoke the old state
2438 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2440 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2442 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2444 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2446 check_spends!(node_txn[0], revoked_local_txn[0]);
2447 node_txn.swap_remove(0);
2449 check_added_monitors!(nodes[0], 1);
2450 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2452 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455 check_added_monitors!(nodes[1], 1);
2456 mine_transaction(&nodes[0], &node_txn[1]);
2457 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2460 get_announce_close_broadcast_events(&nodes, 0, 1);
2461 assert_eq!(nodes[0].node.list_channels().len(), 0);
2462 assert_eq!(nodes[1].node.list_channels().len(), 0);
2466 fn revoked_output_claim() {
2467 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468 // transaction is broadcast by its counterparty
2469 let chanmon_cfgs = create_chanmon_cfgs(2);
2470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2474 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476 assert_eq!(revoked_local_txn.len(), 1);
2477 // Only output is the full channel value back to nodes[0]:
2478 assert_eq!(revoked_local_txn[0].output.len(), 1);
2479 // Send a payment through, updating everyone's latest commitment txn
2480 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2482 // Inform nodes[1] that nodes[0] broadcast a stale tx
2483 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484 check_added_monitors!(nodes[1], 1);
2485 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2489 check_spends!(node_txn[0], revoked_local_txn[0]);
2490 check_spends!(node_txn[1], chan_1.3);
2492 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2493 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2494 get_announce_close_broadcast_events(&nodes, 0, 1);
2495 check_added_monitors!(nodes[0], 1);
2496 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2500 fn claim_htlc_outputs_shared_tx() {
2501 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2502 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2503 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2508 // Create some new channel:
2509 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2511 // Rebalance the network to generate htlc in the two directions
2512 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2513 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2514 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2515 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2517 // Get the will-be-revoked local txn from node[0]
2518 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2520 assert_eq!(revoked_local_txn[0].input.len(), 1);
2521 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2522 assert_eq!(revoked_local_txn[1].input.len(), 1);
2523 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2524 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2525 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2527 //Revoke the old state
2528 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2531 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532 check_added_monitors!(nodes[0], 1);
2533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2534 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2535 check_added_monitors!(nodes[1], 1);
2536 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2537 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2538 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2540 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2541 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2543 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2544 check_spends!(node_txn[0], revoked_local_txn[0]);
2546 let mut witness_lens = BTreeSet::new();
2547 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2548 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2549 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2550 assert_eq!(witness_lens.len(), 3);
2551 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2552 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2553 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2555 // Next nodes[1] broadcasts its current local tx state:
2556 assert_eq!(node_txn[1].input.len(), 1);
2557 check_spends!(node_txn[1], chan_1.3);
2559 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2560 // ANTI_REORG_DELAY confirmations.
2561 mine_transaction(&nodes[1], &node_txn[0]);
2562 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2563 expect_payment_failed!(nodes[1], payment_hash_2, false);
2565 get_announce_close_broadcast_events(&nodes, 0, 1);
2566 assert_eq!(nodes[0].node.list_channels().len(), 0);
2567 assert_eq!(nodes[1].node.list_channels().len(), 0);
2571 fn claim_htlc_outputs_single_tx() {
2572 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2573 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2574 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2579 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2581 // Rebalance the network to generate htlc in the two directions
2582 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2583 // 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
2584 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2585 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2586 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2588 // Get the will-be-revoked local txn from node[0]
2589 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2591 //Revoke the old state
2592 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2595 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2596 check_added_monitors!(nodes[0], 1);
2597 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2598 check_added_monitors!(nodes[1], 1);
2599 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2600 let mut events = nodes[0].node.get_and_clear_pending_events();
2601 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2602 match events.last().unwrap() {
2603 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2604 _ => panic!("Unexpected event"),
2607 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2608 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2610 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2611 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2613 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2614 assert_eq!(node_txn[0].input.len(), 1);
2615 check_spends!(node_txn[0], chan_1.3);
2616 assert_eq!(node_txn[1].input.len(), 1);
2617 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2618 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2619 check_spends!(node_txn[1], node_txn[0]);
2621 // Justice transactions are indices 1-2-4
2622 assert_eq!(node_txn[2].input.len(), 1);
2623 assert_eq!(node_txn[3].input.len(), 1);
2624 assert_eq!(node_txn[4].input.len(), 1);
2626 check_spends!(node_txn[2], revoked_local_txn[0]);
2627 check_spends!(node_txn[3], revoked_local_txn[0]);
2628 check_spends!(node_txn[4], revoked_local_txn[0]);
2630 let mut witness_lens = BTreeSet::new();
2631 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2632 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2633 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2634 assert_eq!(witness_lens.len(), 3);
2635 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2636 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2637 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2639 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2640 // ANTI_REORG_DELAY confirmations.
2641 mine_transaction(&nodes[1], &node_txn[2]);
2642 mine_transaction(&nodes[1], &node_txn[3]);
2643 mine_transaction(&nodes[1], &node_txn[4]);
2644 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2645 expect_payment_failed!(nodes[1], payment_hash_2, false);
2647 get_announce_close_broadcast_events(&nodes, 0, 1);
2648 assert_eq!(nodes[0].node.list_channels().len(), 0);
2649 assert_eq!(nodes[1].node.list_channels().len(), 0);
2653 fn test_htlc_on_chain_success() {
2654 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2655 // the preimage backward accordingly. So here we test that ChannelManager is
2656 // broadcasting the right event to other nodes in payment path.
2657 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2658 // A --------------------> B ----------------------> C (preimage)
2659 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2660 // commitment transaction was broadcast.
2661 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2663 // B should be able to claim via preimage if A then broadcasts its local tx.
2664 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2665 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2666 // PaymentSent event).
2668 let chanmon_cfgs = create_chanmon_cfgs(3);
2669 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2670 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2671 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2673 // Create some initial channels
2674 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2675 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2677 // Ensure all nodes are at the same height
2678 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2679 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2680 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2681 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2683 // Rebalance the network a bit by relaying one payment through all the channels...
2684 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2685 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2687 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2688 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2690 // Broadcast legit commitment tx from C on B's chain
2691 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2692 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2693 assert_eq!(commitment_tx.len(), 1);
2694 check_spends!(commitment_tx[0], chan_2.3);
2695 nodes[2].node.claim_funds(our_payment_preimage);
2696 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2697 nodes[2].node.claim_funds(our_payment_preimage_2);
2698 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2699 check_added_monitors!(nodes[2], 2);
2700 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2701 assert!(updates.update_add_htlcs.is_empty());
2702 assert!(updates.update_fail_htlcs.is_empty());
2703 assert!(updates.update_fail_malformed_htlcs.is_empty());
2704 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2706 mine_transaction(&nodes[2], &commitment_tx[0]);
2707 check_closed_broadcast!(nodes[2], true);
2708 check_added_monitors!(nodes[2], 1);
2709 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2710 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)
2711 assert_eq!(node_txn.len(), 5);
2712 assert_eq!(node_txn[0], node_txn[3]);
2713 assert_eq!(node_txn[1], node_txn[4]);
2714 assert_eq!(node_txn[2], commitment_tx[0]);
2715 check_spends!(node_txn[0], commitment_tx[0]);
2716 check_spends!(node_txn[1], commitment_tx[0]);
2717 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2718 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2719 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2720 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2721 assert_eq!(node_txn[0].lock_time.0, 0);
2722 assert_eq!(node_txn[1].lock_time.0, 0);
2724 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2725 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2726 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2727 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2729 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2730 assert_eq!(added_monitors.len(), 1);
2731 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2732 added_monitors.clear();
2734 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2735 assert_eq!(forwarded_events.len(), 3);
2736 match forwarded_events[0] {
2737 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2738 _ => panic!("Unexpected event"),
2740 let chan_id = Some(chan_1.2);
2741 match forwarded_events[1] {
2742 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2743 assert_eq!(fee_earned_msat, Some(1000));
2744 assert_eq!(prev_channel_id, chan_id);
2745 assert_eq!(claim_from_onchain_tx, true);
2746 assert_eq!(next_channel_id, Some(chan_2.2));
2750 match forwarded_events[2] {
2751 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2752 assert_eq!(fee_earned_msat, Some(1000));
2753 assert_eq!(prev_channel_id, chan_id);
2754 assert_eq!(claim_from_onchain_tx, true);
2755 assert_eq!(next_channel_id, Some(chan_2.2));
2759 let events = nodes[1].node.get_and_clear_pending_msg_events();
2761 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2762 assert_eq!(added_monitors.len(), 2);
2763 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2764 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2765 added_monitors.clear();
2767 assert_eq!(events.len(), 3);
2769 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2770 _ => panic!("Unexpected event"),
2773 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2774 _ => panic!("Unexpected event"),
2778 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, .. } } => {
2779 assert!(update_add_htlcs.is_empty());
2780 assert!(update_fail_htlcs.is_empty());
2781 assert_eq!(update_fulfill_htlcs.len(), 1);
2782 assert!(update_fail_malformed_htlcs.is_empty());
2783 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2785 _ => panic!("Unexpected event"),
2787 macro_rules! check_tx_local_broadcast {
2788 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2789 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2790 assert_eq!(node_txn.len(), 3);
2791 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2792 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2793 check_spends!(node_txn[1], $commitment_tx);
2794 check_spends!(node_txn[2], $commitment_tx);
2795 assert_ne!(node_txn[1].lock_time.0, 0);
2796 assert_ne!(node_txn[2].lock_time.0, 0);
2798 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2799 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2800 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2803 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2804 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2805 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2806 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2808 check_spends!(node_txn[0], $chan_tx);
2809 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2813 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2814 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2815 // timeout-claim of the output that nodes[2] just claimed via success.
2816 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2818 // Broadcast legit commitment tx from A on B's chain
2819 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2820 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2821 check_spends!(node_a_commitment_tx[0], chan_1.3);
2822 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2823 check_closed_broadcast!(nodes[1], true);
2824 check_added_monitors!(nodes[1], 1);
2825 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2826 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2827 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2828 let commitment_spend =
2829 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2830 check_spends!(node_txn[1], commitment_tx[0]);
2831 check_spends!(node_txn[2], commitment_tx[0]);
2832 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2835 check_spends!(node_txn[0], commitment_tx[0]);
2836 check_spends!(node_txn[1], commitment_tx[0]);
2837 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2841 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2842 assert_eq!(commitment_spend.input.len(), 2);
2843 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845 assert_eq!(commitment_spend.lock_time.0, 0);
2846 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2847 check_spends!(node_txn[3], chan_1.3);
2848 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2849 check_spends!(node_txn[4], node_txn[3]);
2850 check_spends!(node_txn[5], node_txn[3]);
2851 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2852 // we already checked the same situation with A.
2854 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2855 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2856 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2857 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2858 check_closed_broadcast!(nodes[0], true);
2859 check_added_monitors!(nodes[0], 1);
2860 let events = nodes[0].node.get_and_clear_pending_events();
2861 assert_eq!(events.len(), 5);
2862 let mut first_claimed = false;
2863 for event in events {
2865 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2866 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2867 assert!(!first_claimed);
2868 first_claimed = true;
2870 assert_eq!(payment_preimage, our_payment_preimage_2);
2871 assert_eq!(payment_hash, payment_hash_2);
2874 Event::PaymentPathSuccessful { .. } => {},
2875 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2876 _ => panic!("Unexpected event"),
2879 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2882 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2883 // Test that in case of a unilateral close onchain, we detect the state of output and
2884 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2885 // broadcasting the right event to other nodes in payment path.
2886 // A ------------------> B ----------------------> C (timeout)
2887 // B's commitment tx C's commitment tx
2889 // B's HTLC timeout tx B's timeout tx
2891 let chanmon_cfgs = create_chanmon_cfgs(3);
2892 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2893 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2894 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2895 *nodes[0].connect_style.borrow_mut() = connect_style;
2896 *nodes[1].connect_style.borrow_mut() = connect_style;
2897 *nodes[2].connect_style.borrow_mut() = connect_style;
2899 // Create some intial channels
2900 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2901 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2903 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2904 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2905 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2907 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2909 // Broadcast legit commitment tx from C on B's chain
2910 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2911 check_spends!(commitment_tx[0], chan_2.3);
2912 nodes[2].node.fail_htlc_backwards(&payment_hash);
2913 check_added_monitors!(nodes[2], 0);
2914 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2915 check_added_monitors!(nodes[2], 1);
2917 let events = nodes[2].node.get_and_clear_pending_msg_events();
2918 assert_eq!(events.len(), 1);
2920 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, .. } } => {
2921 assert!(update_add_htlcs.is_empty());
2922 assert!(!update_fail_htlcs.is_empty());
2923 assert!(update_fulfill_htlcs.is_empty());
2924 assert!(update_fail_malformed_htlcs.is_empty());
2925 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2927 _ => panic!("Unexpected event"),
2929 mine_transaction(&nodes[2], &commitment_tx[0]);
2930 check_closed_broadcast!(nodes[2], true);
2931 check_added_monitors!(nodes[2], 1);
2932 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2933 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2934 assert_eq!(node_txn.len(), 1);
2935 check_spends!(node_txn[0], chan_2.3);
2936 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2938 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2939 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2940 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2941 mine_transaction(&nodes[1], &commitment_tx[0]);
2942 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2945 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2946 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2947 assert_eq!(node_txn[0], node_txn[3]);
2948 assert_eq!(node_txn[1], node_txn[4]);
2950 check_spends!(node_txn[2], commitment_tx[0]);
2951 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2953 check_spends!(node_txn[0], chan_2.3);
2954 check_spends!(node_txn[1], node_txn[0]);
2955 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2956 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2958 timeout_tx = node_txn[2].clone();
2962 mine_transaction(&nodes[1], &timeout_tx);
2963 check_added_monitors!(nodes[1], 1);
2964 check_closed_broadcast!(nodes[1], true);
2966 // B will rebroadcast a fee-bumped timeout transaction here.
2967 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2968 assert_eq!(node_txn.len(), 1);
2969 check_spends!(node_txn[0], commitment_tx[0]);
2972 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2974 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2975 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2976 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2977 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2978 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2979 if node_txn.len() == 1 {
2980 check_spends!(node_txn[0], chan_2.3);
2982 assert_eq!(node_txn.len(), 0);
2986 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
2987 check_added_monitors!(nodes[1], 1);
2988 let events = nodes[1].node.get_and_clear_pending_msg_events();
2989 assert_eq!(events.len(), 1);
2991 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, .. } } => {
2992 assert!(update_add_htlcs.is_empty());
2993 assert!(!update_fail_htlcs.is_empty());
2994 assert!(update_fulfill_htlcs.is_empty());
2995 assert!(update_fail_malformed_htlcs.is_empty());
2996 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2998 _ => panic!("Unexpected event"),
3001 // Broadcast legit commitment tx from B on A's chain
3002 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3003 check_spends!(commitment_tx[0], chan_1.3);
3005 mine_transaction(&nodes[0], &commitment_tx[0]);
3006 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3008 check_closed_broadcast!(nodes[0], true);
3009 check_added_monitors!(nodes[0], 1);
3010 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3011 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3012 assert_eq!(node_txn.len(), 2);
3013 check_spends!(node_txn[0], chan_1.3);
3014 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3015 check_spends!(node_txn[1], commitment_tx[0]);
3016 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3020 fn test_htlc_on_chain_timeout() {
3021 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3022 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3023 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3027 fn test_simple_commitment_revoked_fail_backward() {
3028 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3029 // and fail backward accordingly.
3031 let chanmon_cfgs = create_chanmon_cfgs(3);
3032 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3033 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3034 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3036 // Create some initial channels
3037 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3038 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3040 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3041 // Get the will-be-revoked local txn from nodes[2]
3042 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3043 // Revoke the old state
3044 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3046 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3048 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3049 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3050 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3051 check_added_monitors!(nodes[1], 1);
3052 check_closed_broadcast!(nodes[1], true);
3054 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3055 check_added_monitors!(nodes[1], 1);
3056 let events = nodes[1].node.get_and_clear_pending_msg_events();
3057 assert_eq!(events.len(), 1);
3059 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, .. } } => {
3060 assert!(update_add_htlcs.is_empty());
3061 assert_eq!(update_fail_htlcs.len(), 1);
3062 assert!(update_fulfill_htlcs.is_empty());
3063 assert!(update_fail_malformed_htlcs.is_empty());
3064 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3066 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3067 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3068 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3070 _ => panic!("Unexpected event"),
3074 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3075 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3076 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3077 // commitment transaction anymore.
3078 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3079 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3080 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3081 // technically disallowed and we should probably handle it reasonably.
3082 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3083 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3085 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3086 // commitment_signed (implying it will be in the latest remote commitment transaction).
3087 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3088 // and once they revoke the previous commitment transaction (allowing us to send a new
3089 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3090 let chanmon_cfgs = create_chanmon_cfgs(3);
3091 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3092 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3093 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3095 // Create some initial channels
3096 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3097 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3099 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 });
3100 // Get the will-be-revoked local txn from nodes[2]
3101 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3102 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3103 // Revoke the old state
3104 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3106 let value = if use_dust {
3107 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3108 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3109 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3112 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3113 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3114 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3116 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3117 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3118 check_added_monitors!(nodes[2], 1);
3119 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3120 assert!(updates.update_add_htlcs.is_empty());
3121 assert!(updates.update_fulfill_htlcs.is_empty());
3122 assert!(updates.update_fail_malformed_htlcs.is_empty());
3123 assert_eq!(updates.update_fail_htlcs.len(), 1);
3124 assert!(updates.update_fee.is_none());
3125 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3126 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3127 // Drop the last RAA from 3 -> 2
3129 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3130 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3131 check_added_monitors!(nodes[2], 1);
3132 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3133 assert!(updates.update_add_htlcs.is_empty());
3134 assert!(updates.update_fulfill_htlcs.is_empty());
3135 assert!(updates.update_fail_malformed_htlcs.is_empty());
3136 assert_eq!(updates.update_fail_htlcs.len(), 1);
3137 assert!(updates.update_fee.is_none());
3138 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3139 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3140 check_added_monitors!(nodes[1], 1);
3141 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3142 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3143 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3144 check_added_monitors!(nodes[2], 1);
3146 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3147 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3148 check_added_monitors!(nodes[2], 1);
3149 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3150 assert!(updates.update_add_htlcs.is_empty());
3151 assert!(updates.update_fulfill_htlcs.is_empty());
3152 assert!(updates.update_fail_malformed_htlcs.is_empty());
3153 assert_eq!(updates.update_fail_htlcs.len(), 1);
3154 assert!(updates.update_fee.is_none());
3155 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3156 // At this point first_payment_hash has dropped out of the latest two commitment
3157 // transactions that nodes[1] is tracking...
3158 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3159 check_added_monitors!(nodes[1], 1);
3160 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3161 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3162 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3163 check_added_monitors!(nodes[2], 1);
3165 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3166 // on nodes[2]'s RAA.
3167 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3168 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3169 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3170 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3171 check_added_monitors!(nodes[1], 0);
3174 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3175 // One monitor for the new revocation preimage, no second on as we won't generate a new
3176 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3177 check_added_monitors!(nodes[1], 1);
3178 let events = nodes[1].node.get_and_clear_pending_events();
3179 assert_eq!(events.len(), 2);
3181 Event::PendingHTLCsForwardable { .. } => { },
3182 _ => panic!("Unexpected event"),
3185 Event::HTLCHandlingFailed { .. } => { },
3186 _ => panic!("Unexpected event"),
3188 // Deliberately don't process the pending fail-back so they all fail back at once after
3189 // block connection just like the !deliver_bs_raa case
3192 let mut failed_htlcs = HashSet::new();
3193 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3195 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3196 check_added_monitors!(nodes[1], 1);
3197 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3198 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3200 let events = nodes[1].node.get_and_clear_pending_events();
3201 assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3203 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3204 _ => panic!("Unexepected event"),
3207 Event::PaymentPathFailed { ref payment_hash, .. } => {
3208 assert_eq!(*payment_hash, fourth_payment_hash);
3210 _ => panic!("Unexpected event"),
3212 if !deliver_bs_raa {
3214 Event::PaymentFailed { ref payment_hash, .. } => {
3215 assert_eq!(*payment_hash, fourth_payment_hash);
3217 _ => panic!("Unexpected event"),
3220 Event::PendingHTLCsForwardable { .. } => { },
3221 _ => panic!("Unexpected event"),
3224 nodes[1].node.process_pending_htlc_forwards();
3225 check_added_monitors!(nodes[1], 1);
3227 let events = nodes[1].node.get_and_clear_pending_msg_events();
3228 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3229 match events[if deliver_bs_raa { 1 } else { 0 }] {
3230 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3231 _ => panic!("Unexpected event"),
3233 match events[if deliver_bs_raa { 2 } else { 1 }] {
3234 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3235 assert_eq!(channel_id, chan_2.2);
3236 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3238 _ => panic!("Unexpected event"),
3242 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, .. } } => {
3243 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3244 assert_eq!(update_add_htlcs.len(), 1);
3245 assert!(update_fulfill_htlcs.is_empty());
3246 assert!(update_fail_htlcs.is_empty());
3247 assert!(update_fail_malformed_htlcs.is_empty());
3249 _ => panic!("Unexpected event"),
3252 match events[if deliver_bs_raa { 3 } else { 2 }] {
3253 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, .. } } => {
3254 assert!(update_add_htlcs.is_empty());
3255 assert_eq!(update_fail_htlcs.len(), 3);
3256 assert!(update_fulfill_htlcs.is_empty());
3257 assert!(update_fail_malformed_htlcs.is_empty());
3258 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3260 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3261 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3262 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3264 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3266 let events = nodes[0].node.get_and_clear_pending_events();
3267 assert_eq!(events.len(), 3);
3269 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3270 assert!(failed_htlcs.insert(payment_hash.0));
3271 // If we delivered B's RAA we got an unknown preimage error, not something
3272 // that we should update our routing table for.
3273 if !deliver_bs_raa {
3274 assert!(network_update.is_some());
3277 _ => panic!("Unexpected event"),
3280 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3281 assert!(failed_htlcs.insert(payment_hash.0));
3282 assert!(network_update.is_some());
3284 _ => panic!("Unexpected event"),
3287 Event::PaymentPathFailed { ref payment_hash, ref network_update, .. } => {
3288 assert!(failed_htlcs.insert(payment_hash.0));
3289 assert!(network_update.is_some());
3291 _ => panic!("Unexpected event"),
3294 _ => panic!("Unexpected event"),
3297 assert!(failed_htlcs.contains(&first_payment_hash.0));
3298 assert!(failed_htlcs.contains(&second_payment_hash.0));
3299 assert!(failed_htlcs.contains(&third_payment_hash.0));
3303 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3304 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3305 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3306 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3307 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3311 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3312 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3313 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3314 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3315 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3319 fn fail_backward_pending_htlc_upon_channel_failure() {
3320 let chanmon_cfgs = create_chanmon_cfgs(2);
3321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3323 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3324 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3326 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3328 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3329 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3330 check_added_monitors!(nodes[0], 1);
3332 let payment_event = {
3333 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3334 assert_eq!(events.len(), 1);
3335 SendEvent::from_event(events.remove(0))
3337 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3338 assert_eq!(payment_event.msgs.len(), 1);
3341 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3342 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3344 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3345 check_added_monitors!(nodes[0], 0);
3347 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3350 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3352 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3354 let secp_ctx = Secp256k1::new();
3355 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3356 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3357 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3358 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3359 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3361 // Send a 0-msat update_add_htlc to fail the channel.
3362 let update_add_htlc = msgs::UpdateAddHTLC {
3368 onion_routing_packet,
3370 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3372 let events = nodes[0].node.get_and_clear_pending_events();
3373 assert_eq!(events.len(), 2);
3374 // Check that Alice fails backward the pending HTLC from the second payment.
3376 Event::PaymentPathFailed { payment_hash, .. } => {
3377 assert_eq!(payment_hash, failed_payment_hash);
3379 _ => panic!("Unexpected event"),
3382 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3383 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3385 _ => panic!("Unexpected event {:?}", events[1]),
3387 check_closed_broadcast!(nodes[0], true);
3388 check_added_monitors!(nodes[0], 1);
3392 fn test_htlc_ignore_latest_remote_commitment() {
3393 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3394 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3395 let chanmon_cfgs = create_chanmon_cfgs(2);
3396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3399 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3401 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3402 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3403 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3404 check_closed_broadcast!(nodes[0], true);
3405 check_added_monitors!(nodes[0], 1);
3406 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3408 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3409 assert_eq!(node_txn.len(), 3);
3410 assert_eq!(node_txn[0], node_txn[1]);
3412 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3413 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3414 check_closed_broadcast!(nodes[1], true);
3415 check_added_monitors!(nodes[1], 1);
3416 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3418 // Duplicate the connect_block call since this may happen due to other listeners
3419 // registering new transactions
3420 header.prev_blockhash = header.block_hash();
3421 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3425 fn test_force_close_fail_back() {
3426 // Check which HTLCs are failed-backwards on channel force-closure
3427 let chanmon_cfgs = create_chanmon_cfgs(3);
3428 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3429 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3430 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3431 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3432 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3434 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3436 let mut payment_event = {
3437 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3438 check_added_monitors!(nodes[0], 1);
3440 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3441 assert_eq!(events.len(), 1);
3442 SendEvent::from_event(events.remove(0))
3445 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3446 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3448 expect_pending_htlcs_forwardable!(nodes[1]);
3450 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3451 assert_eq!(events_2.len(), 1);
3452 payment_event = SendEvent::from_event(events_2.remove(0));
3453 assert_eq!(payment_event.msgs.len(), 1);
3455 check_added_monitors!(nodes[1], 1);
3456 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3457 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3458 check_added_monitors!(nodes[2], 1);
3459 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3461 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3462 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3463 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3465 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3466 check_closed_broadcast!(nodes[2], true);
3467 check_added_monitors!(nodes[2], 1);
3468 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3470 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3471 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3472 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3473 // back to nodes[1] upon timeout otherwise.
3474 assert_eq!(node_txn.len(), 1);
3478 mine_transaction(&nodes[1], &tx);
3480 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3481 check_closed_broadcast!(nodes[1], true);
3482 check_added_monitors!(nodes[1], 1);
3483 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3485 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3487 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3488 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3490 mine_transaction(&nodes[2], &tx);
3491 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3492 assert_eq!(node_txn.len(), 1);
3493 assert_eq!(node_txn[0].input.len(), 1);
3494 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3495 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3496 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3498 check_spends!(node_txn[0], tx);
3502 fn test_dup_events_on_peer_disconnect() {
3503 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3504 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3505 // as we used to generate the event immediately upon receipt of the payment preimage in the
3506 // update_fulfill_htlc message.
3508 let chanmon_cfgs = create_chanmon_cfgs(2);
3509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3511 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3512 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3514 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3516 nodes[1].node.claim_funds(payment_preimage);
3517 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3518 check_added_monitors!(nodes[1], 1);
3519 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3520 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3521 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3523 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3524 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3526 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3527 expect_payment_path_successful!(nodes[0]);
3531 fn test_peer_disconnected_before_funding_broadcasted() {
3532 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3533 // before the funding transaction has been broadcasted.
3534 let chanmon_cfgs = create_chanmon_cfgs(2);
3535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3537 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3539 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3540 // broadcasted, even though it's created by `nodes[0]`.
3541 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();
3542 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3543 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3544 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3545 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3547 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3548 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3550 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3552 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3553 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3555 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3556 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3559 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3562 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3563 // disconnected before the funding transaction was broadcasted.
3564 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3565 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3567 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3568 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3572 fn test_simple_peer_disconnect() {
3573 // Test that we can reconnect when there are no lost messages
3574 let chanmon_cfgs = create_chanmon_cfgs(3);
3575 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3576 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3577 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3578 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3579 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3585 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3588 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3590 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3591 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3594 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3595 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3596 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3597 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3600 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3602 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3603 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3605 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3607 let events = nodes[0].node.get_and_clear_pending_events();
3608 assert_eq!(events.len(), 3);
3610 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3611 assert_eq!(payment_preimage, payment_preimage_3);
3612 assert_eq!(payment_hash, payment_hash_3);
3614 _ => panic!("Unexpected event"),
3617 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3618 assert_eq!(payment_hash, payment_hash_5);
3619 assert!(payment_failed_permanently);
3621 _ => panic!("Unexpected event"),
3624 Event::PaymentPathSuccessful { .. } => {},
3625 _ => panic!("Unexpected event"),
3629 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3630 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3633 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3634 // Test that we can reconnect when in-flight HTLC updates get dropped
3635 let chanmon_cfgs = create_chanmon_cfgs(2);
3636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3638 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3640 let mut as_channel_ready = None;
3641 if messages_delivered == 0 {
3642 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3643 as_channel_ready = Some(channel_ready);
3644 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3645 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3646 // it before the channel_reestablish message.
3648 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3651 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3653 let payment_event = {
3654 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3655 check_added_monitors!(nodes[0], 1);
3657 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3658 assert_eq!(events.len(), 1);
3659 SendEvent::from_event(events.remove(0))
3661 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3663 if messages_delivered < 2 {
3664 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3666 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3667 if messages_delivered >= 3 {
3668 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3669 check_added_monitors!(nodes[1], 1);
3670 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3672 if messages_delivered >= 4 {
3673 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3674 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3675 check_added_monitors!(nodes[0], 1);
3677 if messages_delivered >= 5 {
3678 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3679 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3680 // No commitment_signed so get_event_msg's assert(len == 1) passes
3681 check_added_monitors!(nodes[0], 1);
3683 if messages_delivered >= 6 {
3684 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3685 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3686 check_added_monitors!(nodes[1], 1);
3693 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3694 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3695 if messages_delivered < 3 {
3696 if simulate_broken_lnd {
3697 // lnd has a long-standing bug where they send a channel_ready prior to a
3698 // channel_reestablish if you reconnect prior to channel_ready time.
3700 // Here we simulate that behavior, delivering a channel_ready immediately on
3701 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3702 // in `reconnect_nodes` but we currently don't fail based on that.
3704 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3705 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3707 // Even if the channel_ready messages get exchanged, as long as nothing further was
3708 // received on either side, both sides will need to resend them.
3709 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3710 } else if messages_delivered == 3 {
3711 // nodes[0] still wants its RAA + commitment_signed
3712 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3713 } else if messages_delivered == 4 {
3714 // nodes[0] still wants its commitment_signed
3715 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3716 } else if messages_delivered == 5 {
3717 // nodes[1] still wants its final RAA
3718 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3719 } else if messages_delivered == 6 {
3720 // Everything was delivered...
3721 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3724 let events_1 = nodes[1].node.get_and_clear_pending_events();
3725 assert_eq!(events_1.len(), 1);
3727 Event::PendingHTLCsForwardable { .. } => { },
3728 _ => panic!("Unexpected event"),
3731 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3732 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3733 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3735 nodes[1].node.process_pending_htlc_forwards();
3737 let events_2 = nodes[1].node.get_and_clear_pending_events();
3738 assert_eq!(events_2.len(), 1);
3740 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3741 assert_eq!(payment_hash_1, *payment_hash);
3742 assert_eq!(amount_msat, 1_000_000);
3744 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3745 assert!(payment_preimage.is_none());
3746 assert_eq!(payment_secret_1, *payment_secret);
3748 _ => panic!("expected PaymentPurpose::InvoicePayment")
3751 _ => panic!("Unexpected event"),
3754 nodes[1].node.claim_funds(payment_preimage_1);
3755 check_added_monitors!(nodes[1], 1);
3756 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3758 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3759 assert_eq!(events_3.len(), 1);
3760 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3761 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3762 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3763 assert!(updates.update_add_htlcs.is_empty());
3764 assert!(updates.update_fail_htlcs.is_empty());
3765 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3766 assert!(updates.update_fail_malformed_htlcs.is_empty());
3767 assert!(updates.update_fee.is_none());
3768 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3770 _ => panic!("Unexpected event"),
3773 if messages_delivered >= 1 {
3774 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3776 let events_4 = nodes[0].node.get_and_clear_pending_events();
3777 assert_eq!(events_4.len(), 1);
3779 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3780 assert_eq!(payment_preimage_1, *payment_preimage);
3781 assert_eq!(payment_hash_1, *payment_hash);
3783 _ => panic!("Unexpected event"),
3786 if messages_delivered >= 2 {
3787 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3788 check_added_monitors!(nodes[0], 1);
3789 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3791 if messages_delivered >= 3 {
3792 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3793 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3794 check_added_monitors!(nodes[1], 1);
3796 if messages_delivered >= 4 {
3797 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3798 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3799 // No commitment_signed so get_event_msg's assert(len == 1) passes
3800 check_added_monitors!(nodes[1], 1);
3802 if messages_delivered >= 5 {
3803 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3804 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3805 check_added_monitors!(nodes[0], 1);
3812 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3813 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3814 if messages_delivered < 2 {
3815 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816 if messages_delivered < 1 {
3817 expect_payment_sent!(nodes[0], payment_preimage_1);
3819 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3821 } else if messages_delivered == 2 {
3822 // nodes[0] still wants its RAA + commitment_signed
3823 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3824 } else if messages_delivered == 3 {
3825 // nodes[0] still wants its commitment_signed
3826 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3827 } else if messages_delivered == 4 {
3828 // nodes[1] still wants its final RAA
3829 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3830 } else if messages_delivered == 5 {
3831 // Everything was delivered...
3832 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3835 if messages_delivered == 1 || messages_delivered == 2 {
3836 expect_payment_path_successful!(nodes[0]);
3839 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3840 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3841 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3843 if messages_delivered > 2 {
3844 expect_payment_path_successful!(nodes[0]);
3847 // Channel should still work fine...
3848 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3849 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3850 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3854 fn test_drop_messages_peer_disconnect_a() {
3855 do_test_drop_messages_peer_disconnect(0, true);
3856 do_test_drop_messages_peer_disconnect(0, false);
3857 do_test_drop_messages_peer_disconnect(1, false);
3858 do_test_drop_messages_peer_disconnect(2, false);
3862 fn test_drop_messages_peer_disconnect_b() {
3863 do_test_drop_messages_peer_disconnect(3, false);
3864 do_test_drop_messages_peer_disconnect(4, false);
3865 do_test_drop_messages_peer_disconnect(5, false);
3866 do_test_drop_messages_peer_disconnect(6, false);
3870 fn test_funding_peer_disconnect() {
3871 // Test that we can lock in our funding tx while disconnected
3872 let chanmon_cfgs = create_chanmon_cfgs(2);
3873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3875 let persister: test_utils::TestPersister;
3876 let new_chain_monitor: test_utils::TestChainMonitor;
3877 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3878 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3879 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3881 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3882 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3884 confirm_transaction(&nodes[0], &tx);
3885 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3886 assert!(events_1.is_empty());
3888 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3890 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3891 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3893 confirm_transaction(&nodes[1], &tx);
3894 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3895 assert!(events_2.is_empty());
3897 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3898 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3899 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3900 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3902 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3903 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3904 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3905 assert_eq!(events_3.len(), 1);
3906 let as_channel_ready = match events_3[0] {
3907 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3908 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3911 _ => panic!("Unexpected event {:?}", events_3[0]),
3914 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3915 // announcement_signatures as well as channel_update.
3916 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3917 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3918 assert_eq!(events_4.len(), 3);
3920 let bs_channel_ready = match events_4[0] {
3921 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3922 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3923 chan_id = msg.channel_id;
3926 _ => panic!("Unexpected event {:?}", events_4[0]),
3928 let bs_announcement_sigs = match events_4[1] {
3929 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3930 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3933 _ => panic!("Unexpected event {:?}", events_4[1]),
3936 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3937 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3939 _ => panic!("Unexpected event {:?}", events_4[2]),
3942 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3943 // generates a duplicative private channel_update
3944 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3945 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3946 assert_eq!(events_5.len(), 1);
3948 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3949 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3951 _ => panic!("Unexpected event {:?}", events_5[0]),
3954 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3955 // announcement_signatures.
3956 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3957 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3958 assert_eq!(events_6.len(), 1);
3959 let as_announcement_sigs = match events_6[0] {
3960 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3961 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3964 _ => panic!("Unexpected event {:?}", events_6[0]),
3967 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3968 // broadcast the channel announcement globally, as well as re-send its (now-public)
3970 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3971 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3972 assert_eq!(events_7.len(), 1);
3973 let (chan_announcement, as_update) = match events_7[0] {
3974 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3975 (msg.clone(), update_msg.clone())
3977 _ => panic!("Unexpected event {:?}", events_7[0]),
3980 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3981 // same channel_announcement.
3982 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3983 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3984 assert_eq!(events_8.len(), 1);
3985 let bs_update = match events_8[0] {
3986 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3987 assert_eq!(*msg, chan_announcement);
3990 _ => panic!("Unexpected event {:?}", events_8[0]),
3993 // Provide the channel announcement and public updates to the network graph
3994 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3995 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3996 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3998 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3999 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4000 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4002 // Check that after deserialization and reconnection we can still generate an identical
4003 // channel_announcement from the cached signatures.
4004 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4006 let nodes_0_serialized = nodes[0].node.encode();
4007 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4008 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4010 persister = test_utils::TestPersister::new();
4011 let keys_manager = &chanmon_cfgs[0].keys_manager;
4012 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);
4013 nodes[0].chain_monitor = &new_chain_monitor;
4014 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4015 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4016 &mut chan_0_monitor_read, keys_manager).unwrap();
4017 assert!(chan_0_monitor_read.is_empty());
4019 let mut nodes_0_read = &nodes_0_serialized[..];
4020 let (_, nodes_0_deserialized_tmp) = {
4021 let mut channel_monitors = HashMap::new();
4022 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4023 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4024 default_config: UserConfig::default(),
4026 fee_estimator: node_cfgs[0].fee_estimator,
4027 chain_monitor: nodes[0].chain_monitor,
4028 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4029 logger: nodes[0].logger,
4033 nodes_0_deserialized = nodes_0_deserialized_tmp;
4034 assert!(nodes_0_read.is_empty());
4036 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4037 nodes[0].node = &nodes_0_deserialized;
4038 check_added_monitors!(nodes[0], 1);
4040 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4042 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4043 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4044 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4045 let mut found_announcement = false;
4046 for event in msgs.iter() {
4048 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4049 if *msg == chan_announcement { found_announcement = true; }
4051 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4052 _ => panic!("Unexpected event"),
4055 assert!(found_announcement);
4059 fn test_channel_ready_without_best_block_updated() {
4060 // Previously, if we were offline when a funding transaction was locked in, and then we came
4061 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4062 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4063 // channel_ready immediately instead.
4064 let chanmon_cfgs = create_chanmon_cfgs(2);
4065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4067 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4068 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4070 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4072 let conf_height = nodes[0].best_block_info().1 + 1;
4073 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4074 let block_txn = [funding_tx];
4075 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4076 let conf_block_header = nodes[0].get_block_header(conf_height);
4077 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4079 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4080 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4081 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4085 fn test_drop_messages_peer_disconnect_dual_htlc() {
4086 // Test that we can handle reconnecting when both sides of a channel have pending
4087 // commitment_updates when we disconnect.
4088 let chanmon_cfgs = create_chanmon_cfgs(2);
4089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4091 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4092 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4094 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4096 // Now try to send a second payment which will fail to send
4097 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4098 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4099 check_added_monitors!(nodes[0], 1);
4101 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4102 assert_eq!(events_1.len(), 1);
4104 MessageSendEvent::UpdateHTLCs { .. } => {},
4105 _ => panic!("Unexpected event"),
4108 nodes[1].node.claim_funds(payment_preimage_1);
4109 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4110 check_added_monitors!(nodes[1], 1);
4112 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4113 assert_eq!(events_2.len(), 1);
4115 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 } } => {
4116 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4117 assert!(update_add_htlcs.is_empty());
4118 assert_eq!(update_fulfill_htlcs.len(), 1);
4119 assert!(update_fail_htlcs.is_empty());
4120 assert!(update_fail_malformed_htlcs.is_empty());
4121 assert!(update_fee.is_none());
4123 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4124 let events_3 = nodes[0].node.get_and_clear_pending_events();
4125 assert_eq!(events_3.len(), 1);
4127 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4128 assert_eq!(*payment_preimage, payment_preimage_1);
4129 assert_eq!(*payment_hash, payment_hash_1);
4131 _ => panic!("Unexpected event"),
4134 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4135 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4136 // No commitment_signed so get_event_msg's assert(len == 1) passes
4137 check_added_monitors!(nodes[0], 1);
4139 _ => panic!("Unexpected event"),
4142 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4143 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4145 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4146 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4147 assert_eq!(reestablish_1.len(), 1);
4148 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4149 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4150 assert_eq!(reestablish_2.len(), 1);
4152 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4153 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4154 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4155 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4157 assert!(as_resp.0.is_none());
4158 assert!(bs_resp.0.is_none());
4160 assert!(bs_resp.1.is_none());
4161 assert!(bs_resp.2.is_none());
4163 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4165 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4166 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4167 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4168 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4169 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4170 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4171 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4172 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4173 // No commitment_signed so get_event_msg's assert(len == 1) passes
4174 check_added_monitors!(nodes[1], 1);
4176 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4177 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4178 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4179 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4180 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4181 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4182 assert!(bs_second_commitment_signed.update_fee.is_none());
4183 check_added_monitors!(nodes[1], 1);
4185 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4186 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4187 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4188 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4189 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4190 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4191 assert!(as_commitment_signed.update_fee.is_none());
4192 check_added_monitors!(nodes[0], 1);
4194 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4195 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4196 // No commitment_signed so get_event_msg's assert(len == 1) passes
4197 check_added_monitors!(nodes[0], 1);
4199 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4200 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4201 // No commitment_signed so get_event_msg's assert(len == 1) passes
4202 check_added_monitors!(nodes[1], 1);
4204 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4205 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4206 check_added_monitors!(nodes[1], 1);
4208 expect_pending_htlcs_forwardable!(nodes[1]);
4210 let events_5 = nodes[1].node.get_and_clear_pending_events();
4211 assert_eq!(events_5.len(), 1);
4213 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4214 assert_eq!(payment_hash_2, *payment_hash);
4216 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4217 assert!(payment_preimage.is_none());
4218 assert_eq!(payment_secret_2, *payment_secret);
4220 _ => panic!("expected PaymentPurpose::InvoicePayment")
4223 _ => panic!("Unexpected event"),
4226 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4227 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4228 check_added_monitors!(nodes[0], 1);
4230 expect_payment_path_successful!(nodes[0]);
4231 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4234 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4235 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4236 // to avoid our counterparty failing the channel.
4237 let chanmon_cfgs = create_chanmon_cfgs(2);
4238 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4239 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4240 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4242 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4244 let our_payment_hash = if send_partial_mpp {
4245 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4246 // Use the utility function send_payment_along_path to send the payment with MPP data which
4247 // indicates there are more HTLCs coming.
4248 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.
4249 let payment_id = PaymentId([42; 32]);
4250 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();
4251 check_added_monitors!(nodes[0], 1);
4252 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4253 assert_eq!(events.len(), 1);
4254 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4255 // hop should *not* yet generate any PaymentReceived event(s).
4256 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4259 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4262 let mut block = Block {
4263 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4266 connect_block(&nodes[0], &block);
4267 connect_block(&nodes[1], &block);
4268 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4269 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4270 block.header.prev_blockhash = block.block_hash();
4271 connect_block(&nodes[0], &block);
4272 connect_block(&nodes[1], &block);
4275 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4277 check_added_monitors!(nodes[1], 1);
4278 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4279 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4280 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4281 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4282 assert!(htlc_timeout_updates.update_fee.is_none());
4284 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4285 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4286 // 100_000 msat as u64, followed by the height at which we failed back above
4287 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4288 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4289 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4293 fn test_htlc_timeout() {
4294 do_test_htlc_timeout(true);
4295 do_test_htlc_timeout(false);
4298 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4299 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4300 let chanmon_cfgs = create_chanmon_cfgs(3);
4301 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4302 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4303 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4304 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4305 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4307 // Make sure all nodes are at the same starting height
4308 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4309 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4310 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4312 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4313 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4315 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4317 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4318 check_added_monitors!(nodes[1], 1);
4320 // Now attempt to route a second payment, which should be placed in the holding cell
4321 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4322 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4323 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4325 check_added_monitors!(nodes[0], 1);
4326 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4327 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4328 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4329 expect_pending_htlcs_forwardable!(nodes[1]);
4331 check_added_monitors!(nodes[1], 0);
4333 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4334 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4335 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4336 connect_blocks(&nodes[1], 1);
4339 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4340 check_added_monitors!(nodes[1], 1);
4341 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4342 assert_eq!(fail_commit.len(), 1);
4343 match fail_commit[0] {
4344 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4345 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4346 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4348 _ => unreachable!(),
4350 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4352 let events = nodes[1].node.get_and_clear_pending_events();
4353 assert_eq!(events.len(), 2);
4354 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4355 assert_eq!(*payment_hash, second_payment_hash);
4356 } else { panic!("Unexpected event"); }
4357 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4358 assert_eq!(*payment_hash, second_payment_hash);
4359 } else { panic!("Unexpected event"); }
4364 fn test_holding_cell_htlc_add_timeouts() {
4365 do_test_holding_cell_htlc_add_timeouts(false);
4366 do_test_holding_cell_htlc_add_timeouts(true);
4370 fn test_no_txn_manager_serialize_deserialize() {
4371 let chanmon_cfgs = create_chanmon_cfgs(2);
4372 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4373 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4374 let logger: test_utils::TestLogger;
4375 let fee_estimator: test_utils::TestFeeEstimator;
4376 let persister: test_utils::TestPersister;
4377 let new_chain_monitor: test_utils::TestChainMonitor;
4378 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4379 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4381 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4383 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4385 let nodes_0_serialized = nodes[0].node.encode();
4386 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4387 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4388 .write(&mut chan_0_monitor_serialized).unwrap();
4390 logger = test_utils::TestLogger::new();
4391 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4392 persister = test_utils::TestPersister::new();
4393 let keys_manager = &chanmon_cfgs[0].keys_manager;
4394 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4395 nodes[0].chain_monitor = &new_chain_monitor;
4396 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4397 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4398 &mut chan_0_monitor_read, keys_manager).unwrap();
4399 assert!(chan_0_monitor_read.is_empty());
4401 let mut nodes_0_read = &nodes_0_serialized[..];
4402 let config = UserConfig::default();
4403 let (_, nodes_0_deserialized_tmp) = {
4404 let mut channel_monitors = HashMap::new();
4405 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4406 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4407 default_config: config,
4409 fee_estimator: &fee_estimator,
4410 chain_monitor: nodes[0].chain_monitor,
4411 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4416 nodes_0_deserialized = nodes_0_deserialized_tmp;
4417 assert!(nodes_0_read.is_empty());
4419 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4420 nodes[0].node = &nodes_0_deserialized;
4421 assert_eq!(nodes[0].node.list_channels().len(), 1);
4422 check_added_monitors!(nodes[0], 1);
4424 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4425 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4426 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4427 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4429 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4430 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4431 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4432 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4434 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4435 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4436 for node in nodes.iter() {
4437 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4438 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4439 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4442 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4446 fn test_manager_serialize_deserialize_events() {
4447 // This test makes sure the events field in ChannelManager survives de/serialization
4448 let chanmon_cfgs = create_chanmon_cfgs(2);
4449 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4450 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4451 let fee_estimator: test_utils::TestFeeEstimator;
4452 let persister: test_utils::TestPersister;
4453 let logger: test_utils::TestLogger;
4454 let new_chain_monitor: test_utils::TestChainMonitor;
4455 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4456 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4458 // Start creating a channel, but stop right before broadcasting the funding transaction
4459 let channel_value = 100000;
4460 let push_msat = 10001;
4461 let a_flags = InitFeatures::known();
4462 let b_flags = InitFeatures::known();
4463 let node_a = nodes.remove(0);
4464 let node_b = nodes.remove(0);
4465 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4466 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()));
4467 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()));
4469 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4471 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4472 check_added_monitors!(node_a, 0);
4474 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()));
4476 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4477 assert_eq!(added_monitors.len(), 1);
4478 assert_eq!(added_monitors[0].0, funding_output);
4479 added_monitors.clear();
4482 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4483 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4485 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4486 assert_eq!(added_monitors.len(), 1);
4487 assert_eq!(added_monitors[0].0, funding_output);
4488 added_monitors.clear();
4490 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4495 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4496 let nodes_0_serialized = nodes[0].node.encode();
4497 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4498 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4500 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4501 logger = test_utils::TestLogger::new();
4502 persister = test_utils::TestPersister::new();
4503 let keys_manager = &chanmon_cfgs[0].keys_manager;
4504 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4505 nodes[0].chain_monitor = &new_chain_monitor;
4506 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4507 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4508 &mut chan_0_monitor_read, keys_manager).unwrap();
4509 assert!(chan_0_monitor_read.is_empty());
4511 let mut nodes_0_read = &nodes_0_serialized[..];
4512 let config = UserConfig::default();
4513 let (_, nodes_0_deserialized_tmp) = {
4514 let mut channel_monitors = HashMap::new();
4515 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4516 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4517 default_config: config,
4519 fee_estimator: &fee_estimator,
4520 chain_monitor: nodes[0].chain_monitor,
4521 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4526 nodes_0_deserialized = nodes_0_deserialized_tmp;
4527 assert!(nodes_0_read.is_empty());
4529 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4531 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4532 nodes[0].node = &nodes_0_deserialized;
4534 // After deserializing, make sure the funding_transaction is still held by the channel manager
4535 let events_4 = nodes[0].node.get_and_clear_pending_events();
4536 assert_eq!(events_4.len(), 0);
4537 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4538 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4540 // Make sure the channel is functioning as though the de/serialization never happened
4541 assert_eq!(nodes[0].node.list_channels().len(), 1);
4542 check_added_monitors!(nodes[0], 1);
4544 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4545 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4546 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4547 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4549 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4550 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4551 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4552 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4554 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4555 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4556 for node in nodes.iter() {
4557 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4558 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4559 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4562 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4566 fn test_simple_manager_serialize_deserialize() {
4567 let chanmon_cfgs = create_chanmon_cfgs(2);
4568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4570 let logger: test_utils::TestLogger;
4571 let fee_estimator: test_utils::TestFeeEstimator;
4572 let persister: test_utils::TestPersister;
4573 let new_chain_monitor: test_utils::TestChainMonitor;
4574 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4576 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4578 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4579 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4583 let nodes_0_serialized = nodes[0].node.encode();
4584 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4585 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4587 logger = test_utils::TestLogger::new();
4588 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4589 persister = test_utils::TestPersister::new();
4590 let keys_manager = &chanmon_cfgs[0].keys_manager;
4591 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4592 nodes[0].chain_monitor = &new_chain_monitor;
4593 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4594 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4595 &mut chan_0_monitor_read, keys_manager).unwrap();
4596 assert!(chan_0_monitor_read.is_empty());
4598 let mut nodes_0_read = &nodes_0_serialized[..];
4599 let (_, nodes_0_deserialized_tmp) = {
4600 let mut channel_monitors = HashMap::new();
4601 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4602 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4603 default_config: UserConfig::default(),
4605 fee_estimator: &fee_estimator,
4606 chain_monitor: nodes[0].chain_monitor,
4607 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4612 nodes_0_deserialized = nodes_0_deserialized_tmp;
4613 assert!(nodes_0_read.is_empty());
4615 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4616 nodes[0].node = &nodes_0_deserialized;
4617 check_added_monitors!(nodes[0], 1);
4619 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4621 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4622 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4626 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4627 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4628 let chanmon_cfgs = create_chanmon_cfgs(4);
4629 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4630 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4631 let logger: test_utils::TestLogger;
4632 let fee_estimator: test_utils::TestFeeEstimator;
4633 let persister: test_utils::TestPersister;
4634 let new_chain_monitor: test_utils::TestChainMonitor;
4635 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4636 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4637 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4638 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4639 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4641 let mut node_0_stale_monitors_serialized = Vec::new();
4642 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4643 let mut writer = test_utils::TestVecWriter(Vec::new());
4644 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4645 node_0_stale_monitors_serialized.push(writer.0);
4648 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4650 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4651 let nodes_0_serialized = nodes[0].node.encode();
4653 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4654 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4655 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4656 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4658 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4660 let mut node_0_monitors_serialized = Vec::new();
4661 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4662 let mut writer = test_utils::TestVecWriter(Vec::new());
4663 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4664 node_0_monitors_serialized.push(writer.0);
4667 logger = test_utils::TestLogger::new();
4668 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4669 persister = test_utils::TestPersister::new();
4670 let keys_manager = &chanmon_cfgs[0].keys_manager;
4671 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4672 nodes[0].chain_monitor = &new_chain_monitor;
4675 let mut node_0_stale_monitors = Vec::new();
4676 for serialized in node_0_stale_monitors_serialized.iter() {
4677 let mut read = &serialized[..];
4678 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4679 assert!(read.is_empty());
4680 node_0_stale_monitors.push(monitor);
4683 let mut node_0_monitors = Vec::new();
4684 for serialized in node_0_monitors_serialized.iter() {
4685 let mut read = &serialized[..];
4686 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4687 assert!(read.is_empty());
4688 node_0_monitors.push(monitor);
4691 let mut nodes_0_read = &nodes_0_serialized[..];
4692 if let Err(msgs::DecodeError::InvalidValue) =
4693 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4694 default_config: UserConfig::default(),
4696 fee_estimator: &fee_estimator,
4697 chain_monitor: nodes[0].chain_monitor,
4698 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4700 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4702 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4705 let mut nodes_0_read = &nodes_0_serialized[..];
4706 let (_, nodes_0_deserialized_tmp) =
4707 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4708 default_config: UserConfig::default(),
4710 fee_estimator: &fee_estimator,
4711 chain_monitor: nodes[0].chain_monitor,
4712 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4714 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4716 nodes_0_deserialized = nodes_0_deserialized_tmp;
4717 assert!(nodes_0_read.is_empty());
4719 { // Channel close should result in a commitment tx
4720 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4721 assert_eq!(txn.len(), 1);
4722 check_spends!(txn[0], funding_tx);
4723 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4726 for monitor in node_0_monitors.drain(..) {
4727 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4728 check_added_monitors!(nodes[0], 1);
4730 nodes[0].node = &nodes_0_deserialized;
4731 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4733 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4734 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4735 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4736 //... and we can even still claim the payment!
4737 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4739 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4740 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4741 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4742 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4743 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4744 assert_eq!(msg_events.len(), 1);
4745 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4747 &ErrorAction::SendErrorMessage { ref msg } => {
4748 assert_eq!(msg.channel_id, channel_id);
4750 _ => panic!("Unexpected event!"),
4755 macro_rules! check_spendable_outputs {
4756 ($node: expr, $keysinterface: expr) => {
4758 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4759 let mut txn = Vec::new();
4760 let mut all_outputs = Vec::new();
4761 let secp_ctx = Secp256k1::new();
4762 for event in events.drain(..) {
4764 Event::SpendableOutputs { mut outputs } => {
4765 for outp in outputs.drain(..) {
4766 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4767 all_outputs.push(outp);
4770 _ => panic!("Unexpected event"),
4773 if all_outputs.len() > 1 {
4774 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) {
4784 fn test_claim_sizeable_push_msat() {
4785 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4786 let chanmon_cfgs = create_chanmon_cfgs(2);
4787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4789 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4791 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4792 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4793 check_closed_broadcast!(nodes[1], true);
4794 check_added_monitors!(nodes[1], 1);
4795 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4796 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4797 assert_eq!(node_txn.len(), 1);
4798 check_spends!(node_txn[0], chan.3);
4799 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
4801 mine_transaction(&nodes[1], &node_txn[0]);
4802 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4804 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4805 assert_eq!(spend_txn.len(), 1);
4806 assert_eq!(spend_txn[0].input.len(), 1);
4807 check_spends!(spend_txn[0], node_txn[0]);
4808 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4812 fn test_claim_on_remote_sizeable_push_msat() {
4813 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4814 // to_remote output is encumbered by a P2WPKH
4815 let chanmon_cfgs = create_chanmon_cfgs(2);
4816 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4817 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4818 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4820 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4821 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4822 check_closed_broadcast!(nodes[0], true);
4823 check_added_monitors!(nodes[0], 1);
4824 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4826 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4827 assert_eq!(node_txn.len(), 1);
4828 check_spends!(node_txn[0], chan.3);
4829 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
4831 mine_transaction(&nodes[1], &node_txn[0]);
4832 check_closed_broadcast!(nodes[1], true);
4833 check_added_monitors!(nodes[1], 1);
4834 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4835 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4837 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4838 assert_eq!(spend_txn.len(), 1);
4839 check_spends!(spend_txn[0], node_txn[0]);
4843 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4844 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4845 // to_remote output is encumbered by a P2WPKH
4847 let chanmon_cfgs = create_chanmon_cfgs(2);
4848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4850 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4852 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4853 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4854 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4855 assert_eq!(revoked_local_txn[0].input.len(), 1);
4856 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4858 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4859 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4860 check_closed_broadcast!(nodes[1], true);
4861 check_added_monitors!(nodes[1], 1);
4862 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4864 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4865 mine_transaction(&nodes[1], &node_txn[0]);
4866 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4868 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4869 assert_eq!(spend_txn.len(), 3);
4870 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4871 check_spends!(spend_txn[1], node_txn[0]);
4872 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4876 fn test_static_spendable_outputs_preimage_tx() {
4877 let chanmon_cfgs = create_chanmon_cfgs(2);
4878 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4879 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4880 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4882 // Create some initial channels
4883 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4885 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4887 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4888 assert_eq!(commitment_tx[0].input.len(), 1);
4889 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4891 // Settle A's commitment tx on B's chain
4892 nodes[1].node.claim_funds(payment_preimage);
4893 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4894 check_added_monitors!(nodes[1], 1);
4895 mine_transaction(&nodes[1], &commitment_tx[0]);
4896 check_added_monitors!(nodes[1], 1);
4897 let events = nodes[1].node.get_and_clear_pending_msg_events();
4899 MessageSendEvent::UpdateHTLCs { .. } => {},
4900 _ => panic!("Unexpected event"),
4903 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4904 _ => panic!("Unexepected event"),
4907 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4908 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4909 assert_eq!(node_txn.len(), 3);
4910 check_spends!(node_txn[0], commitment_tx[0]);
4911 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4912 check_spends!(node_txn[1], chan_1.3);
4913 check_spends!(node_txn[2], node_txn[1]);
4915 mine_transaction(&nodes[1], &node_txn[0]);
4916 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4917 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4919 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4920 assert_eq!(spend_txn.len(), 1);
4921 check_spends!(spend_txn[0], node_txn[0]);
4925 fn test_static_spendable_outputs_timeout_tx() {
4926 let chanmon_cfgs = create_chanmon_cfgs(2);
4927 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4928 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4929 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4931 // Create some initial channels
4932 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4934 // Rebalance the network a bit by relaying one payment through all the channels ...
4935 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4937 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4939 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4940 assert_eq!(commitment_tx[0].input.len(), 1);
4941 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4943 // Settle A's commitment tx on B' chain
4944 mine_transaction(&nodes[1], &commitment_tx[0]);
4945 check_added_monitors!(nodes[1], 1);
4946 let events = nodes[1].node.get_and_clear_pending_msg_events();
4948 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4949 _ => panic!("Unexpected event"),
4951 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4953 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4954 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4955 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4956 check_spends!(node_txn[0], chan_1.3.clone());
4957 check_spends!(node_txn[1], commitment_tx[0].clone());
4958 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4960 mine_transaction(&nodes[1], &node_txn[1]);
4961 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4962 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4963 expect_payment_failed!(nodes[1], our_payment_hash, false);
4965 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4966 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4967 check_spends!(spend_txn[0], commitment_tx[0]);
4968 check_spends!(spend_txn[1], node_txn[1]);
4969 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4973 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4974 let chanmon_cfgs = create_chanmon_cfgs(2);
4975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4977 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4979 // Create some initial channels
4980 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4982 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4983 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4984 assert_eq!(revoked_local_txn[0].input.len(), 1);
4985 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4987 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4989 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4990 check_closed_broadcast!(nodes[1], true);
4991 check_added_monitors!(nodes[1], 1);
4992 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4994 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4995 assert_eq!(node_txn.len(), 2);
4996 assert_eq!(node_txn[0].input.len(), 2);
4997 check_spends!(node_txn[0], revoked_local_txn[0]);
4999 mine_transaction(&nodes[1], &node_txn[0]);
5000 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5002 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5003 assert_eq!(spend_txn.len(), 1);
5004 check_spends!(spend_txn[0], node_txn[0]);
5008 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5009 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5010 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5011 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5012 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5013 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5015 // Create some initial channels
5016 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5018 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5019 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5020 assert_eq!(revoked_local_txn[0].input.len(), 1);
5021 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5023 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5025 // A will generate HTLC-Timeout from revoked commitment tx
5026 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5027 check_closed_broadcast!(nodes[0], true);
5028 check_added_monitors!(nodes[0], 1);
5029 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5030 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5032 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5033 assert_eq!(revoked_htlc_txn.len(), 2);
5034 check_spends!(revoked_htlc_txn[0], chan_1.3);
5035 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5036 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5037 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5038 assert_ne!(revoked_htlc_txn[1].lock_time.0, 0); // HTLC-Timeout
5040 // B will generate justice tx from A's revoked commitment/HTLC tx
5041 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5042 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5043 check_closed_broadcast!(nodes[1], true);
5044 check_added_monitors!(nodes[1], 1);
5045 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5047 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5048 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5049 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5050 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5051 // transactions next...
5052 assert_eq!(node_txn[0].input.len(), 3);
5053 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5055 assert_eq!(node_txn[1].input.len(), 2);
5056 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5057 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5058 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5060 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5061 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5064 assert_eq!(node_txn[2].input.len(), 1);
5065 check_spends!(node_txn[2], chan_1.3);
5067 mine_transaction(&nodes[1], &node_txn[1]);
5068 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5070 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5071 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5072 assert_eq!(spend_txn.len(), 1);
5073 assert_eq!(spend_txn[0].input.len(), 1);
5074 check_spends!(spend_txn[0], node_txn[1]);
5078 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5079 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5080 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5081 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5082 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5083 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5085 // Create some initial channels
5086 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5088 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5089 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5090 assert_eq!(revoked_local_txn[0].input.len(), 1);
5091 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5093 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5094 assert_eq!(revoked_local_txn[0].output.len(), 2);
5096 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5098 // B will generate HTLC-Success from revoked commitment tx
5099 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5100 check_closed_broadcast!(nodes[1], true);
5101 check_added_monitors!(nodes[1], 1);
5102 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5103 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5105 assert_eq!(revoked_htlc_txn.len(), 2);
5106 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5107 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5108 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5110 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5111 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5112 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5114 // A will generate justice tx from B's revoked commitment/HTLC tx
5115 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5116 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5117 check_closed_broadcast!(nodes[0], true);
5118 check_added_monitors!(nodes[0], 1);
5119 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5121 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5122 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5124 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5125 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5126 // transactions next...
5127 assert_eq!(node_txn[0].input.len(), 2);
5128 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5129 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5130 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5132 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5133 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5136 assert_eq!(node_txn[1].input.len(), 1);
5137 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5139 check_spends!(node_txn[2], chan_1.3);
5141 mine_transaction(&nodes[0], &node_txn[1]);
5142 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5144 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5145 // didn't try to generate any new transactions.
5147 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5148 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5149 assert_eq!(spend_txn.len(), 3);
5150 assert_eq!(spend_txn[0].input.len(), 1);
5151 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5152 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5153 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5154 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5158 fn test_onchain_to_onchain_claim() {
5159 // Test that in case of channel closure, we detect the state of output and claim HTLC
5160 // on downstream peer's remote commitment tx.
5161 // First, have C claim an HTLC against its own latest commitment transaction.
5162 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5164 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5167 let chanmon_cfgs = create_chanmon_cfgs(3);
5168 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5169 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5170 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5172 // Create some initial channels
5173 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5174 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5176 // Ensure all nodes are at the same height
5177 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5178 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5179 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5180 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5182 // Rebalance the network a bit by relaying one payment through all the channels ...
5183 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5184 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5186 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5187 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5188 check_spends!(commitment_tx[0], chan_2.3);
5189 nodes[2].node.claim_funds(payment_preimage);
5190 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5191 check_added_monitors!(nodes[2], 1);
5192 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5193 assert!(updates.update_add_htlcs.is_empty());
5194 assert!(updates.update_fail_htlcs.is_empty());
5195 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5196 assert!(updates.update_fail_malformed_htlcs.is_empty());
5198 mine_transaction(&nodes[2], &commitment_tx[0]);
5199 check_closed_broadcast!(nodes[2], true);
5200 check_added_monitors!(nodes[2], 1);
5201 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5203 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5204 assert_eq!(c_txn.len(), 3);
5205 assert_eq!(c_txn[0], c_txn[2]);
5206 assert_eq!(commitment_tx[0], c_txn[1]);
5207 check_spends!(c_txn[1], chan_2.3);
5208 check_spends!(c_txn[2], c_txn[1]);
5209 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5210 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5211 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5212 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
5214 // 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
5215 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
5216 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5217 check_added_monitors!(nodes[1], 1);
5218 let events = nodes[1].node.get_and_clear_pending_events();
5219 assert_eq!(events.len(), 2);
5221 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5222 _ => panic!("Unexpected event"),
5225 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5226 assert_eq!(fee_earned_msat, Some(1000));
5227 assert_eq!(prev_channel_id, Some(chan_1.2));
5228 assert_eq!(claim_from_onchain_tx, true);
5229 assert_eq!(next_channel_id, Some(chan_2.2));
5231 _ => panic!("Unexpected event"),
5234 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5235 // ChannelMonitor: claim tx
5236 assert_eq!(b_txn.len(), 1);
5237 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5240 check_added_monitors!(nodes[1], 1);
5241 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5242 assert_eq!(msg_events.len(), 3);
5243 match msg_events[0] {
5244 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5245 _ => panic!("Unexpected event"),
5247 match msg_events[1] {
5248 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5249 _ => panic!("Unexpected event"),
5251 match msg_events[2] {
5252 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, .. } } => {
5253 assert!(update_add_htlcs.is_empty());
5254 assert!(update_fail_htlcs.is_empty());
5255 assert_eq!(update_fulfill_htlcs.len(), 1);
5256 assert!(update_fail_malformed_htlcs.is_empty());
5257 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5259 _ => panic!("Unexpected event"),
5261 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5262 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5263 mine_transaction(&nodes[1], &commitment_tx[0]);
5264 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5265 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5266 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5267 assert_eq!(b_txn.len(), 3);
5268 check_spends!(b_txn[1], chan_1.3);
5269 check_spends!(b_txn[2], b_txn[1]);
5270 check_spends!(b_txn[0], commitment_tx[0]);
5271 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5272 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5273 assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
5275 check_closed_broadcast!(nodes[1], true);
5276 check_added_monitors!(nodes[1], 1);
5280 fn test_duplicate_payment_hash_one_failure_one_success() {
5281 // Topology : A --> B --> C --> D
5282 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5283 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5284 // we forward one of the payments onwards to D.
5285 let chanmon_cfgs = create_chanmon_cfgs(4);
5286 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5287 // When this test was written, the default base fee floated based on the HTLC count.
5288 // It is now fixed, so we simply set the fee to the expected value here.
5289 let mut config = test_default_channel_config();
5290 config.channel_config.forwarding_fee_base_msat = 196;
5291 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5292 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5293 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5295 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5296 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5297 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5299 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5300 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5301 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5302 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5303 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5305 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5307 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5308 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5309 // script push size limit so that the below script length checks match
5310 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5311 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5312 .with_features(InvoiceFeatures::known());
5313 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5314 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5316 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5317 assert_eq!(commitment_txn[0].input.len(), 1);
5318 check_spends!(commitment_txn[0], chan_2.3);
5320 mine_transaction(&nodes[1], &commitment_txn[0]);
5321 check_closed_broadcast!(nodes[1], true);
5322 check_added_monitors!(nodes[1], 1);
5323 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5324 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5326 let htlc_timeout_tx;
5327 { // Extract one of the two HTLC-Timeout transaction
5328 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5329 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5330 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5331 check_spends!(node_txn[0], chan_2.3);
5333 check_spends!(node_txn[1], commitment_txn[0]);
5334 assert_eq!(node_txn[1].input.len(), 1);
5336 if node_txn.len() > 3 {
5337 check_spends!(node_txn[2], commitment_txn[0]);
5338 assert_eq!(node_txn[2].input.len(), 1);
5339 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5341 check_spends!(node_txn[3], commitment_txn[0]);
5342 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5344 check_spends!(node_txn[2], commitment_txn[0]);
5345 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5348 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5349 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5350 if node_txn.len() > 3 {
5351 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5353 htlc_timeout_tx = node_txn[1].clone();
5356 nodes[2].node.claim_funds(our_payment_preimage);
5357 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5359 mine_transaction(&nodes[2], &commitment_txn[0]);
5360 check_added_monitors!(nodes[2], 2);
5361 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5362 let events = nodes[2].node.get_and_clear_pending_msg_events();
5364 MessageSendEvent::UpdateHTLCs { .. } => {},
5365 _ => panic!("Unexpected event"),
5368 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5369 _ => panic!("Unexepected event"),
5371 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5372 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)
5373 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5374 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5375 assert_eq!(htlc_success_txn[0].input.len(), 1);
5376 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5377 assert_eq!(htlc_success_txn[1].input.len(), 1);
5378 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5379 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5380 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5381 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5382 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5383 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5385 mine_transaction(&nodes[1], &htlc_timeout_tx);
5386 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5387 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
5388 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5389 assert!(htlc_updates.update_add_htlcs.is_empty());
5390 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5391 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5392 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5393 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5394 check_added_monitors!(nodes[1], 1);
5396 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5397 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5399 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5401 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5403 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5404 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5405 // and nodes[2] fee) is rounded down and then claimed in full.
5406 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5407 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5408 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5409 assert!(updates.update_add_htlcs.is_empty());
5410 assert!(updates.update_fail_htlcs.is_empty());
5411 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5412 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5413 assert!(updates.update_fail_malformed_htlcs.is_empty());
5414 check_added_monitors!(nodes[1], 1);
5416 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5417 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5419 let events = nodes[0].node.get_and_clear_pending_events();
5421 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5422 assert_eq!(*payment_preimage, our_payment_preimage);
5423 assert_eq!(*payment_hash, duplicate_payment_hash);
5425 _ => panic!("Unexpected event"),
5430 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5431 let chanmon_cfgs = create_chanmon_cfgs(2);
5432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5434 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5436 // Create some initial channels
5437 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5439 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5440 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5441 assert_eq!(local_txn.len(), 1);
5442 assert_eq!(local_txn[0].input.len(), 1);
5443 check_spends!(local_txn[0], chan_1.3);
5445 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5446 nodes[1].node.claim_funds(payment_preimage);
5447 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5448 check_added_monitors!(nodes[1], 1);
5450 mine_transaction(&nodes[1], &local_txn[0]);
5451 check_added_monitors!(nodes[1], 1);
5452 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5453 let events = nodes[1].node.get_and_clear_pending_msg_events();
5455 MessageSendEvent::UpdateHTLCs { .. } => {},
5456 _ => panic!("Unexpected event"),
5459 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5460 _ => panic!("Unexepected event"),
5463 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5464 assert_eq!(node_txn.len(), 3);
5465 assert_eq!(node_txn[0], node_txn[2]);
5466 assert_eq!(node_txn[1], local_txn[0]);
5467 assert_eq!(node_txn[0].input.len(), 1);
5468 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5469 check_spends!(node_txn[0], local_txn[0]);
5473 mine_transaction(&nodes[1], &node_tx);
5474 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5476 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5477 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5478 assert_eq!(spend_txn.len(), 1);
5479 assert_eq!(spend_txn[0].input.len(), 1);
5480 check_spends!(spend_txn[0], node_tx);
5481 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5484 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5485 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5486 // unrevoked commitment transaction.
5487 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5488 // a remote RAA before they could be failed backwards (and combinations thereof).
5489 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5490 // use the same payment hashes.
5491 // Thus, we use a six-node network:
5496 // And test where C fails back to A/B when D announces its latest commitment transaction
5497 let chanmon_cfgs = create_chanmon_cfgs(6);
5498 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5499 // When this test was written, the default base fee floated based on the HTLC count.
5500 // It is now fixed, so we simply set the fee to the expected value here.
5501 let mut config = test_default_channel_config();
5502 config.channel_config.forwarding_fee_base_msat = 196;
5503 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5504 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5505 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5507 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5508 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5509 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5510 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5511 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5513 // Rebalance and check output sanity...
5514 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5515 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5516 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5518 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5520 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
5522 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
5523 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5525 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
5527 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
5529 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5531 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5532 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5534 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());
5536 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());
5539 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5541 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5542 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
5545 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
5547 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5548 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());
5550 // Double-check that six of the new HTLC were added
5551 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5552 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5553 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5554 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5556 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5557 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5558 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5559 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5560 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5561 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5562 check_added_monitors!(nodes[4], 0);
5564 let failed_destinations = vec![
5565 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5566 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5567 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5568 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5570 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5571 check_added_monitors!(nodes[4], 1);
5573 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5574 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5575 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5576 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5577 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5578 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5580 // Fail 3rd below-dust and 7th above-dust HTLCs
5581 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5582 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5583 check_added_monitors!(nodes[5], 0);
5585 let failed_destinations_2 = vec![
5586 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5587 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5589 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5590 check_added_monitors!(nodes[5], 1);
5592 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5593 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5594 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5595 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5597 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5599 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5600 let failed_destinations_3 = vec![
5601 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5602 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5603 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5604 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5605 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5606 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5608 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5609 check_added_monitors!(nodes[3], 1);
5610 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5611 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5612 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5613 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5614 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5615 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5616 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5617 if deliver_last_raa {
5618 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5620 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5623 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5624 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5625 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5626 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5628 // We now broadcast the latest commitment transaction, which *should* result in failures for
5629 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5630 // the non-broadcast above-dust HTLCs.
5632 // Alternatively, we may broadcast the previous commitment transaction, which should only
5633 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5634 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5636 if announce_latest {
5637 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5639 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5641 let events = nodes[2].node.get_and_clear_pending_events();
5642 let close_event = if deliver_last_raa {
5643 assert_eq!(events.len(), 2 + 6);
5644 events.last().clone().unwrap()
5646 assert_eq!(events.len(), 1);
5647 events.last().clone().unwrap()
5650 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5651 _ => panic!("Unexpected event"),
5654 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5655 check_closed_broadcast!(nodes[2], true);
5656 if deliver_last_raa {
5657 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5659 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5660 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5662 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5663 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5665 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5668 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5670 check_added_monitors!(nodes[2], 3);
5672 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5673 assert_eq!(cs_msgs.len(), 2);
5674 let mut a_done = false;
5675 for msg in cs_msgs {
5677 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5678 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5679 // should be failed-backwards here.
5680 let target = if *node_id == nodes[0].node.get_our_node_id() {
5681 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5682 for htlc in &updates.update_fail_htlcs {
5683 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 });
5685 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5690 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5691 for htlc in &updates.update_fail_htlcs {
5692 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5694 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5695 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5698 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5699 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5700 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5701 if announce_latest {
5702 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5703 if *node_id == nodes[0].node.get_our_node_id() {
5704 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5707 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5709 _ => panic!("Unexpected event"),
5713 let as_events = nodes[0].node.get_and_clear_pending_events();
5714 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5715 let mut as_failds = HashSet::new();
5716 let mut as_updates = 0;
5717 for event in as_events.iter() {
5718 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5719 assert!(as_failds.insert(*payment_hash));
5720 if *payment_hash != payment_hash_2 {
5721 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5723 assert!(!payment_failed_permanently);
5725 if network_update.is_some() {
5728 } else { panic!("Unexpected event"); }
5730 assert!(as_failds.contains(&payment_hash_1));
5731 assert!(as_failds.contains(&payment_hash_2));
5732 if announce_latest {
5733 assert!(as_failds.contains(&payment_hash_3));
5734 assert!(as_failds.contains(&payment_hash_5));
5736 assert!(as_failds.contains(&payment_hash_6));
5738 let bs_events = nodes[1].node.get_and_clear_pending_events();
5739 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5740 let mut bs_failds = HashSet::new();
5741 let mut bs_updates = 0;
5742 for event in bs_events.iter() {
5743 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref network_update, .. } = event {
5744 assert!(bs_failds.insert(*payment_hash));
5745 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5746 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5748 assert!(!payment_failed_permanently);
5750 if network_update.is_some() {
5753 } else { panic!("Unexpected event"); }
5755 assert!(bs_failds.contains(&payment_hash_1));
5756 assert!(bs_failds.contains(&payment_hash_2));
5757 if announce_latest {
5758 assert!(bs_failds.contains(&payment_hash_4));
5760 assert!(bs_failds.contains(&payment_hash_5));
5762 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5763 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5764 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5765 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5766 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5767 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5771 fn test_fail_backwards_latest_remote_announce_a() {
5772 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5776 fn test_fail_backwards_latest_remote_announce_b() {
5777 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5781 fn test_fail_backwards_previous_remote_announce() {
5782 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5783 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5784 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5788 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5789 let chanmon_cfgs = create_chanmon_cfgs(2);
5790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5792 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5794 // Create some initial channels
5795 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5797 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5798 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5799 assert_eq!(local_txn[0].input.len(), 1);
5800 check_spends!(local_txn[0], chan_1.3);
5802 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5803 mine_transaction(&nodes[0], &local_txn[0]);
5804 check_closed_broadcast!(nodes[0], true);
5805 check_added_monitors!(nodes[0], 1);
5806 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5807 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5809 let htlc_timeout = {
5810 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5811 assert_eq!(node_txn.len(), 2);
5812 check_spends!(node_txn[0], chan_1.3);
5813 assert_eq!(node_txn[1].input.len(), 1);
5814 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5815 check_spends!(node_txn[1], local_txn[0]);
5819 mine_transaction(&nodes[0], &htlc_timeout);
5820 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5821 expect_payment_failed!(nodes[0], our_payment_hash, false);
5823 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5824 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5825 assert_eq!(spend_txn.len(), 3);
5826 check_spends!(spend_txn[0], local_txn[0]);
5827 assert_eq!(spend_txn[1].input.len(), 1);
5828 check_spends!(spend_txn[1], htlc_timeout);
5829 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5830 assert_eq!(spend_txn[2].input.len(), 2);
5831 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5832 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5833 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5837 fn test_key_derivation_params() {
5838 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5839 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5840 // let us re-derive the channel key set to then derive a delayed_payment_key.
5842 let chanmon_cfgs = create_chanmon_cfgs(3);
5844 // We manually create the node configuration to backup the seed.
5845 let seed = [42; 32];
5846 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5847 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);
5848 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5849 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() };
5850 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5851 node_cfgs.remove(0);
5852 node_cfgs.insert(0, node);
5854 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5855 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5857 // Create some initial channels
5858 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5860 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5861 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5862 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5864 // Ensure all nodes are at the same height
5865 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5866 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5867 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5868 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5870 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5871 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5872 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5873 assert_eq!(local_txn_1[0].input.len(), 1);
5874 check_spends!(local_txn_1[0], chan_1.3);
5876 // We check funding pubkey are unique
5877 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]));
5878 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]));
5879 if from_0_funding_key_0 == from_1_funding_key_0
5880 || from_0_funding_key_0 == from_1_funding_key_1
5881 || from_0_funding_key_1 == from_1_funding_key_0
5882 || from_0_funding_key_1 == from_1_funding_key_1 {
5883 panic!("Funding pubkeys aren't unique");
5886 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5887 mine_transaction(&nodes[0], &local_txn_1[0]);
5888 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5889 check_closed_broadcast!(nodes[0], true);
5890 check_added_monitors!(nodes[0], 1);
5891 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5893 let htlc_timeout = {
5894 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5895 assert_eq!(node_txn[1].input.len(), 1);
5896 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5897 check_spends!(node_txn[1], local_txn_1[0]);
5901 mine_transaction(&nodes[0], &htlc_timeout);
5902 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5903 expect_payment_failed!(nodes[0], our_payment_hash, false);
5905 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5906 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5907 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5908 assert_eq!(spend_txn.len(), 3);
5909 check_spends!(spend_txn[0], local_txn_1[0]);
5910 assert_eq!(spend_txn[1].input.len(), 1);
5911 check_spends!(spend_txn[1], htlc_timeout);
5912 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5913 assert_eq!(spend_txn[2].input.len(), 2);
5914 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5915 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5916 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5920 fn test_static_output_closing_tx() {
5921 let chanmon_cfgs = create_chanmon_cfgs(2);
5922 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5923 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5924 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5926 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5928 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5929 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5931 mine_transaction(&nodes[0], &closing_tx);
5932 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5933 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5935 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5936 assert_eq!(spend_txn.len(), 1);
5937 check_spends!(spend_txn[0], closing_tx);
5939 mine_transaction(&nodes[1], &closing_tx);
5940 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5941 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5943 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5944 assert_eq!(spend_txn.len(), 1);
5945 check_spends!(spend_txn[0], closing_tx);
5948 fn do_htlc_claim_local_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 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 (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5957 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5958 // present in B's local commitment transaction, but none of A's commitment transactions.
5959 nodes[1].node.claim_funds(payment_preimage);
5960 check_added_monitors!(nodes[1], 1);
5961 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5963 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5964 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5965 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5967 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5968 check_added_monitors!(nodes[0], 1);
5969 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5970 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5971 check_added_monitors!(nodes[1], 1);
5973 let starting_block = nodes[1].best_block_info();
5974 let mut block = Block {
5975 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5978 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5979 connect_block(&nodes[1], &block);
5980 block.header.prev_blockhash = block.block_hash();
5982 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5983 check_closed_broadcast!(nodes[1], true);
5984 check_added_monitors!(nodes[1], 1);
5985 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5988 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5989 let chanmon_cfgs = create_chanmon_cfgs(2);
5990 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5991 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5992 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5993 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5995 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5996 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5997 check_added_monitors!(nodes[0], 1);
5999 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6001 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
6002 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6003 // to "time out" the HTLC.
6005 let starting_block = nodes[1].best_block_info();
6006 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
6008 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6009 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6010 header.prev_blockhash = header.block_hash();
6012 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6013 check_closed_broadcast!(nodes[0], true);
6014 check_added_monitors!(nodes[0], 1);
6015 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6018 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6019 let chanmon_cfgs = create_chanmon_cfgs(3);
6020 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6021 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6022 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6023 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6025 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6026 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6027 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6028 // actually revoked.
6029 let htlc_value = if use_dust { 50000 } else { 3000000 };
6030 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6031 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6032 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6033 check_added_monitors!(nodes[1], 1);
6035 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6036 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6037 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6038 check_added_monitors!(nodes[0], 1);
6039 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6040 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6041 check_added_monitors!(nodes[1], 1);
6042 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6043 check_added_monitors!(nodes[1], 1);
6044 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6046 if check_revoke_no_close {
6047 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6048 check_added_monitors!(nodes[0], 1);
6051 let starting_block = nodes[1].best_block_info();
6052 let mut block = Block {
6053 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
6056 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6057 connect_block(&nodes[0], &block);
6058 block.header.prev_blockhash = block.block_hash();
6060 if !check_revoke_no_close {
6061 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6062 check_closed_broadcast!(nodes[0], true);
6063 check_added_monitors!(nodes[0], 1);
6064 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6066 let events = nodes[0].node.get_and_clear_pending_events();
6067 assert_eq!(events.len(), 2);
6068 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6069 assert_eq!(*payment_hash, our_payment_hash);
6070 } else { panic!("Unexpected event"); }
6071 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6072 assert_eq!(*payment_hash, our_payment_hash);
6073 } else { panic!("Unexpected event"); }
6077 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6078 // There are only a few cases to test here:
6079 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6080 // broadcastable commitment transactions result in channel closure,
6081 // * its included in an unrevoked-but-previous remote commitment transaction,
6082 // * its included in the latest remote or local commitment transactions.
6083 // We test each of the three possible commitment transactions individually and use both dust and
6085 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6086 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6087 // tested for at least one of the cases in other tests.
6089 fn htlc_claim_single_commitment_only_a() {
6090 do_htlc_claim_local_commitment_only(true);
6091 do_htlc_claim_local_commitment_only(false);
6093 do_htlc_claim_current_remote_commitment_only(true);
6094 do_htlc_claim_current_remote_commitment_only(false);
6098 fn htlc_claim_single_commitment_only_b() {
6099 do_htlc_claim_previous_remote_commitment_only(true, false);
6100 do_htlc_claim_previous_remote_commitment_only(false, false);
6101 do_htlc_claim_previous_remote_commitment_only(true, true);
6102 do_htlc_claim_previous_remote_commitment_only(false, true);
6107 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6108 let chanmon_cfgs = create_chanmon_cfgs(2);
6109 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6110 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6111 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6112 // Force duplicate randomness for every get-random call
6113 for node in nodes.iter() {
6114 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6117 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6118 let channel_value_satoshis=10000;
6119 let push_msat=10001;
6120 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6121 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6122 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6123 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6125 // Create a second channel with the same random values. This used to panic due to a colliding
6126 // channel_id, but now panics due to a colliding outbound SCID alias.
6127 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6131 fn bolt2_open_channel_sending_node_checks_part2() {
6132 let chanmon_cfgs = create_chanmon_cfgs(2);
6133 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6135 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6137 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6138 let channel_value_satoshis=2^24;
6139 let push_msat=10001;
6140 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6142 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6143 let channel_value_satoshis=10000;
6144 // Test when push_msat is equal to 1000 * funding_satoshis.
6145 let push_msat=1000*channel_value_satoshis+1;
6146 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6148 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6149 let channel_value_satoshis=10000;
6150 let push_msat=10001;
6151 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
6152 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6153 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6155 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6156 // 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
6157 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6159 // 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.
6160 assert!(BREAKDOWN_TIMEOUT>0);
6161 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6163 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6164 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6165 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6167 // 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.
6168 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6169 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6170 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6171 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6172 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6176 fn bolt2_open_channel_sane_dust_limit() {
6177 let chanmon_cfgs = create_chanmon_cfgs(2);
6178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6180 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6182 let channel_value_satoshis=1000000;
6183 let push_msat=10001;
6184 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6185 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6186 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6187 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6189 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6190 let events = nodes[1].node.get_and_clear_pending_msg_events();
6191 let err_msg = match events[0] {
6192 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6195 _ => panic!("Unexpected event"),
6197 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6200 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6201 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6202 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6203 // is no longer affordable once it's freed.
6205 fn test_fail_holding_cell_htlc_upon_free() {
6206 let chanmon_cfgs = create_chanmon_cfgs(2);
6207 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6208 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6209 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6210 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6212 // First nodes[0] generates an update_fee, setting the channel's
6213 // pending_update_fee.
6215 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6216 *feerate_lock += 20;
6218 nodes[0].node.timer_tick_occurred();
6219 check_added_monitors!(nodes[0], 1);
6221 let events = nodes[0].node.get_and_clear_pending_msg_events();
6222 assert_eq!(events.len(), 1);
6223 let (update_msg, commitment_signed) = match events[0] {
6224 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6225 (update_fee.as_ref(), commitment_signed)
6227 _ => panic!("Unexpected event"),
6230 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6232 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6233 let channel_reserve = chan_stat.channel_reserve_msat;
6234 let feerate = get_feerate!(nodes[0], chan.2);
6235 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6237 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6238 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6239 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6241 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6242 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6243 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6244 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6246 // Flush the pending fee update.
6247 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6248 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6249 check_added_monitors!(nodes[1], 1);
6250 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6251 check_added_monitors!(nodes[0], 1);
6253 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6254 // HTLC, but now that the fee has been raised the payment will now fail, causing
6255 // us to surface its failure to the user.
6256 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6257 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6258 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);
6259 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 {}",
6260 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6261 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6263 // Check that the payment failed to be sent out.
6264 let events = nodes[0].node.get_and_clear_pending_events();
6265 assert_eq!(events.len(), 1);
6267 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6268 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6269 assert_eq!(our_payment_hash.clone(), *payment_hash);
6270 assert_eq!(*payment_failed_permanently, false);
6271 assert_eq!(*all_paths_failed, true);
6272 assert_eq!(*network_update, None);
6273 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
6275 _ => panic!("Unexpected event"),
6279 // Test that if multiple HTLCs are released from the holding cell and one is
6280 // valid but the other is no longer valid upon release, the valid HTLC can be
6281 // successfully completed while the other one fails as expected.
6283 fn test_free_and_fail_holding_cell_htlcs() {
6284 let chanmon_cfgs = create_chanmon_cfgs(2);
6285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6287 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6290 // First nodes[0] generates an update_fee, setting the channel's
6291 // pending_update_fee.
6293 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6294 *feerate_lock += 200;
6296 nodes[0].node.timer_tick_occurred();
6297 check_added_monitors!(nodes[0], 1);
6299 let events = nodes[0].node.get_and_clear_pending_msg_events();
6300 assert_eq!(events.len(), 1);
6301 let (update_msg, commitment_signed) = match events[0] {
6302 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6303 (update_fee.as_ref(), commitment_signed)
6305 _ => panic!("Unexpected event"),
6308 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6310 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6311 let channel_reserve = chan_stat.channel_reserve_msat;
6312 let feerate = get_feerate!(nodes[0], chan.2);
6313 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6315 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6317 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6318 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6319 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6321 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6322 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6323 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6324 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6325 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6326 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6327 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6329 // Flush the pending fee update.
6330 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6331 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6332 check_added_monitors!(nodes[1], 1);
6333 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6334 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6335 check_added_monitors!(nodes[0], 2);
6337 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6338 // but now that the fee has been raised the second payment will now fail, causing us
6339 // to surface its failure to the user. The first payment should succeed.
6340 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6341 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6342 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);
6343 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 {}",
6344 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6345 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6347 // Check that the second payment failed to be sent out.
6348 let events = nodes[0].node.get_and_clear_pending_events();
6349 assert_eq!(events.len(), 1);
6351 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref short_channel_id, .. } => {
6352 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6353 assert_eq!(payment_hash_2.clone(), *payment_hash);
6354 assert_eq!(*payment_failed_permanently, false);
6355 assert_eq!(*all_paths_failed, true);
6356 assert_eq!(*network_update, None);
6357 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
6359 _ => panic!("Unexpected event"),
6362 // Complete the first payment and the RAA from the fee update.
6363 let (payment_event, send_raa_event) = {
6364 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6365 assert_eq!(msgs.len(), 2);
6366 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6368 let raa = match send_raa_event {
6369 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6370 _ => panic!("Unexpected event"),
6372 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6373 check_added_monitors!(nodes[1], 1);
6374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6375 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6376 let events = nodes[1].node.get_and_clear_pending_events();
6377 assert_eq!(events.len(), 1);
6379 Event::PendingHTLCsForwardable { .. } => {},
6380 _ => panic!("Unexpected event"),
6382 nodes[1].node.process_pending_htlc_forwards();
6383 let events = nodes[1].node.get_and_clear_pending_events();
6384 assert_eq!(events.len(), 1);
6386 Event::PaymentReceived { .. } => {},
6387 _ => panic!("Unexpected event"),
6389 nodes[1].node.claim_funds(payment_preimage_1);
6390 check_added_monitors!(nodes[1], 1);
6391 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6393 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6394 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6395 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6396 expect_payment_sent!(nodes[0], payment_preimage_1);
6399 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6400 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6401 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6404 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6405 let chanmon_cfgs = create_chanmon_cfgs(3);
6406 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6407 // When this test was written, the default base fee floated based on the HTLC count.
6408 // It is now fixed, so we simply set the fee to the expected value here.
6409 let mut config = test_default_channel_config();
6410 config.channel_config.forwarding_fee_base_msat = 196;
6411 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6412 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6413 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6414 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6416 // First nodes[1] generates an update_fee, setting the channel's
6417 // pending_update_fee.
6419 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6420 *feerate_lock += 20;
6422 nodes[1].node.timer_tick_occurred();
6423 check_added_monitors!(nodes[1], 1);
6425 let events = nodes[1].node.get_and_clear_pending_msg_events();
6426 assert_eq!(events.len(), 1);
6427 let (update_msg, commitment_signed) = match events[0] {
6428 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6429 (update_fee.as_ref(), commitment_signed)
6431 _ => panic!("Unexpected event"),
6434 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6436 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6437 let channel_reserve = chan_stat.channel_reserve_msat;
6438 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6439 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6441 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6443 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6444 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6445 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6446 let payment_event = {
6447 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6448 check_added_monitors!(nodes[0], 1);
6450 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6451 assert_eq!(events.len(), 1);
6453 SendEvent::from_event(events.remove(0))
6455 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6456 check_added_monitors!(nodes[1], 0);
6457 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6458 expect_pending_htlcs_forwardable!(nodes[1]);
6460 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6461 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6463 // Flush the pending fee update.
6464 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6465 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6466 check_added_monitors!(nodes[2], 1);
6467 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6468 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6469 check_added_monitors!(nodes[1], 2);
6471 // A final RAA message is generated to finalize the fee update.
6472 let events = nodes[1].node.get_and_clear_pending_msg_events();
6473 assert_eq!(events.len(), 1);
6475 let raa_msg = match &events[0] {
6476 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6479 _ => panic!("Unexpected event"),
6482 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6483 check_added_monitors!(nodes[2], 1);
6484 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6486 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6487 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6488 assert_eq!(process_htlc_forwards_event.len(), 2);
6489 match &process_htlc_forwards_event[0] {
6490 &Event::PendingHTLCsForwardable { .. } => {},
6491 _ => panic!("Unexpected event"),
6494 // In response, we call ChannelManager's process_pending_htlc_forwards
6495 nodes[1].node.process_pending_htlc_forwards();
6496 check_added_monitors!(nodes[1], 1);
6498 // This causes the HTLC to be failed backwards.
6499 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6500 assert_eq!(fail_event.len(), 1);
6501 let (fail_msg, commitment_signed) = match &fail_event[0] {
6502 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6503 assert_eq!(updates.update_add_htlcs.len(), 0);
6504 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6505 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6506 assert_eq!(updates.update_fail_htlcs.len(), 1);
6507 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6509 _ => panic!("Unexpected event"),
6512 // Pass the failure messages back to nodes[0].
6513 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6514 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6516 // Complete the HTLC failure+removal process.
6517 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6518 check_added_monitors!(nodes[0], 1);
6519 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6520 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6521 check_added_monitors!(nodes[1], 2);
6522 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6523 assert_eq!(final_raa_event.len(), 1);
6524 let raa = match &final_raa_event[0] {
6525 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6526 _ => panic!("Unexpected event"),
6528 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6529 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6530 check_added_monitors!(nodes[0], 1);
6533 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6534 // 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.
6535 //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.
6538 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6539 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
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 (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6547 route.paths[0][0].fee_msat = 100;
6549 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6550 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6551 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6552 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6556 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6557 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6558 let chanmon_cfgs = create_chanmon_cfgs(2);
6559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6561 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6562 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6564 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6565 route.paths[0][0].fee_msat = 0;
6566 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6567 assert_eq!(err, "Cannot send 0-msat HTLC"));
6569 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6570 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6574 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6575 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6576 let chanmon_cfgs = create_chanmon_cfgs(2);
6577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6579 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6580 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6582 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6583 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6584 check_added_monitors!(nodes[0], 1);
6585 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6586 updates.update_add_htlcs[0].amount_msat = 0;
6588 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6589 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6590 check_closed_broadcast!(nodes[1], true).unwrap();
6591 check_added_monitors!(nodes[1], 1);
6592 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6596 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6597 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6598 //It is enforced when constructing a route.
6599 let chanmon_cfgs = create_chanmon_cfgs(2);
6600 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6602 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6603 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6605 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6606 .with_features(InvoiceFeatures::known());
6607 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6608 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6609 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6610 assert_eq!(err, &"Channel CLTV overflowed?"));
6614 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6615 //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.
6616 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6617 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6618 let chanmon_cfgs = create_chanmon_cfgs(2);
6619 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6620 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6621 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6622 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6623 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6625 for i in 0..max_accepted_htlcs {
6626 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6627 let payment_event = {
6628 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6629 check_added_monitors!(nodes[0], 1);
6631 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6632 assert_eq!(events.len(), 1);
6633 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6634 assert_eq!(htlcs[0].htlc_id, i);
6638 SendEvent::from_event(events.remove(0))
6640 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6641 check_added_monitors!(nodes[1], 0);
6642 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6644 expect_pending_htlcs_forwardable!(nodes[1]);
6645 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6647 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6648 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6649 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6651 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6652 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6656 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6657 //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.
6658 let chanmon_cfgs = create_chanmon_cfgs(2);
6659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6662 let channel_value = 100000;
6663 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6664 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6666 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6668 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6669 // Manually create a route over our max in flight (which our router normally automatically
6671 route.paths[0][0].fee_msat = max_in_flight + 1;
6672 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6673 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)));
6675 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6676 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);
6678 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6681 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6683 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6684 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6685 let chanmon_cfgs = create_chanmon_cfgs(2);
6686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6690 let htlc_minimum_msat: u64;
6692 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6693 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6694 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6697 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6698 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6699 check_added_monitors!(nodes[0], 1);
6700 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6701 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6702 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703 assert!(nodes[1].node.list_channels().is_empty());
6704 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6705 assert!(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()));
6706 check_added_monitors!(nodes[1], 1);
6707 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6711 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6712 //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
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 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6720 let channel_reserve = chan_stat.channel_reserve_msat;
6721 let feerate = get_feerate!(nodes[0], chan.2);
6722 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6723 // The 2* and +1 are for the fee spike reserve.
6724 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6726 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6727 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6728 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6729 check_added_monitors!(nodes[0], 1);
6730 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6732 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6733 // at this time channel-initiatee receivers are not required to enforce that senders
6734 // respect the fee_spike_reserve.
6735 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6736 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6738 assert!(nodes[1].node.list_channels().is_empty());
6739 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6740 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6741 check_added_monitors!(nodes[1], 1);
6742 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6746 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6747 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6748 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6749 let chanmon_cfgs = create_chanmon_cfgs(2);
6750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6752 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6753 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6755 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6756 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6757 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6758 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6759 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6760 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6762 let mut msg = msgs::UpdateAddHTLC {
6766 payment_hash: our_payment_hash,
6767 cltv_expiry: htlc_cltv,
6768 onion_routing_packet: onion_packet.clone(),
6771 for i in 0..super::channel::OUR_MAX_HTLCS {
6772 msg.htlc_id = i as u64;
6773 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6775 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6776 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6778 assert!(nodes[1].node.list_channels().is_empty());
6779 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6780 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6781 check_added_monitors!(nodes[1], 1);
6782 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6786 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6787 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6788 let chanmon_cfgs = create_chanmon_cfgs(2);
6789 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6790 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6791 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6792 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6794 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6795 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6796 check_added_monitors!(nodes[0], 1);
6797 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6798 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6799 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6801 assert!(nodes[1].node.list_channels().is_empty());
6802 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6803 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6804 check_added_monitors!(nodes[1], 1);
6805 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6809 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6810 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6811 let chanmon_cfgs = create_chanmon_cfgs(2);
6812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6814 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6816 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6817 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6818 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6819 check_added_monitors!(nodes[0], 1);
6820 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6821 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6822 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6824 assert!(nodes[1].node.list_channels().is_empty());
6825 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6826 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6827 check_added_monitors!(nodes[1], 1);
6828 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6832 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6833 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6834 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6835 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6836 let chanmon_cfgs = create_chanmon_cfgs(2);
6837 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6838 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6839 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6841 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6842 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6843 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6844 check_added_monitors!(nodes[0], 1);
6845 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6846 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6848 //Disconnect and Reconnect
6849 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6850 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6851 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6852 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6853 assert_eq!(reestablish_1.len(), 1);
6854 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6855 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6856 assert_eq!(reestablish_2.len(), 1);
6857 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6858 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6859 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6860 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6863 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6864 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6865 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6866 check_added_monitors!(nodes[1], 1);
6867 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6869 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6871 assert!(nodes[1].node.list_channels().is_empty());
6872 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6873 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6874 check_added_monitors!(nodes[1], 1);
6875 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6879 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6880 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6882 let chanmon_cfgs = create_chanmon_cfgs(2);
6883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6885 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6886 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6887 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6888 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6890 check_added_monitors!(nodes[0], 1);
6891 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6892 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6894 let update_msg = msgs::UpdateFulfillHTLC{
6897 payment_preimage: our_payment_preimage,
6900 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6902 assert!(nodes[0].node.list_channels().is_empty());
6903 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6904 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6905 check_added_monitors!(nodes[0], 1);
6906 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6910 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6911 //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.
6913 let chanmon_cfgs = create_chanmon_cfgs(2);
6914 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6915 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6916 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6917 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6919 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6920 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6921 check_added_monitors!(nodes[0], 1);
6922 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6923 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6925 let update_msg = msgs::UpdateFailHTLC{
6928 reason: msgs::OnionErrorPacket { data: Vec::new()},
6931 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6933 assert!(nodes[0].node.list_channels().is_empty());
6934 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6935 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()));
6936 check_added_monitors!(nodes[0], 1);
6937 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6941 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6942 //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.
6944 let chanmon_cfgs = create_chanmon_cfgs(2);
6945 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6946 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6947 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6948 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6950 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6951 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6952 check_added_monitors!(nodes[0], 1);
6953 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6954 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6955 let update_msg = msgs::UpdateFailMalformedHTLC{
6958 sha256_of_onion: [1; 32],
6959 failure_code: 0x8000,
6962 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6964 assert!(nodes[0].node.list_channels().is_empty());
6965 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6966 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()));
6967 check_added_monitors!(nodes[0], 1);
6968 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6972 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6973 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6975 let chanmon_cfgs = create_chanmon_cfgs(2);
6976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6978 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6979 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6981 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6983 nodes[1].node.claim_funds(our_payment_preimage);
6984 check_added_monitors!(nodes[1], 1);
6985 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6987 let events = nodes[1].node.get_and_clear_pending_msg_events();
6988 assert_eq!(events.len(), 1);
6989 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6991 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, .. } } => {
6992 assert!(update_add_htlcs.is_empty());
6993 assert_eq!(update_fulfill_htlcs.len(), 1);
6994 assert!(update_fail_htlcs.is_empty());
6995 assert!(update_fail_malformed_htlcs.is_empty());
6996 assert!(update_fee.is_none());
6997 update_fulfill_htlcs[0].clone()
6999 _ => panic!("Unexpected event"),
7003 update_fulfill_msg.htlc_id = 1;
7005 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7007 assert!(nodes[0].node.list_channels().is_empty());
7008 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7009 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7010 check_added_monitors!(nodes[0], 1);
7011 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7015 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7016 //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.
7018 let chanmon_cfgs = create_chanmon_cfgs(2);
7019 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7020 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7021 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7022 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7024 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7026 nodes[1].node.claim_funds(our_payment_preimage);
7027 check_added_monitors!(nodes[1], 1);
7028 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7030 let events = nodes[1].node.get_and_clear_pending_msg_events();
7031 assert_eq!(events.len(), 1);
7032 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7034 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, .. } } => {
7035 assert!(update_add_htlcs.is_empty());
7036 assert_eq!(update_fulfill_htlcs.len(), 1);
7037 assert!(update_fail_htlcs.is_empty());
7038 assert!(update_fail_malformed_htlcs.is_empty());
7039 assert!(update_fee.is_none());
7040 update_fulfill_htlcs[0].clone()
7042 _ => panic!("Unexpected event"),
7046 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7048 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7050 assert!(nodes[0].node.list_channels().is_empty());
7051 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7052 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7053 check_added_monitors!(nodes[0], 1);
7054 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7058 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7059 //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.
7061 let chanmon_cfgs = create_chanmon_cfgs(2);
7062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7064 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7065 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7067 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7068 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7069 check_added_monitors!(nodes[0], 1);
7071 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7072 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7074 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7075 check_added_monitors!(nodes[1], 0);
7076 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7078 let events = nodes[1].node.get_and_clear_pending_msg_events();
7080 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7082 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, .. } } => {
7083 assert!(update_add_htlcs.is_empty());
7084 assert!(update_fulfill_htlcs.is_empty());
7085 assert!(update_fail_htlcs.is_empty());
7086 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7087 assert!(update_fee.is_none());
7088 update_fail_malformed_htlcs[0].clone()
7090 _ => panic!("Unexpected event"),
7093 update_msg.failure_code &= !0x8000;
7094 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7096 assert!(nodes[0].node.list_channels().is_empty());
7097 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7098 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7099 check_added_monitors!(nodes[0], 1);
7100 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7104 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7105 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7106 // * 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.
7108 let chanmon_cfgs = create_chanmon_cfgs(3);
7109 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7110 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7111 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7112 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7113 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7115 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7118 let mut payment_event = {
7119 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7120 check_added_monitors!(nodes[0], 1);
7121 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7122 assert_eq!(events.len(), 1);
7123 SendEvent::from_event(events.remove(0))
7125 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7126 check_added_monitors!(nodes[1], 0);
7127 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7128 expect_pending_htlcs_forwardable!(nodes[1]);
7129 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7130 assert_eq!(events_2.len(), 1);
7131 check_added_monitors!(nodes[1], 1);
7132 payment_event = SendEvent::from_event(events_2.remove(0));
7133 assert_eq!(payment_event.msgs.len(), 1);
7136 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7137 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7138 check_added_monitors!(nodes[2], 0);
7139 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7141 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7142 assert_eq!(events_3.len(), 1);
7143 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7145 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 } } => {
7146 assert!(update_add_htlcs.is_empty());
7147 assert!(update_fulfill_htlcs.is_empty());
7148 assert!(update_fail_htlcs.is_empty());
7149 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7150 assert!(update_fee.is_none());
7151 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7153 _ => panic!("Unexpected event"),
7157 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7159 check_added_monitors!(nodes[1], 0);
7160 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7161 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7162 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7163 assert_eq!(events_4.len(), 1);
7165 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7167 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, .. } } => {
7168 assert!(update_add_htlcs.is_empty());
7169 assert!(update_fulfill_htlcs.is_empty());
7170 assert_eq!(update_fail_htlcs.len(), 1);
7171 assert!(update_fail_malformed_htlcs.is_empty());
7172 assert!(update_fee.is_none());
7174 _ => panic!("Unexpected event"),
7177 check_added_monitors!(nodes[1], 1);
7180 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7181 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7182 // 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
7183 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7185 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7186 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7189 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7190 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7192 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7194 // We route 2 dust-HTLCs between A and B
7195 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7196 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7197 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7199 // Cache one local commitment tx as previous
7200 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7202 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7203 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7204 check_added_monitors!(nodes[1], 0);
7205 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7206 check_added_monitors!(nodes[1], 1);
7208 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7209 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7210 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7211 check_added_monitors!(nodes[0], 1);
7213 // Cache one local commitment tx as lastest
7214 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7216 let events = nodes[0].node.get_and_clear_pending_msg_events();
7218 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7219 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7221 _ => panic!("Unexpected event"),
7224 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7225 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7227 _ => panic!("Unexpected event"),
7230 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7231 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7232 if announce_latest {
7233 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7235 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7238 check_closed_broadcast!(nodes[0], true);
7239 check_added_monitors!(nodes[0], 1);
7240 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7242 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7243 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7244 let events = nodes[0].node.get_and_clear_pending_events();
7245 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7246 assert_eq!(events.len(), 2);
7247 let mut first_failed = false;
7248 for event in events {
7250 Event::PaymentPathFailed { payment_hash, .. } => {
7251 if payment_hash == payment_hash_1 {
7252 assert!(!first_failed);
7253 first_failed = true;
7255 assert_eq!(payment_hash, payment_hash_2);
7258 _ => panic!("Unexpected event"),
7264 fn test_failure_delay_dust_htlc_local_commitment() {
7265 do_test_failure_delay_dust_htlc_local_commitment(true);
7266 do_test_failure_delay_dust_htlc_local_commitment(false);
7269 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7270 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7271 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7272 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7273 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7274 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7275 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7277 let chanmon_cfgs = create_chanmon_cfgs(3);
7278 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7279 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7280 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7281 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7283 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7285 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7286 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7288 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7289 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7291 // We revoked bs_commitment_tx
7293 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7294 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7297 let mut timeout_tx = Vec::new();
7299 // We fail dust-HTLC 1 by broadcast of local commitment tx
7300 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7301 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7302 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7303 expect_payment_failed!(nodes[0], dust_hash, false);
7305 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7306 check_closed_broadcast!(nodes[0], true);
7307 check_added_monitors!(nodes[0], 1);
7308 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7309 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7310 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7311 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7312 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7313 mine_transaction(&nodes[0], &timeout_tx[0]);
7314 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7315 expect_payment_failed!(nodes[0], non_dust_hash, false);
7317 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7318 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7319 check_closed_broadcast!(nodes[0], true);
7320 check_added_monitors!(nodes[0], 1);
7321 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7322 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7324 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7325 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7326 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7327 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7328 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7329 // dust HTLC should have been failed.
7330 expect_payment_failed!(nodes[0], dust_hash, false);
7333 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7335 assert_eq!(timeout_tx[0].lock_time.0, 0);
7337 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7338 mine_transaction(&nodes[0], &timeout_tx[0]);
7339 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7340 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7341 expect_payment_failed!(nodes[0], non_dust_hash, false);
7346 fn test_sweep_outbound_htlc_failure_update() {
7347 do_test_sweep_outbound_htlc_failure_update(false, true);
7348 do_test_sweep_outbound_htlc_failure_update(false, false);
7349 do_test_sweep_outbound_htlc_failure_update(true, false);
7353 fn test_user_configurable_csv_delay() {
7354 // We test our channel constructors yield errors when we pass them absurd csv delay
7356 let mut low_our_to_self_config = UserConfig::default();
7357 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7358 let mut high_their_to_self_config = UserConfig::default();
7359 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7360 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7361 let chanmon_cfgs = create_chanmon_cfgs(2);
7362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7364 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7366 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7367 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7368 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7369 &low_our_to_self_config, 0, 42)
7372 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())); },
7373 _ => panic!("Unexpected event"),
7375 } else { assert!(false) }
7377 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7378 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7379 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7380 open_channel.to_self_delay = 200;
7381 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7382 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7383 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7386 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())); },
7387 _ => panic!("Unexpected event"),
7389 } else { assert!(false); }
7391 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7392 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7393 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()));
7394 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7395 accept_channel.to_self_delay = 200;
7396 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7398 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7400 &ErrorAction::SendErrorMessage { ref msg } => {
7401 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()));
7402 reason_msg = msg.data.clone();
7406 } else { panic!(); }
7407 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7409 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7410 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7411 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7412 open_channel.to_self_delay = 200;
7413 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7414 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7415 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7418 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())); },
7419 _ => panic!("Unexpected event"),
7421 } else { assert!(false); }
7424 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7425 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7426 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7427 // panic message informs the user they should force-close without broadcasting, which is tested
7428 // if `reconnect_panicing` is not set.
7434 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7435 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7436 // during signing due to revoked tx
7437 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7438 let keys_manager = &chanmon_cfgs[0].keys_manager;
7441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7443 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7445 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7447 // Cache node A state before any channel update
7448 let previous_node_state = nodes[0].node.encode();
7449 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7450 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7452 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7453 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7455 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7456 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7458 // Restore node A from previous state
7459 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7460 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7461 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7462 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7463 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7464 persister = test_utils::TestPersister::new();
7465 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7467 let mut channel_monitors = HashMap::new();
7468 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7469 <(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 {
7470 keys_manager: keys_manager,
7471 fee_estimator: &fee_estimator,
7472 chain_monitor: &monitor,
7474 tx_broadcaster: &tx_broadcaster,
7475 default_config: UserConfig::default(),
7479 nodes[0].node = &node_state_0;
7480 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7481 nodes[0].chain_monitor = &monitor;
7482 nodes[0].chain_source = &chain_source;
7484 check_added_monitors!(nodes[0], 1);
7486 if reconnect_panicing {
7487 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7488 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7490 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7492 // Check we close channel detecting A is fallen-behind
7493 // Check that we sent the warning message when we detected that A has fallen behind,
7494 // and give the possibility for A to recover from the warning.
7495 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7496 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7497 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7500 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7501 // The node B should not broadcast the transaction to force close the channel!
7502 assert!(node_txn.is_empty());
7505 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7506 // Check A panics upon seeing proof it has fallen behind.
7507 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7508 return; // By this point we should have panic'ed!
7511 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7512 check_added_monitors!(nodes[0], 1);
7513 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7515 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7516 assert_eq!(node_txn.len(), 0);
7519 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7520 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7521 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7523 &ErrorAction::SendErrorMessage { ref msg } => {
7524 assert_eq!(msg.data, "Channel force-closed");
7526 _ => panic!("Unexpected event!"),
7529 panic!("Unexpected event {:?}", msg)
7533 // after the warning message sent by B, we should not able to
7534 // use the channel, or reconnect with success to the channel.
7535 assert!(nodes[0].node.list_usable_channels().is_empty());
7536 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7537 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7538 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7540 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7541 let mut err_msgs_0 = Vec::with_capacity(1);
7542 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7543 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7545 &ErrorAction::SendErrorMessage { ref msg } => {
7546 assert_eq!(msg.data, "Failed to find corresponding channel");
7547 err_msgs_0.push(msg.clone());
7549 _ => panic!("Unexpected event!"),
7552 panic!("Unexpected event!");
7555 assert_eq!(err_msgs_0.len(), 1);
7556 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7557 assert!(nodes[1].node.list_usable_channels().is_empty());
7558 check_added_monitors!(nodes[1], 1);
7559 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7560 check_closed_broadcast!(nodes[1], false);
7565 fn test_data_loss_protect_showing_stale_state_panics() {
7566 do_test_data_loss_protect(true);
7570 fn test_force_close_without_broadcast() {
7571 do_test_data_loss_protect(false);
7575 fn test_check_htlc_underpaying() {
7576 // Send payment through A -> B but A is maliciously
7577 // sending a probe payment (i.e less than expected value0
7578 // to B, B should refuse payment.
7580 let chanmon_cfgs = create_chanmon_cfgs(2);
7581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7583 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7585 // Create some initial channels
7586 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7588 let scorer = test_utils::TestScorer::with_penalty(0);
7589 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7590 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7591 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();
7592 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7593 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7594 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7595 check_added_monitors!(nodes[0], 1);
7597 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7598 assert_eq!(events.len(), 1);
7599 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7600 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7601 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7603 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7604 // and then will wait a second random delay before failing the HTLC back:
7605 expect_pending_htlcs_forwardable!(nodes[1]);
7606 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7608 // Node 3 is expecting payment of 100_000 but received 10_000,
7609 // it should fail htlc like we didn't know the preimage.
7610 nodes[1].node.process_pending_htlc_forwards();
7612 let events = nodes[1].node.get_and_clear_pending_msg_events();
7613 assert_eq!(events.len(), 1);
7614 let (update_fail_htlc, commitment_signed) = match events[0] {
7615 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 } } => {
7616 assert!(update_add_htlcs.is_empty());
7617 assert!(update_fulfill_htlcs.is_empty());
7618 assert_eq!(update_fail_htlcs.len(), 1);
7619 assert!(update_fail_malformed_htlcs.is_empty());
7620 assert!(update_fee.is_none());
7621 (update_fail_htlcs[0].clone(), commitment_signed)
7623 _ => panic!("Unexpected event"),
7625 check_added_monitors!(nodes[1], 1);
7627 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7628 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7630 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7631 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7632 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7633 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7637 fn test_announce_disable_channels() {
7638 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7639 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7641 let chanmon_cfgs = create_chanmon_cfgs(2);
7642 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7643 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7644 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7646 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7647 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7648 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7651 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7652 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7654 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7655 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7656 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7657 assert_eq!(msg_events.len(), 3);
7658 let mut chans_disabled = HashMap::new();
7659 for e in msg_events {
7661 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7662 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7663 // Check that each channel gets updated exactly once
7664 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7665 panic!("Generated ChannelUpdate for wrong chan!");
7668 _ => panic!("Unexpected event"),
7672 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7673 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7674 assert_eq!(reestablish_1.len(), 3);
7675 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7676 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7677 assert_eq!(reestablish_2.len(), 3);
7679 // Reestablish chan_1
7680 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7681 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7682 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7683 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7684 // Reestablish chan_2
7685 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7686 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7687 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7688 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7689 // Reestablish chan_3
7690 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7691 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7692 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7693 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7695 nodes[0].node.timer_tick_occurred();
7696 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7697 nodes[0].node.timer_tick_occurred();
7698 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7699 assert_eq!(msg_events.len(), 3);
7700 for e in msg_events {
7702 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7703 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7704 match chans_disabled.remove(&msg.contents.short_channel_id) {
7705 // Each update should have a higher timestamp than the previous one, replacing
7707 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7708 None => panic!("Generated ChannelUpdate for wrong chan!"),
7711 _ => panic!("Unexpected event"),
7714 // Check that each channel gets updated exactly once
7715 assert!(chans_disabled.is_empty());
7719 fn test_bump_penalty_txn_on_revoked_commitment() {
7720 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7721 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7723 let chanmon_cfgs = create_chanmon_cfgs(2);
7724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7726 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7728 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7730 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7731 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7732 .with_features(InvoiceFeatures::known());
7733 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7734 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7736 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7737 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7738 assert_eq!(revoked_txn[0].output.len(), 4);
7739 assert_eq!(revoked_txn[0].input.len(), 1);
7740 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7741 let revoked_txid = revoked_txn[0].txid();
7743 let mut penalty_sum = 0;
7744 for outp in revoked_txn[0].output.iter() {
7745 if outp.script_pubkey.is_v0_p2wsh() {
7746 penalty_sum += outp.value;
7750 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7751 let header_114 = connect_blocks(&nodes[1], 14);
7753 // Actually revoke tx by claiming a HTLC
7754 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7755 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7756 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7757 check_added_monitors!(nodes[1], 1);
7759 // One or more justice tx should have been broadcast, check it
7763 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7764 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7765 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7766 assert_eq!(node_txn[0].output.len(), 1);
7767 check_spends!(node_txn[0], revoked_txn[0]);
7768 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7769 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7770 penalty_1 = node_txn[0].txid();
7774 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7775 connect_blocks(&nodes[1], 15);
7776 let mut penalty_2 = penalty_1;
7777 let mut feerate_2 = 0;
7779 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7780 assert_eq!(node_txn.len(), 1);
7781 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7782 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7783 assert_eq!(node_txn[0].output.len(), 1);
7784 check_spends!(node_txn[0], revoked_txn[0]);
7785 penalty_2 = node_txn[0].txid();
7786 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7787 assert_ne!(penalty_2, penalty_1);
7788 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7789 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7790 // Verify 25% bump heuristic
7791 assert!(feerate_2 * 100 >= feerate_1 * 125);
7795 assert_ne!(feerate_2, 0);
7797 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7798 connect_blocks(&nodes[1], 1);
7800 let mut feerate_3 = 0;
7802 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7803 assert_eq!(node_txn.len(), 1);
7804 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7805 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7806 assert_eq!(node_txn[0].output.len(), 1);
7807 check_spends!(node_txn[0], revoked_txn[0]);
7808 penalty_3 = node_txn[0].txid();
7809 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7810 assert_ne!(penalty_3, penalty_2);
7811 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7812 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7813 // Verify 25% bump heuristic
7814 assert!(feerate_3 * 100 >= feerate_2 * 125);
7818 assert_ne!(feerate_3, 0);
7820 nodes[1].node.get_and_clear_pending_events();
7821 nodes[1].node.get_and_clear_pending_msg_events();
7825 fn test_bump_penalty_txn_on_revoked_htlcs() {
7826 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7827 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7829 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7830 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7831 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7833 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7835 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7836 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7837 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7838 let scorer = test_utils::TestScorer::with_penalty(0);
7839 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7840 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7841 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7842 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7843 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7844 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7845 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7846 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7848 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7849 assert_eq!(revoked_local_txn[0].input.len(), 1);
7850 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7852 // Revoke local commitment tx
7853 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7855 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7856 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7857 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7858 check_closed_broadcast!(nodes[1], true);
7859 check_added_monitors!(nodes[1], 1);
7860 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7861 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7863 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7864 assert_eq!(revoked_htlc_txn.len(), 3);
7865 check_spends!(revoked_htlc_txn[1], chan.3);
7867 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7868 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7869 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7871 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7872 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7873 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7874 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7876 // Broadcast set of revoked txn on A
7877 let hash_128 = connect_blocks(&nodes[0], 40);
7878 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7879 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7880 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7881 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7882 let events = nodes[0].node.get_and_clear_pending_events();
7883 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7884 match events.last().unwrap() {
7885 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7886 _ => panic!("Unexpected event"),
7892 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7893 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7894 // Verify claim tx are spending revoked HTLC txn
7896 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7897 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7898 // which are included in the same block (they are broadcasted because we scan the
7899 // transactions linearly and generate claims as we go, they likely should be removed in the
7901 assert_eq!(node_txn[0].input.len(), 1);
7902 check_spends!(node_txn[0], revoked_local_txn[0]);
7903 assert_eq!(node_txn[1].input.len(), 1);
7904 check_spends!(node_txn[1], revoked_local_txn[0]);
7905 assert_eq!(node_txn[2].input.len(), 1);
7906 check_spends!(node_txn[2], revoked_local_txn[0]);
7908 // Each of the three justice transactions claim a separate (single) output of the three
7909 // available, which we check here:
7910 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7911 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7912 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7914 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7915 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7917 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7918 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7919 // a remote commitment tx has already been confirmed).
7920 check_spends!(node_txn[3], chan.3);
7922 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7923 // output, checked above).
7924 assert_eq!(node_txn[4].input.len(), 2);
7925 assert_eq!(node_txn[4].output.len(), 1);
7926 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7928 first = node_txn[4].txid();
7929 // Store both feerates for later comparison
7930 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7931 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7932 penalty_txn = vec![node_txn[2].clone()];
7936 // Connect one more block to see if bumped penalty are issued for HTLC txn
7937 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7938 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7939 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7940 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7942 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7943 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7945 check_spends!(node_txn[0], revoked_local_txn[0]);
7946 check_spends!(node_txn[1], revoked_local_txn[0]);
7947 // Note that these are both bogus - they spend outputs already claimed in block 129:
7948 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7949 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7951 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7952 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7958 // Few more blocks to confirm penalty txn
7959 connect_blocks(&nodes[0], 4);
7960 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7961 let header_144 = connect_blocks(&nodes[0], 9);
7963 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7964 assert_eq!(node_txn.len(), 1);
7966 assert_eq!(node_txn[0].input.len(), 2);
7967 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7968 // Verify bumped tx is different and 25% bump heuristic
7969 assert_ne!(first, node_txn[0].txid());
7970 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7971 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7972 assert!(feerate_2 * 100 > feerate_1 * 125);
7973 let txn = vec![node_txn[0].clone()];
7977 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7978 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7979 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7980 connect_blocks(&nodes[0], 20);
7982 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7983 // We verify than no new transaction has been broadcast because previously
7984 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7985 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7986 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7987 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7988 // up bumped justice generation.
7989 assert_eq!(node_txn.len(), 0);
7992 check_closed_broadcast!(nodes[0], true);
7993 check_added_monitors!(nodes[0], 1);
7997 fn test_bump_penalty_txn_on_remote_commitment() {
7998 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7999 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8002 // Provide preimage for one
8003 // Check aggregation
8005 let chanmon_cfgs = create_chanmon_cfgs(2);
8006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8008 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8010 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8011 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8012 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8014 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8015 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8016 assert_eq!(remote_txn[0].output.len(), 4);
8017 assert_eq!(remote_txn[0].input.len(), 1);
8018 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8020 // Claim a HTLC without revocation (provide B monitor with preimage)
8021 nodes[1].node.claim_funds(payment_preimage);
8022 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8023 mine_transaction(&nodes[1], &remote_txn[0]);
8024 check_added_monitors!(nodes[1], 2);
8025 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8027 // One or more claim tx should have been broadcast, check it
8031 let feerate_timeout;
8032 let feerate_preimage;
8034 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8035 // 9 transactions including:
8036 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8037 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8038 // 2 * HTLC-Success (one RBF bump we'll check later)
8040 assert_eq!(node_txn.len(), 8);
8041 assert_eq!(node_txn[0].input.len(), 1);
8042 assert_eq!(node_txn[6].input.len(), 1);
8043 check_spends!(node_txn[0], remote_txn[0]);
8044 check_spends!(node_txn[6], remote_txn[0]);
8046 check_spends!(node_txn[1], chan.3);
8047 check_spends!(node_txn[2], node_txn[1]);
8049 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8050 preimage_bump = node_txn[3].clone();
8051 check_spends!(node_txn[3], remote_txn[0]);
8053 assert_eq!(node_txn[1], node_txn[4]);
8054 assert_eq!(node_txn[2], node_txn[5]);
8056 preimage_bump = node_txn[7].clone();
8057 check_spends!(node_txn[7], remote_txn[0]);
8058 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8060 assert_eq!(node_txn[1], node_txn[3]);
8061 assert_eq!(node_txn[2], node_txn[4]);
8064 timeout = node_txn[6].txid();
8065 let index = node_txn[6].input[0].previous_output.vout;
8066 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8067 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8069 preimage = node_txn[0].txid();
8070 let index = node_txn[0].input[0].previous_output.vout;
8071 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8072 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8076 assert_ne!(feerate_timeout, 0);
8077 assert_ne!(feerate_preimage, 0);
8079 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8080 connect_blocks(&nodes[1], 15);
8082 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8083 assert_eq!(node_txn.len(), 1);
8084 assert_eq!(node_txn[0].input.len(), 1);
8085 assert_eq!(preimage_bump.input.len(), 1);
8086 check_spends!(node_txn[0], remote_txn[0]);
8087 check_spends!(preimage_bump, remote_txn[0]);
8089 let index = preimage_bump.input[0].previous_output.vout;
8090 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8091 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8092 assert!(new_feerate * 100 > feerate_timeout * 125);
8093 assert_ne!(timeout, preimage_bump.txid());
8095 let index = node_txn[0].input[0].previous_output.vout;
8096 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8097 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8098 assert!(new_feerate * 100 > feerate_preimage * 125);
8099 assert_ne!(preimage, node_txn[0].txid());
8104 nodes[1].node.get_and_clear_pending_events();
8105 nodes[1].node.get_and_clear_pending_msg_events();
8109 fn test_counterparty_raa_skip_no_crash() {
8110 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8111 // commitment transaction, we would have happily carried on and provided them the next
8112 // commitment transaction based on one RAA forward. This would probably eventually have led to
8113 // channel closure, but it would not have resulted in funds loss. Still, our
8114 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8115 // check simply that the channel is closed in response to such an RAA, but don't check whether
8116 // we decide to punish our counterparty for revoking their funds (as we don't currently
8118 let chanmon_cfgs = create_chanmon_cfgs(2);
8119 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8120 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8121 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8122 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8124 let per_commitment_secret;
8125 let next_per_commitment_point;
8127 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8128 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8130 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8132 // Make signer believe we got a counterparty signature, so that it allows the revocation
8133 keys.get_enforcement_state().last_holder_commitment -= 1;
8134 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8136 // Must revoke without gaps
8137 keys.get_enforcement_state().last_holder_commitment -= 1;
8138 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8140 keys.get_enforcement_state().last_holder_commitment -= 1;
8141 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8142 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8145 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8146 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8147 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8148 check_added_monitors!(nodes[1], 1);
8149 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8153 fn test_bump_txn_sanitize_tracking_maps() {
8154 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8155 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8157 let chanmon_cfgs = create_chanmon_cfgs(2);
8158 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8159 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8160 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8162 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8163 // Lock HTLC in both directions
8164 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8165 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8167 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8168 assert_eq!(revoked_local_txn[0].input.len(), 1);
8169 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8171 // Revoke local commitment tx
8172 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8174 // Broadcast set of revoked txn on A
8175 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8176 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8177 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8179 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8180 check_closed_broadcast!(nodes[0], true);
8181 check_added_monitors!(nodes[0], 1);
8182 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8184 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8185 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8186 check_spends!(node_txn[0], revoked_local_txn[0]);
8187 check_spends!(node_txn[1], revoked_local_txn[0]);
8188 check_spends!(node_txn[2], revoked_local_txn[0]);
8189 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8193 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8194 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8195 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8197 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8198 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8199 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8204 fn test_pending_claimed_htlc_no_balance_underflow() {
8205 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8206 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8207 let chanmon_cfgs = create_chanmon_cfgs(2);
8208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8210 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8211 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8213 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8214 nodes[1].node.claim_funds(payment_preimage);
8215 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8216 check_added_monitors!(nodes[1], 1);
8217 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8219 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8220 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8221 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8222 check_added_monitors!(nodes[0], 1);
8223 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8225 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8226 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8227 // can get our balance.
8229 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8230 // the public key of the only hop. This works around ChannelDetails not showing the
8231 // almost-claimed HTLC as available balance.
8232 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8233 route.payment_params = None; // This is all wrong, but unnecessary
8234 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8235 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8236 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8238 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8242 fn test_channel_conf_timeout() {
8243 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8244 // confirm within 2016 blocks, as recommended by BOLT 2.
8245 let chanmon_cfgs = create_chanmon_cfgs(2);
8246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8250 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8252 // The outbound node should wait forever for confirmation:
8253 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8254 // copied here instead of directly referencing the constant.
8255 connect_blocks(&nodes[0], 2016);
8256 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8258 // The inbound node should fail the channel after exactly 2016 blocks
8259 connect_blocks(&nodes[1], 2015);
8260 check_added_monitors!(nodes[1], 0);
8261 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8263 connect_blocks(&nodes[1], 1);
8264 check_added_monitors!(nodes[1], 1);
8265 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8266 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8267 assert_eq!(close_ev.len(), 1);
8269 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8270 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8271 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8273 _ => panic!("Unexpected event"),
8278 fn test_override_channel_config() {
8279 let chanmon_cfgs = create_chanmon_cfgs(2);
8280 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8281 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8282 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8284 // Node0 initiates a channel to node1 using the override config.
8285 let mut override_config = UserConfig::default();
8286 override_config.channel_handshake_config.our_to_self_delay = 200;
8288 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8290 // Assert the channel created by node0 is using the override config.
8291 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8292 assert_eq!(res.channel_flags, 0);
8293 assert_eq!(res.to_self_delay, 200);
8297 fn test_override_0msat_htlc_minimum() {
8298 let mut zero_config = UserConfig::default();
8299 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8300 let chanmon_cfgs = create_chanmon_cfgs(2);
8301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8303 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8305 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8306 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8307 assert_eq!(res.htlc_minimum_msat, 1);
8309 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8310 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8311 assert_eq!(res.htlc_minimum_msat, 1);
8315 fn test_channel_update_has_correct_htlc_maximum_msat() {
8316 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8317 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8318 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8319 // 90% of the `channel_value`.
8320 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8322 let mut config_30_percent = UserConfig::default();
8323 config_30_percent.channel_handshake_config.announced_channel = true;
8324 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8325 let mut config_50_percent = UserConfig::default();
8326 config_50_percent.channel_handshake_config.announced_channel = true;
8327 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8328 let mut config_95_percent = UserConfig::default();
8329 config_95_percent.channel_handshake_config.announced_channel = true;
8330 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8331 let mut config_100_percent = UserConfig::default();
8332 config_100_percent.channel_handshake_config.announced_channel = true;
8333 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8335 let chanmon_cfgs = create_chanmon_cfgs(4);
8336 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8337 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)]);
8338 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8340 let channel_value_satoshis = 100000;
8341 let channel_value_msat = channel_value_satoshis * 1000;
8342 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8343 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8344 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8346 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());
8347 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());
8349 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8350 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8351 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8352 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8353 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8354 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8356 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8357 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8359 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8360 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8361 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8363 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8367 fn test_manually_accept_inbound_channel_request() {
8368 let mut manually_accept_conf = UserConfig::default();
8369 manually_accept_conf.manually_accept_inbound_channels = true;
8370 let chanmon_cfgs = create_chanmon_cfgs(2);
8371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8373 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8375 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8376 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8378 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8380 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8381 // accepting the inbound channel request.
8382 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8384 let events = nodes[1].node.get_and_clear_pending_events();
8386 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8387 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8389 _ => panic!("Unexpected event"),
8392 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8393 assert_eq!(accept_msg_ev.len(), 1);
8395 match accept_msg_ev[0] {
8396 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8397 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8399 _ => panic!("Unexpected event"),
8402 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8404 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8405 assert_eq!(close_msg_ev.len(), 1);
8407 let events = nodes[1].node.get_and_clear_pending_events();
8409 Event::ChannelClosed { user_channel_id, .. } => {
8410 assert_eq!(user_channel_id, 23);
8412 _ => panic!("Unexpected event"),
8417 fn test_manually_reject_inbound_channel_request() {
8418 let mut manually_accept_conf = UserConfig::default();
8419 manually_accept_conf.manually_accept_inbound_channels = true;
8420 let chanmon_cfgs = create_chanmon_cfgs(2);
8421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8423 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8425 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8426 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8428 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8430 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8431 // rejecting the inbound channel request.
8432 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8434 let events = nodes[1].node.get_and_clear_pending_events();
8436 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8437 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8439 _ => panic!("Unexpected event"),
8442 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8443 assert_eq!(close_msg_ev.len(), 1);
8445 match close_msg_ev[0] {
8446 MessageSendEvent::HandleError { ref node_id, .. } => {
8447 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8449 _ => panic!("Unexpected event"),
8451 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8455 fn test_reject_funding_before_inbound_channel_accepted() {
8456 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8457 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8458 // the node operator before the counterparty sends a `FundingCreated` message. If a
8459 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8460 // and the channel should be closed.
8461 let mut manually_accept_conf = UserConfig::default();
8462 manually_accept_conf.manually_accept_inbound_channels = true;
8463 let chanmon_cfgs = create_chanmon_cfgs(2);
8464 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8465 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8466 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8468 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8469 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8470 let temp_channel_id = res.temporary_channel_id;
8472 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8474 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8475 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8477 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8478 nodes[1].node.get_and_clear_pending_events();
8480 // Get the `AcceptChannel` message of `nodes[1]` without calling
8481 // `ChannelManager::accept_inbound_channel`, which generates a
8482 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8483 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8484 // succeed when `nodes[0]` is passed to it.
8485 let accept_chan_msg = {
8487 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8488 channel.get_accept_channel_message()
8490 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8492 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8494 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8495 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8497 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8498 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8500 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8501 assert_eq!(close_msg_ev.len(), 1);
8503 let expected_err = "FundingCreated message received before the channel was accepted";
8504 match close_msg_ev[0] {
8505 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8506 assert_eq!(msg.channel_id, temp_channel_id);
8507 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8508 assert_eq!(msg.data, expected_err);
8510 _ => panic!("Unexpected event"),
8513 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8517 fn test_can_not_accept_inbound_channel_twice() {
8518 let mut manually_accept_conf = UserConfig::default();
8519 manually_accept_conf.manually_accept_inbound_channels = true;
8520 let chanmon_cfgs = create_chanmon_cfgs(2);
8521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8523 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8525 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8526 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8528 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8530 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8531 // accepting the inbound channel request.
8532 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8534 let events = nodes[1].node.get_and_clear_pending_events();
8536 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8537 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8538 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8540 Err(APIError::APIMisuseError { err }) => {
8541 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8543 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8544 Err(_) => panic!("Unexpected Error"),
8547 _ => panic!("Unexpected event"),
8550 // Ensure that the channel wasn't closed after attempting to accept it twice.
8551 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8552 assert_eq!(accept_msg_ev.len(), 1);
8554 match accept_msg_ev[0] {
8555 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8556 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8558 _ => panic!("Unexpected event"),
8563 fn test_can_not_accept_unknown_inbound_channel() {
8564 let chanmon_cfg = create_chanmon_cfgs(2);
8565 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8566 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8567 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8569 let unknown_channel_id = [0; 32];
8570 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8572 Err(APIError::ChannelUnavailable { err }) => {
8573 assert_eq!(err, "Can't accept a channel that doesn't exist");
8575 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8576 Err(_) => panic!("Unexpected Error"),
8581 fn test_simple_mpp() {
8582 // Simple test of sending a multi-path payment.
8583 let chanmon_cfgs = create_chanmon_cfgs(4);
8584 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8585 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8586 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8588 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8589 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8590 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8591 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8593 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8594 let path = route.paths[0].clone();
8595 route.paths.push(path);
8596 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8597 route.paths[0][0].short_channel_id = chan_1_id;
8598 route.paths[0][1].short_channel_id = chan_3_id;
8599 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8600 route.paths[1][0].short_channel_id = chan_2_id;
8601 route.paths[1][1].short_channel_id = chan_4_id;
8602 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8603 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8607 fn test_preimage_storage() {
8608 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8609 let chanmon_cfgs = create_chanmon_cfgs(2);
8610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8612 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8614 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8617 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8618 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8619 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8620 check_added_monitors!(nodes[0], 1);
8621 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8622 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8624 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8626 // Note that after leaving the above scope we have no knowledge of any arguments or return
8627 // values from previous calls.
8628 expect_pending_htlcs_forwardable!(nodes[1]);
8629 let events = nodes[1].node.get_and_clear_pending_events();
8630 assert_eq!(events.len(), 1);
8632 Event::PaymentReceived { ref purpose, .. } => {
8634 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8635 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8637 _ => panic!("expected PaymentPurpose::InvoicePayment")
8640 _ => panic!("Unexpected event"),
8645 #[allow(deprecated)]
8646 fn test_secret_timeout() {
8647 // Simple test of payment secret storage time outs. After
8648 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8649 let chanmon_cfgs = create_chanmon_cfgs(2);
8650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8652 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8654 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8656 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8658 // We should fail to register the same payment hash twice, at least until we've connected a
8659 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8660 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8661 assert_eq!(err, "Duplicate payment hash");
8662 } else { panic!(); }
8664 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8666 header: BlockHeader {
8668 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8669 merkle_root: TxMerkleNode::all_zeros(),
8670 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8674 connect_block(&nodes[1], &block);
8675 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8676 assert_eq!(err, "Duplicate payment hash");
8677 } else { panic!(); }
8679 // If we then connect the second block, we should be able to register the same payment hash
8680 // again (this time getting a new payment secret).
8681 block.header.prev_blockhash = block.header.block_hash();
8682 block.header.time += 1;
8683 connect_block(&nodes[1], &block);
8684 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8685 assert_ne!(payment_secret_1, our_payment_secret);
8688 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8689 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8690 check_added_monitors!(nodes[0], 1);
8691 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8692 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8693 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8694 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8696 // Note that after leaving the above scope we have no knowledge of any arguments or return
8697 // values from previous calls.
8698 expect_pending_htlcs_forwardable!(nodes[1]);
8699 let events = nodes[1].node.get_and_clear_pending_events();
8700 assert_eq!(events.len(), 1);
8702 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8703 assert!(payment_preimage.is_none());
8704 assert_eq!(payment_secret, our_payment_secret);
8705 // We don't actually have the payment preimage with which to claim this payment!
8707 _ => panic!("Unexpected event"),
8712 fn test_bad_secret_hash() {
8713 // Simple test of unregistered payment hash/invalid payment secret handling
8714 let chanmon_cfgs = create_chanmon_cfgs(2);
8715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8717 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8719 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8721 let random_payment_hash = PaymentHash([42; 32]);
8722 let random_payment_secret = PaymentSecret([43; 32]);
8723 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8724 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8726 // All the below cases should end up being handled exactly identically, so we macro the
8727 // resulting events.
8728 macro_rules! handle_unknown_invalid_payment_data {
8729 ($payment_hash: expr) => {
8730 check_added_monitors!(nodes[0], 1);
8731 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8732 let payment_event = SendEvent::from_event(events.pop().unwrap());
8733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8734 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8736 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8737 // again to process the pending backwards-failure of the HTLC
8738 expect_pending_htlcs_forwardable!(nodes[1]);
8739 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8740 check_added_monitors!(nodes[1], 1);
8742 // We should fail the payment back
8743 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8744 match events.pop().unwrap() {
8745 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8746 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8747 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8749 _ => panic!("Unexpected event"),
8754 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8755 // Error data is the HTLC value (100,000) and current block height
8756 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8758 // Send a payment with the right payment hash but the wrong payment secret
8759 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8760 handle_unknown_invalid_payment_data!(our_payment_hash);
8761 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8763 // Send a payment with a random payment hash, but the right payment secret
8764 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8765 handle_unknown_invalid_payment_data!(random_payment_hash);
8766 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8768 // Send a payment with a random payment hash and random payment secret
8769 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8770 handle_unknown_invalid_payment_data!(random_payment_hash);
8771 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8775 fn test_update_err_monitor_lockdown() {
8776 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8777 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8778 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8780 // This scenario may happen in a watchtower setup, where watchtower process a block height
8781 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8782 // commitment at same time.
8784 let chanmon_cfgs = create_chanmon_cfgs(2);
8785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8787 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8789 // Create some initial channel
8790 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8791 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8793 // Rebalance the network to generate htlc in the two directions
8794 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8796 // Route a HTLC from node 0 to node 1 (but don't settle)
8797 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8799 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8800 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8801 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8802 let persister = test_utils::TestPersister::new();
8804 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8805 let mut w = test_utils::TestVecWriter(Vec::new());
8806 monitor.write(&mut w).unwrap();
8807 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8808 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8809 assert!(new_monitor == *monitor);
8810 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);
8811 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8814 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8815 let block = Block { header, txdata: vec![] };
8816 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8817 // transaction lock time requirements here.
8818 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8819 watchtower.chain_monitor.block_connected(&block, 200);
8821 // Try to update ChannelMonitor
8822 nodes[1].node.claim_funds(preimage);
8823 check_added_monitors!(nodes[1], 1);
8824 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8826 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8827 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8828 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8829 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8830 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8831 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8832 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8833 } else { assert!(false); }
8834 } else { assert!(false); };
8835 // Our local monitor is in-sync and hasn't processed yet timeout
8836 check_added_monitors!(nodes[0], 1);
8837 let events = nodes[0].node.get_and_clear_pending_events();
8838 assert_eq!(events.len(), 1);
8842 fn test_concurrent_monitor_claim() {
8843 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8844 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8845 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8846 // state N+1 confirms. Alice claims output from state N+1.
8848 let chanmon_cfgs = create_chanmon_cfgs(2);
8849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8851 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8853 // Create some initial channel
8854 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8855 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8857 // Rebalance the network to generate htlc in the two directions
8858 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8860 // Route a HTLC from node 0 to node 1 (but don't settle)
8861 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8863 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8864 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8865 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8866 let persister = test_utils::TestPersister::new();
8867 let watchtower_alice = {
8868 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8869 let mut w = test_utils::TestVecWriter(Vec::new());
8870 monitor.write(&mut w).unwrap();
8871 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8872 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8873 assert!(new_monitor == *monitor);
8874 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);
8875 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8878 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8879 let block = Block { header, txdata: vec![] };
8880 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8881 // transaction lock time requirements here.
8882 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));
8883 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8885 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8887 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8888 assert_eq!(txn.len(), 2);
8892 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8893 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8894 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8895 let persister = test_utils::TestPersister::new();
8896 let watchtower_bob = {
8897 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8898 let mut w = test_utils::TestVecWriter(Vec::new());
8899 monitor.write(&mut w).unwrap();
8900 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8901 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8902 assert!(new_monitor == *monitor);
8903 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);
8904 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8907 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8908 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8910 // Route another payment to generate another update with still previous HTLC pending
8911 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8913 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8915 check_added_monitors!(nodes[1], 1);
8917 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8918 assert_eq!(updates.update_add_htlcs.len(), 1);
8919 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8920 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8921 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8922 // Watchtower Alice should already have seen the block and reject the update
8923 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8924 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8925 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8926 } else { assert!(false); }
8927 } else { assert!(false); };
8928 // Our local monitor is in-sync and hasn't processed yet timeout
8929 check_added_monitors!(nodes[0], 1);
8931 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8932 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8933 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8935 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8938 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8939 assert_eq!(txn.len(), 2);
8940 bob_state_y = txn[0].clone();
8944 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8945 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8946 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);
8948 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8949 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8950 // the onchain detection of the HTLC output
8951 assert_eq!(htlc_txn.len(), 2);
8952 check_spends!(htlc_txn[0], bob_state_y);
8953 check_spends!(htlc_txn[1], bob_state_y);
8958 fn test_pre_lockin_no_chan_closed_update() {
8959 // Test that if a peer closes a channel in response to a funding_created message we don't
8960 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8963 // Doing so would imply a channel monitor update before the initial channel monitor
8964 // registration, violating our API guarantees.
8966 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8967 // then opening a second channel with the same funding output as the first (which is not
8968 // rejected because the first channel does not exist in the ChannelManager) and closing it
8969 // before receiving funding_signed.
8970 let chanmon_cfgs = create_chanmon_cfgs(2);
8971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8973 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8975 // Create an initial channel
8976 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8977 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8978 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8979 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8980 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8982 // Move the first channel through the funding flow...
8983 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8985 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8986 check_added_monitors!(nodes[0], 0);
8988 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8989 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8990 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8991 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8992 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8996 fn test_htlc_no_detection() {
8997 // This test is a mutation to underscore the detection logic bug we had
8998 // before #653. HTLC value routed is above the remaining balance, thus
8999 // inverting HTLC and `to_remote` output. HTLC will come second and
9000 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9001 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9002 // outputs order detection for correct spending children filtring.
9004 let chanmon_cfgs = create_chanmon_cfgs(2);
9005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9007 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9009 // Create some initial channels
9010 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9012 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9013 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9014 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9015 assert_eq!(local_txn[0].input.len(), 1);
9016 assert_eq!(local_txn[0].output.len(), 3);
9017 check_spends!(local_txn[0], chan_1.3);
9019 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9020 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9021 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9022 // We deliberately connect the local tx twice as this should provoke a failure calling
9023 // this test before #653 fix.
9024 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);
9025 check_closed_broadcast!(nodes[0], true);
9026 check_added_monitors!(nodes[0], 1);
9027 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9028 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9030 let htlc_timeout = {
9031 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9032 assert_eq!(node_txn[1].input.len(), 1);
9033 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9034 check_spends!(node_txn[1], local_txn[0]);
9038 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
9039 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9040 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9041 expect_payment_failed!(nodes[0], our_payment_hash, false);
9044 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9045 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9046 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9047 // Carol, Alice would be the upstream node, and Carol the downstream.)
9049 // Steps of the test:
9050 // 1) Alice sends a HTLC to Carol through Bob.
9051 // 2) Carol doesn't settle the HTLC.
9052 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9053 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9054 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9055 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9056 // 5) Carol release the preimage to Bob off-chain.
9057 // 6) Bob claims the offered output on the broadcasted commitment.
9058 let chanmon_cfgs = create_chanmon_cfgs(3);
9059 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9060 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9061 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9063 // Create some initial channels
9064 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9065 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9067 // Steps (1) and (2):
9068 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9069 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9071 // Check that Alice's commitment transaction now contains an output for this HTLC.
9072 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9073 check_spends!(alice_txn[0], chan_ab.3);
9074 assert_eq!(alice_txn[0].output.len(), 2);
9075 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9076 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9077 assert_eq!(alice_txn.len(), 2);
9079 // Steps (3) and (4):
9080 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9081 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9082 let mut force_closing_node = 0; // Alice force-closes
9083 let mut counterparty_node = 1; // Bob if Alice force-closes
9086 if !broadcast_alice {
9087 force_closing_node = 1;
9088 counterparty_node = 0;
9090 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9091 check_closed_broadcast!(nodes[force_closing_node], true);
9092 check_added_monitors!(nodes[force_closing_node], 1);
9093 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9094 if go_onchain_before_fulfill {
9095 let txn_to_broadcast = match broadcast_alice {
9096 true => alice_txn.clone(),
9097 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9099 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9100 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9101 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9102 if broadcast_alice {
9103 check_closed_broadcast!(nodes[1], true);
9104 check_added_monitors!(nodes[1], 1);
9105 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9107 assert_eq!(bob_txn.len(), 1);
9108 check_spends!(bob_txn[0], chan_ab.3);
9112 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9113 // process of removing the HTLC from their commitment transactions.
9114 nodes[2].node.claim_funds(payment_preimage);
9115 check_added_monitors!(nodes[2], 1);
9116 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9118 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9119 assert!(carol_updates.update_add_htlcs.is_empty());
9120 assert!(carol_updates.update_fail_htlcs.is_empty());
9121 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9122 assert!(carol_updates.update_fee.is_none());
9123 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9125 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9126 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9127 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9128 if !go_onchain_before_fulfill && broadcast_alice {
9129 let events = nodes[1].node.get_and_clear_pending_msg_events();
9130 assert_eq!(events.len(), 1);
9132 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9133 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9135 _ => panic!("Unexpected event"),
9138 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9139 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9140 // Carol<->Bob's updated commitment transaction info.
9141 check_added_monitors!(nodes[1], 2);
9143 let events = nodes[1].node.get_and_clear_pending_msg_events();
9144 assert_eq!(events.len(), 2);
9145 let bob_revocation = match events[0] {
9146 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9147 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9150 _ => panic!("Unexpected event"),
9152 let bob_updates = match events[1] {
9153 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9154 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9157 _ => panic!("Unexpected event"),
9160 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9161 check_added_monitors!(nodes[2], 1);
9162 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9163 check_added_monitors!(nodes[2], 1);
9165 let events = nodes[2].node.get_and_clear_pending_msg_events();
9166 assert_eq!(events.len(), 1);
9167 let carol_revocation = match events[0] {
9168 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9169 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9172 _ => panic!("Unexpected event"),
9174 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9175 check_added_monitors!(nodes[1], 1);
9177 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9178 // here's where we put said channel's commitment tx on-chain.
9179 let mut txn_to_broadcast = alice_txn.clone();
9180 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9181 if !go_onchain_before_fulfill {
9182 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
9183 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9184 // If Bob was the one to force-close, he will have already passed these checks earlier.
9185 if broadcast_alice {
9186 check_closed_broadcast!(nodes[1], true);
9187 check_added_monitors!(nodes[1], 1);
9188 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9190 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9191 if broadcast_alice {
9192 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9193 // new block being connected. The ChannelManager being notified triggers a monitor update,
9194 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9195 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9197 assert_eq!(bob_txn.len(), 3);
9198 check_spends!(bob_txn[1], chan_ab.3);
9200 assert_eq!(bob_txn.len(), 2);
9201 check_spends!(bob_txn[0], chan_ab.3);
9206 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9207 // broadcasted commitment transaction.
9209 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9210 if go_onchain_before_fulfill {
9211 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9212 assert_eq!(bob_txn.len(), 2);
9214 let script_weight = match broadcast_alice {
9215 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9216 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9218 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9219 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9220 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9221 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9222 if broadcast_alice && !go_onchain_before_fulfill {
9223 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9224 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9226 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9227 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9233 fn test_onchain_htlc_settlement_after_close() {
9234 do_test_onchain_htlc_settlement_after_close(true, true);
9235 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9236 do_test_onchain_htlc_settlement_after_close(true, false);
9237 do_test_onchain_htlc_settlement_after_close(false, false);
9241 fn test_duplicate_chan_id() {
9242 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9243 // already open we reject it and keep the old channel.
9245 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9246 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9247 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9248 // updating logic for the existing channel.
9249 let chanmon_cfgs = create_chanmon_cfgs(2);
9250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9252 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9254 // Create an initial channel
9255 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9256 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9257 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9258 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()));
9260 // Try to create a second channel with the same temporary_channel_id as the first and check
9261 // that it is rejected.
9262 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9264 let events = nodes[1].node.get_and_clear_pending_msg_events();
9265 assert_eq!(events.len(), 1);
9267 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9268 // Technically, at this point, nodes[1] would be justified in thinking both the
9269 // first (valid) and second (invalid) channels are closed, given they both have
9270 // the same non-temporary channel_id. However, currently we do not, so we just
9271 // move forward with it.
9272 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9273 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9275 _ => panic!("Unexpected event"),
9279 // Move the first channel through the funding flow...
9280 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9282 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9283 check_added_monitors!(nodes[0], 0);
9285 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9286 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9288 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9289 assert_eq!(added_monitors.len(), 1);
9290 assert_eq!(added_monitors[0].0, funding_output);
9291 added_monitors.clear();
9293 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9295 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9296 let channel_id = funding_outpoint.to_channel_id();
9298 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9301 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9302 // Technically this is allowed by the spec, but we don't support it and there's little reason
9303 // to. Still, it shouldn't cause any other issues.
9304 open_chan_msg.temporary_channel_id = channel_id;
9305 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9307 let events = nodes[1].node.get_and_clear_pending_msg_events();
9308 assert_eq!(events.len(), 1);
9310 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9311 // Technically, at this point, nodes[1] would be justified in thinking both
9312 // channels are closed, but currently we do not, so we just move forward with it.
9313 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9314 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9316 _ => panic!("Unexpected event"),
9320 // Now try to create a second channel which has a duplicate funding output.
9321 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9322 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9323 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9324 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()));
9325 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9327 let funding_created = {
9328 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9329 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9330 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9331 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9332 // channelmanager in a possibly nonsense state instead).
9333 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9334 let logger = test_utils::TestLogger::new();
9335 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9337 check_added_monitors!(nodes[0], 0);
9338 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9339 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9340 // still needs to be cleared here.
9341 check_added_monitors!(nodes[1], 1);
9343 // ...still, nodes[1] will reject the duplicate channel.
9345 let events = nodes[1].node.get_and_clear_pending_msg_events();
9346 assert_eq!(events.len(), 1);
9348 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9349 // Technically, at this point, nodes[1] would be justified in thinking both
9350 // channels are closed, but currently we do not, so we just move forward with it.
9351 assert_eq!(msg.channel_id, channel_id);
9352 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9354 _ => panic!("Unexpected event"),
9358 // finally, finish creating the original channel and send a payment over it to make sure
9359 // everything is functional.
9360 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9362 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9363 assert_eq!(added_monitors.len(), 1);
9364 assert_eq!(added_monitors[0].0, funding_output);
9365 added_monitors.clear();
9368 let events_4 = nodes[0].node.get_and_clear_pending_events();
9369 assert_eq!(events_4.len(), 0);
9370 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9371 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9373 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9374 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9375 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9376 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9380 fn test_error_chans_closed() {
9381 // Test that we properly handle error messages, closing appropriate channels.
9383 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9384 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9385 // we can test various edge cases around it to ensure we don't regress.
9386 let chanmon_cfgs = create_chanmon_cfgs(3);
9387 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9388 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9389 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9391 // Create some initial channels
9392 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9393 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9394 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9396 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9397 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9398 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9400 // Closing a channel from a different peer has no effect
9401 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9402 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9404 // Closing one channel doesn't impact others
9405 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9406 check_added_monitors!(nodes[0], 1);
9407 check_closed_broadcast!(nodes[0], false);
9408 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9409 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9410 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9411 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);
9412 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);
9414 // A null channel ID should close all channels
9415 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9416 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9417 check_added_monitors!(nodes[0], 2);
9418 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9419 let events = nodes[0].node.get_and_clear_pending_msg_events();
9420 assert_eq!(events.len(), 2);
9422 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9423 assert_eq!(msg.contents.flags & 2, 2);
9425 _ => panic!("Unexpected event"),
9428 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9429 assert_eq!(msg.contents.flags & 2, 2);
9431 _ => panic!("Unexpected event"),
9433 // Note that at this point users of a standard PeerHandler will end up calling
9434 // peer_disconnected with no_connection_possible set to false, duplicating the
9435 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9436 // users with their own peer handling logic. We duplicate the call here, however.
9437 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9438 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9440 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9441 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9442 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9446 fn test_invalid_funding_tx() {
9447 // Test that we properly handle invalid funding transactions sent to us from a peer.
9449 // Previously, all other major lightning implementations had failed to properly sanitize
9450 // funding transactions from their counterparties, leading to a multi-implementation critical
9451 // security vulnerability (though we always sanitized properly, we've previously had
9452 // un-released crashes in the sanitization process).
9454 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9455 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9456 // gave up on it. We test this here by generating such a transaction.
9457 let chanmon_cfgs = create_chanmon_cfgs(2);
9458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9460 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9462 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9463 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()));
9464 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()));
9466 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9468 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9469 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9470 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9472 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9473 assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9474 chan_utils::HTLCType::AcceptedHTLC);
9476 let wit_program_script: Script = wit_program.clone().into();
9477 for output in tx.output.iter_mut() {
9478 // Make the confirmed funding transaction have a bogus script_pubkey
9479 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9482 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9483 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()));
9484 check_added_monitors!(nodes[1], 1);
9486 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()));
9487 check_added_monitors!(nodes[0], 1);
9489 let events_1 = nodes[0].node.get_and_clear_pending_events();
9490 assert_eq!(events_1.len(), 0);
9492 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9493 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9494 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9496 let expected_err = "funding tx had wrong script/value or output index";
9497 confirm_transaction_at(&nodes[1], &tx, 1);
9498 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9499 check_added_monitors!(nodes[1], 1);
9500 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9501 assert_eq!(events_2.len(), 1);
9502 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9503 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9504 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9505 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9506 } else { panic!(); }
9507 } else { panic!(); }
9508 assert_eq!(nodes[1].node.list_channels().len(), 0);
9510 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9511 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9512 // as its not 32 bytes long.
9513 let mut spend_tx = Transaction {
9514 version: 2i32, lock_time: PackedLockTime::ZERO,
9515 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9516 previous_output: BitcoinOutPoint {
9520 script_sig: Script::new(),
9521 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9522 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9524 output: vec![TxOut {
9526 script_pubkey: Script::new(),
9529 check_spends!(spend_tx, tx);
9530 mine_transaction(&nodes[1], &spend_tx);
9533 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9534 // In the first version of the chain::Confirm interface, after a refactor was made to not
9535 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9536 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9537 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9538 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9539 // spending transaction until height N+1 (or greater). This was due to the way
9540 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9541 // spending transaction at the height the input transaction was confirmed at, not whether we
9542 // should broadcast a spending transaction at the current height.
9543 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9544 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9545 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9546 // until we learned about an additional block.
9548 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9549 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9550 let chanmon_cfgs = create_chanmon_cfgs(3);
9551 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9552 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9553 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9554 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9556 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9557 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9558 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9559 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9560 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9562 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9563 check_closed_broadcast!(nodes[1], true);
9564 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9565 check_added_monitors!(nodes[1], 1);
9566 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9567 assert_eq!(node_txn.len(), 1);
9569 let conf_height = nodes[1].best_block_info().1;
9570 if !test_height_before_timelock {
9571 connect_blocks(&nodes[1], 24 * 6);
9573 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9574 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9575 if test_height_before_timelock {
9576 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9577 // generate any events or broadcast any transactions
9578 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9579 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9581 // We should broadcast an HTLC transaction spending our funding transaction first
9582 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9583 assert_eq!(spending_txn.len(), 2);
9584 assert_eq!(spending_txn[0], node_txn[0]);
9585 check_spends!(spending_txn[1], node_txn[0]);
9586 // We should also generate a SpendableOutputs event with the to_self output (as its
9588 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9589 assert_eq!(descriptor_spend_txn.len(), 1);
9591 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9592 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9593 // additional block built on top of the current chain.
9594 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9595 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9596 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9597 check_added_monitors!(nodes[1], 1);
9599 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9600 assert!(updates.update_add_htlcs.is_empty());
9601 assert!(updates.update_fulfill_htlcs.is_empty());
9602 assert_eq!(updates.update_fail_htlcs.len(), 1);
9603 assert!(updates.update_fail_malformed_htlcs.is_empty());
9604 assert!(updates.update_fee.is_none());
9605 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9606 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9607 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9612 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9613 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9614 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9618 fn test_forwardable_regen() {
9619 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9620 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9622 // We test it for both payment receipt and payment forwarding.
9624 let chanmon_cfgs = create_chanmon_cfgs(3);
9625 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9626 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9627 let persister: test_utils::TestPersister;
9628 let new_chain_monitor: test_utils::TestChainMonitor;
9629 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9630 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9631 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9632 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9634 // First send a payment to nodes[1]
9635 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9636 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9637 check_added_monitors!(nodes[0], 1);
9639 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9640 assert_eq!(events.len(), 1);
9641 let payment_event = SendEvent::from_event(events.pop().unwrap());
9642 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9643 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9645 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9647 // Next send a payment which is forwarded by nodes[1]
9648 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9649 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9650 check_added_monitors!(nodes[0], 1);
9652 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9653 assert_eq!(events.len(), 1);
9654 let payment_event = SendEvent::from_event(events.pop().unwrap());
9655 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9656 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9658 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9660 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9662 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9663 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9664 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9666 let nodes_1_serialized = nodes[1].node.encode();
9667 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9668 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9669 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9670 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9672 persister = test_utils::TestPersister::new();
9673 let keys_manager = &chanmon_cfgs[1].keys_manager;
9674 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);
9675 nodes[1].chain_monitor = &new_chain_monitor;
9677 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9678 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9679 &mut chan_0_monitor_read, keys_manager).unwrap();
9680 assert!(chan_0_monitor_read.is_empty());
9681 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9682 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9683 &mut chan_1_monitor_read, keys_manager).unwrap();
9684 assert!(chan_1_monitor_read.is_empty());
9686 let mut nodes_1_read = &nodes_1_serialized[..];
9687 let (_, nodes_1_deserialized_tmp) = {
9688 let mut channel_monitors = HashMap::new();
9689 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9690 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9691 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9692 default_config: UserConfig::default(),
9694 fee_estimator: node_cfgs[1].fee_estimator,
9695 chain_monitor: nodes[1].chain_monitor,
9696 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9697 logger: nodes[1].logger,
9701 nodes_1_deserialized = nodes_1_deserialized_tmp;
9702 assert!(nodes_1_read.is_empty());
9704 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9705 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9706 nodes[1].node = &nodes_1_deserialized;
9707 check_added_monitors!(nodes[1], 2);
9709 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9710 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9711 // the commitment state.
9712 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9714 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9716 expect_pending_htlcs_forwardable!(nodes[1]);
9717 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9718 check_added_monitors!(nodes[1], 1);
9720 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9721 assert_eq!(events.len(), 1);
9722 let payment_event = SendEvent::from_event(events.pop().unwrap());
9723 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9724 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9725 expect_pending_htlcs_forwardable!(nodes[2]);
9726 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9728 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9729 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9732 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9733 let chanmon_cfgs = create_chanmon_cfgs(2);
9734 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9735 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9736 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9738 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9740 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9741 .with_features(InvoiceFeatures::known());
9742 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9744 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9747 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9748 check_added_monitors!(nodes[0], 1);
9749 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9750 assert_eq!(events.len(), 1);
9751 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9752 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9753 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9755 expect_pending_htlcs_forwardable!(nodes[1]);
9756 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9759 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9760 check_added_monitors!(nodes[0], 1);
9761 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9762 assert_eq!(events.len(), 1);
9763 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9764 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9765 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9766 // At this point, nodes[1] would notice it has too much value for the payment. It will
9767 // assume the second is a privacy attack (no longer particularly relevant
9768 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9769 // the first HTLC delivered above.
9772 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9773 nodes[1].node.process_pending_htlc_forwards();
9775 if test_for_second_fail_panic {
9776 // Now we go fail back the first HTLC from the user end.
9777 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9779 let expected_destinations = vec![
9780 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9781 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9783 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9784 nodes[1].node.process_pending_htlc_forwards();
9786 check_added_monitors!(nodes[1], 1);
9787 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9788 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9790 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9791 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9792 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9794 let failure_events = nodes[0].node.get_and_clear_pending_events();
9795 assert_eq!(failure_events.len(), 2);
9796 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9797 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9799 // Let the second HTLC fail and claim the first
9800 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9801 nodes[1].node.process_pending_htlc_forwards();
9803 check_added_monitors!(nodes[1], 1);
9804 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9805 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9806 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9808 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9810 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9815 fn test_dup_htlc_second_fail_panic() {
9816 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9817 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9818 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9819 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9820 do_test_dup_htlc_second_rejected(true);
9824 fn test_dup_htlc_second_rejected() {
9825 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9826 // simply reject the second HTLC but are still able to claim the first HTLC.
9827 do_test_dup_htlc_second_rejected(false);
9831 fn test_inconsistent_mpp_params() {
9832 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9833 // such HTLC and allow the second to stay.
9834 let chanmon_cfgs = create_chanmon_cfgs(4);
9835 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9836 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9837 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9839 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9840 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9841 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9842 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9844 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9845 .with_features(InvoiceFeatures::known());
9846 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9847 assert_eq!(route.paths.len(), 2);
9848 route.paths.sort_by(|path_a, _| {
9849 // Sort the path so that the path through nodes[1] comes first
9850 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9851 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9853 let payment_params_opt = Some(payment_params);
9855 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9857 let cur_height = nodes[0].best_block_info().1;
9858 let payment_id = PaymentId([42; 32]);
9860 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();
9861 check_added_monitors!(nodes[0], 1);
9863 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9864 assert_eq!(events.len(), 1);
9865 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9867 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9870 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();
9871 check_added_monitors!(nodes[0], 1);
9873 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9874 assert_eq!(events.len(), 1);
9875 let payment_event = SendEvent::from_event(events.pop().unwrap());
9877 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9878 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9880 expect_pending_htlcs_forwardable!(nodes[2]);
9881 check_added_monitors!(nodes[2], 1);
9883 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9884 assert_eq!(events.len(), 1);
9885 let payment_event = SendEvent::from_event(events.pop().unwrap());
9887 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9888 check_added_monitors!(nodes[3], 0);
9889 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9891 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9892 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9893 // post-payment_secrets) and fail back the new HTLC.
9895 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9896 nodes[3].node.process_pending_htlc_forwards();
9897 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9898 nodes[3].node.process_pending_htlc_forwards();
9900 check_added_monitors!(nodes[3], 1);
9902 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9903 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9904 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9906 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9907 check_added_monitors!(nodes[2], 1);
9909 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9910 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9911 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9913 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9915 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();
9916 check_added_monitors!(nodes[0], 1);
9918 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9919 assert_eq!(events.len(), 1);
9920 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9922 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9926 fn test_keysend_payments_to_public_node() {
9927 let chanmon_cfgs = create_chanmon_cfgs(2);
9928 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9929 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9930 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9932 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9933 let network_graph = nodes[0].network_graph;
9934 let payer_pubkey = nodes[0].node.get_our_node_id();
9935 let payee_pubkey = nodes[1].node.get_our_node_id();
9936 let route_params = RouteParameters {
9937 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9938 final_value_msat: 10000,
9939 final_cltv_expiry_delta: 40,
9941 let scorer = test_utils::TestScorer::with_penalty(0);
9942 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9943 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9945 let test_preimage = PaymentPreimage([42; 32]);
9946 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9947 check_added_monitors!(nodes[0], 1);
9948 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9949 assert_eq!(events.len(), 1);
9950 let event = events.pop().unwrap();
9951 let path = vec![&nodes[1]];
9952 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9953 claim_payment(&nodes[0], &path, test_preimage);
9957 fn test_keysend_payments_to_private_node() {
9958 let chanmon_cfgs = create_chanmon_cfgs(2);
9959 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9960 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9961 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9963 let payer_pubkey = nodes[0].node.get_our_node_id();
9964 let payee_pubkey = nodes[1].node.get_our_node_id();
9965 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9966 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9968 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9969 let route_params = RouteParameters {
9970 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9971 final_value_msat: 10000,
9972 final_cltv_expiry_delta: 40,
9974 let network_graph = nodes[0].network_graph;
9975 let first_hops = nodes[0].node.list_usable_channels();
9976 let scorer = test_utils::TestScorer::with_penalty(0);
9977 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9978 let route = find_route(
9979 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9980 nodes[0].logger, &scorer, &random_seed_bytes
9983 let test_preimage = PaymentPreimage([42; 32]);
9984 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9985 check_added_monitors!(nodes[0], 1);
9986 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9987 assert_eq!(events.len(), 1);
9988 let event = events.pop().unwrap();
9989 let path = vec![&nodes[1]];
9990 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9991 claim_payment(&nodes[0], &path, test_preimage);
9995 fn test_double_partial_claim() {
9996 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9997 // time out, the sender resends only some of the MPP parts, then the user processes the
9998 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
10000 let chanmon_cfgs = create_chanmon_cfgs(4);
10001 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10002 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10003 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10005 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10006 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10007 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10008 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10010 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10011 assert_eq!(route.paths.len(), 2);
10012 route.paths.sort_by(|path_a, _| {
10013 // Sort the path so that the path through nodes[1] comes first
10014 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10015 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10018 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10019 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10020 // amount of time to respond to.
10022 // Connect some blocks to time out the payment
10023 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10024 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10026 let failed_destinations = vec![
10027 HTLCDestination::FailedPayment { payment_hash },
10028 HTLCDestination::FailedPayment { payment_hash },
10030 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10032 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10034 // nodes[1] now retries one of the two paths...
10035 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10036 check_added_monitors!(nodes[0], 2);
10038 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10039 assert_eq!(events.len(), 2);
10040 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10042 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10043 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10044 nodes[3].node.claim_funds(payment_preimage);
10045 check_added_monitors!(nodes[3], 0);
10046 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10049 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10050 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10051 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10052 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10053 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10054 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10055 // not have the preimage tied to the still-pending HTLC.
10057 // To get to the correct state, on startup we should propagate the preimage to the
10058 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10059 // receiving the preimage without a state update.
10061 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10062 // definitely claimed.
10063 let chanmon_cfgs = create_chanmon_cfgs(4);
10064 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10065 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10067 let persister: test_utils::TestPersister;
10068 let new_chain_monitor: test_utils::TestChainMonitor;
10069 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10071 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10073 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10074 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10075 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10076 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10078 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10079 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10080 assert_eq!(route.paths.len(), 2);
10081 route.paths.sort_by(|path_a, _| {
10082 // Sort the path so that the path through nodes[1] comes first
10083 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10084 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10087 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10088 check_added_monitors!(nodes[0], 2);
10090 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10091 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10092 assert_eq!(send_events.len(), 2);
10093 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);
10094 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);
10096 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10097 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10098 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10099 if !persist_both_monitors {
10100 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10101 if outpoint.to_channel_id() == chan_id_not_persisted {
10102 assert!(original_monitor.0.is_empty());
10103 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10108 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10109 nodes[3].node.write(&mut original_manager).unwrap();
10111 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10113 nodes[3].node.claim_funds(payment_preimage);
10114 check_added_monitors!(nodes[3], 2);
10115 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10117 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10118 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10119 // with the old ChannelManager.
10120 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10121 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10122 if outpoint.to_channel_id() == chan_id_persisted {
10123 assert!(updated_monitor.0.is_empty());
10124 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10127 // If `persist_both_monitors` is set, get the second monitor here as well
10128 if persist_both_monitors {
10129 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10130 if outpoint.to_channel_id() == chan_id_not_persisted {
10131 assert!(original_monitor.0.is_empty());
10132 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10137 // Now restart nodes[3].
10138 persister = test_utils::TestPersister::new();
10139 let keys_manager = &chanmon_cfgs[3].keys_manager;
10140 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);
10141 nodes[3].chain_monitor = &new_chain_monitor;
10142 let mut monitors = Vec::new();
10143 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10144 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10145 monitors.push(deserialized_monitor);
10148 let config = UserConfig::default();
10149 nodes_3_deserialized = {
10150 let mut channel_monitors = HashMap::new();
10151 for monitor in monitors.iter_mut() {
10152 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10154 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10155 default_config: config,
10157 fee_estimator: node_cfgs[3].fee_estimator,
10158 chain_monitor: nodes[3].chain_monitor,
10159 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10160 logger: nodes[3].logger,
10164 nodes[3].node = &nodes_3_deserialized;
10166 for monitor in monitors {
10167 // On startup the preimage should have been copied into the non-persisted monitor:
10168 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10169 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10171 check_added_monitors!(nodes[3], 2);
10173 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10174 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10176 // During deserialization, we should have closed one channel and broadcast its latest
10177 // commitment transaction. We should also still have the original PaymentReceived event we
10178 // never finished processing.
10179 let events = nodes[3].node.get_and_clear_pending_events();
10180 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10181 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10182 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10183 if persist_both_monitors {
10184 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10187 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10188 // ChannelManager prior to handling the original one.
10189 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10190 events[if persist_both_monitors { 3 } else { 2 }]
10192 assert_eq!(payment_hash, our_payment_hash);
10193 } else { panic!(); }
10195 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10196 if !persist_both_monitors {
10197 // If one of the two channels is still live, reveal the payment preimage over it.
10199 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10200 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10201 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10202 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10204 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10205 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10206 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10208 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10210 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10211 // claim should fly.
10212 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10213 check_added_monitors!(nodes[3], 1);
10214 assert_eq!(ds_msgs.len(), 2);
10215 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10217 let cs_updates = match ds_msgs[0] {
10218 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10219 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10220 check_added_monitors!(nodes[2], 1);
10221 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10222 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10223 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10229 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10230 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10231 expect_payment_sent!(nodes[0], payment_preimage);
10236 fn test_partial_claim_before_restart() {
10237 do_test_partial_claim_before_restart(false);
10238 do_test_partial_claim_before_restart(true);
10241 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10242 #[derive(Clone, Copy, PartialEq)]
10243 enum ExposureEvent {
10244 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10246 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10248 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10249 AtUpdateFeeOutbound,
10252 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10253 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10256 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10257 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10258 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10259 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10260 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10261 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10262 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10263 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10265 let chanmon_cfgs = create_chanmon_cfgs(2);
10266 let mut config = test_default_channel_config();
10267 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10268 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10269 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10270 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10272 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10273 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10274 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10275 open_channel.max_accepted_htlcs = 60;
10277 open_channel.dust_limit_satoshis = 546;
10279 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10280 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10281 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10283 let opt_anchors = false;
10285 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10288 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10289 chan.holder_dust_limit_satoshis = 546;
10293 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10294 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()));
10295 check_added_monitors!(nodes[1], 1);
10297 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()));
10298 check_added_monitors!(nodes[0], 1);
10300 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10301 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10302 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10304 let dust_buffer_feerate = {
10305 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10306 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10307 chan.get_dust_buffer_feerate(None) as u64
10309 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;
10310 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10312 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;
10313 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10315 let dust_htlc_on_counterparty_tx: u64 = 25;
10316 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10319 if dust_outbound_balance {
10320 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10321 // Outbound dust balance: 4372 sats
10322 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10323 for i in 0..dust_outbound_htlc_on_holder_tx {
10324 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10325 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10328 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10329 // Inbound dust balance: 4372 sats
10330 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10331 for _ in 0..dust_inbound_htlc_on_holder_tx {
10332 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10336 if dust_outbound_balance {
10337 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10338 // Outbound dust balance: 5000 sats
10339 for i in 0..dust_htlc_on_counterparty_tx {
10340 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10341 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10344 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10345 // Inbound dust balance: 5000 sats
10346 for _ in 0..dust_htlc_on_counterparty_tx {
10347 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10352 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10353 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10354 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 });
10355 let mut config = UserConfig::default();
10356 // With default dust exposure: 5000 sats
10358 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10359 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10360 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)));
10362 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)));
10364 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10365 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 });
10366 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10367 check_added_monitors!(nodes[1], 1);
10368 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10369 assert_eq!(events.len(), 1);
10370 let payment_event = SendEvent::from_event(events.remove(0));
10371 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10372 // With default dust exposure: 5000 sats
10374 // Outbound dust balance: 6399 sats
10375 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10376 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10377 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);
10379 // Outbound dust balance: 5200 sats
10380 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);
10382 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10383 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10384 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10386 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10387 *feerate_lock = *feerate_lock * 10;
10389 nodes[0].node.timer_tick_occurred();
10390 check_added_monitors!(nodes[0], 1);
10391 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);
10394 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10395 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10396 added_monitors.clear();
10400 fn test_max_dust_htlc_exposure() {
10401 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10402 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10403 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10404 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10405 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10406 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10407 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10408 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10409 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10410 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10411 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10412 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10416 fn test_non_final_funding_tx() {
10417 let chanmon_cfgs = create_chanmon_cfgs(2);
10418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10420 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10422 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10423 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10424 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10425 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10426 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10428 let best_height = nodes[0].node.best_block.read().unwrap().height();
10430 let chan_id = *nodes[0].network_chan_count.borrow();
10431 let events = nodes[0].node.get_and_clear_pending_events();
10432 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
10433 assert_eq!(events.len(), 1);
10434 let mut tx = match events[0] {
10435 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10436 // Timelock the transaction _beyond_ the best client height + 2.
10437 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
10438 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10441 _ => panic!("Unexpected event"),
10443 // Transaction should fail as it's evaluated as non-final for propagation.
10444 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10445 Err(APIError::APIMisuseError { err }) => {
10446 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10451 // However, transaction should be accepted if it's in a +2 headroom from best block.
10452 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
10453 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10454 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());