1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::gossip::NetworkGraph;
27 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::{Builder, Script};
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
44 use bitcoin::{Transaction, TxIn, TxOut, Witness};
45 use bitcoin::OutPoint as BitcoinOutPoint;
47 use bitcoin::secp256k1::Secp256k1;
48 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use alloc::collections::BTreeSet;
55 use core::default::Default;
56 use sync::{Arc, Mutex};
58 use ln::functional_test_utils::*;
59 use ln::chan_utils::CommitmentTransaction;
62 fn test_insane_channel_opens() {
63 // Stand up a network of 2 nodes
64 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
65 let mut cfg = UserConfig::default();
66 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
67 let chanmon_cfgs = create_chanmon_cfgs(2);
68 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
70 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72 // Instantiate channel parameters where we push the maximum msats given our
74 let channel_value_sat = 31337; // same as funding satoshis
75 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78 // Have node0 initiate a channel to node1 with aforementioned parameters
79 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81 // Extract the channel open message from node0 to node1
82 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84 // Test helper that asserts we get the correct error string given a mutator
85 // that supposedly makes the channel open message insane
86 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89 assert_eq!(msg_events.len(), 1);
90 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93 &ErrorAction::SendErrorMessage { .. } => {
94 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96 _ => panic!("unexpected event!"),
98 } else { assert!(false); }
101 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103 // Test all mutations that would make the channel open message insane
104 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
105 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
107 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
111 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
115 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
117 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 fn test_funding_exceeds_no_wumbo_limit() {
124 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
126 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
127 let chanmon_cfgs = create_chanmon_cfgs(2);
128 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
131 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
133 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
134 Err(APIError::APIMisuseError { err }) => {
135 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
141 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
142 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
143 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
144 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
145 // in normal testing, we test it explicitly here.
146 let chanmon_cfgs = create_chanmon_cfgs(2);
147 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
148 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
149 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
151 // Have node0 initiate a channel to node1 with aforementioned parameters
152 let mut push_amt = 100_000_000;
153 let feerate_per_kw = 253;
154 let opt_anchors = false;
155 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
156 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
158 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
159 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
160 if !send_from_initiator {
161 open_channel_message.channel_reserve_satoshis = 0;
162 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
164 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
166 // Extract the channel accept message from node1 to node0
167 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
168 if send_from_initiator {
169 accept_channel_message.channel_reserve_satoshis = 0;
170 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
172 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
175 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
176 chan.holder_selected_channel_reserve_satoshis = 0;
177 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
180 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
181 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
182 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
184 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
185 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
186 if send_from_initiator {
187 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
188 // Note that for outbound channels we have to consider the commitment tx fee and the
189 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
190 // well as an additional HTLC.
191 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
193 send_payment(&nodes[1], &[&nodes[0]], push_amt);
198 fn test_counterparty_no_reserve() {
199 do_test_counterparty_no_reserve(true);
200 do_test_counterparty_no_reserve(false);
204 fn test_async_inbound_update_fee() {
205 let chanmon_cfgs = create_chanmon_cfgs(2);
206 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
207 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
208 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
209 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
212 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
216 // send (1) commitment_signed -.
217 // <- update_add_htlc/commitment_signed
218 // send (2) RAA (awaiting remote revoke) -.
219 // (1) commitment_signed is delivered ->
220 // .- send (3) RAA (awaiting remote revoke)
221 // (2) RAA is delivered ->
222 // .- send (4) commitment_signed
223 // <- (3) RAA is delivered
224 // send (5) commitment_signed -.
225 // <- (4) commitment_signed is delivered
227 // (5) commitment_signed is delivered ->
229 // (6) RAA is delivered ->
231 // First nodes[0] generates an update_fee
233 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
236 nodes[0].node.timer_tick_occurred();
237 check_added_monitors!(nodes[0], 1);
239 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
240 assert_eq!(events_0.len(), 1);
241 let (update_msg, commitment_signed) = match events_0[0] { // (1)
242 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
243 (update_fee.as_ref(), commitment_signed)
245 _ => panic!("Unexpected event"),
248 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
250 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
251 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
252 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
253 check_added_monitors!(nodes[1], 1);
255 let payment_event = {
256 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
257 assert_eq!(events_1.len(), 1);
258 SendEvent::from_event(events_1.remove(0))
260 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
261 assert_eq!(payment_event.msgs.len(), 1);
263 // ...now when the messages get delivered everyone should be happy
264 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
265 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
266 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
267 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
268 check_added_monitors!(nodes[0], 1);
270 // deliver(1), generate (3):
271 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
272 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
273 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
274 check_added_monitors!(nodes[1], 1);
276 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
277 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
278 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
279 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
280 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
281 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
282 assert!(bs_update.update_fee.is_none()); // (4)
283 check_added_monitors!(nodes[1], 1);
285 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
286 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
287 assert!(as_update.update_add_htlcs.is_empty()); // (5)
288 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
289 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
290 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
291 assert!(as_update.update_fee.is_none()); // (5)
292 check_added_monitors!(nodes[0], 1);
294 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
295 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
296 // only (6) so get_event_msg's assert(len == 1) passes
297 check_added_monitors!(nodes[0], 1);
299 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
300 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
301 check_added_monitors!(nodes[1], 1);
303 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
304 check_added_monitors!(nodes[0], 1);
306 let events_2 = nodes[0].node.get_and_clear_pending_events();
307 assert_eq!(events_2.len(), 1);
309 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
310 _ => panic!("Unexpected event"),
313 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
314 check_added_monitors!(nodes[1], 1);
318 fn test_update_fee_unordered_raa() {
319 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
320 // crash in an earlier version of the update_fee patch)
321 let chanmon_cfgs = create_chanmon_cfgs(2);
322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
325 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
328 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
330 // First nodes[0] generates an update_fee
332 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
335 nodes[0].node.timer_tick_occurred();
336 check_added_monitors!(nodes[0], 1);
338 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
339 assert_eq!(events_0.len(), 1);
340 let update_msg = match events_0[0] { // (1)
341 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
344 _ => panic!("Unexpected event"),
347 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
349 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
350 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
351 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
352 check_added_monitors!(nodes[1], 1);
354 let payment_event = {
355 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
356 assert_eq!(events_1.len(), 1);
357 SendEvent::from_event(events_1.remove(0))
359 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
360 assert_eq!(payment_event.msgs.len(), 1);
362 // ...now when the messages get delivered everyone should be happy
363 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
364 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
365 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
366 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
367 check_added_monitors!(nodes[0], 1);
369 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
370 check_added_monitors!(nodes[1], 1);
372 // We can't continue, sadly, because our (1) now has a bogus signature
376 fn test_multi_flight_update_fee() {
377 let chanmon_cfgs = create_chanmon_cfgs(2);
378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
380 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
381 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
384 // update_fee/commitment_signed ->
385 // .- send (1) RAA and (2) commitment_signed
386 // update_fee (never committed) ->
388 // We have to manually generate the above update_fee, it is allowed by the protocol but we
389 // don't track which updates correspond to which revoke_and_ack responses so we're in
390 // AwaitingRAA mode and will not generate the update_fee yet.
391 // <- (1) RAA delivered
392 // (3) is generated and send (4) CS -.
393 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
394 // know the per_commitment_point to use for it.
395 // <- (2) commitment_signed delivered
397 // B should send no response here
398 // (4) commitment_signed delivered ->
399 // <- RAA/commitment_signed delivered
402 // First nodes[0] generates an update_fee
405 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406 initial_feerate = *feerate_lock;
407 *feerate_lock = initial_feerate + 20;
409 nodes[0].node.timer_tick_occurred();
410 check_added_monitors!(nodes[0], 1);
412 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
413 assert_eq!(events_0.len(), 1);
414 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
415 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
416 (update_fee.as_ref().unwrap(), commitment_signed)
418 _ => panic!("Unexpected event"),
421 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
422 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
423 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
424 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
425 check_added_monitors!(nodes[1], 1);
427 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
430 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
431 *feerate_lock = initial_feerate + 40;
433 nodes[0].node.timer_tick_occurred();
434 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
435 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
437 // Create the (3) update_fee message that nodes[0] will generate before it does...
438 let mut update_msg_2 = msgs::UpdateFee {
439 channel_id: update_msg_1.channel_id.clone(),
440 feerate_per_kw: (initial_feerate + 30) as u32,
443 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
445 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
447 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
449 // Deliver (1), generating (3) and (4)
450 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
451 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
452 check_added_monitors!(nodes[0], 1);
453 assert!(as_second_update.update_add_htlcs.is_empty());
454 assert!(as_second_update.update_fulfill_htlcs.is_empty());
455 assert!(as_second_update.update_fail_htlcs.is_empty());
456 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
457 // Check that the update_fee newly generated matches what we delivered:
458 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
459 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
461 // Deliver (2) commitment_signed
462 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
463 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
464 check_added_monitors!(nodes[0], 1);
465 // No commitment_signed so get_event_msg's assert(len == 1) passes
467 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
468 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
469 check_added_monitors!(nodes[1], 1);
472 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
473 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
474 check_added_monitors!(nodes[1], 1);
476 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
477 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[0], 1);
480 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
481 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
482 // No commitment_signed so get_event_msg's assert(len == 1) passes
483 check_added_monitors!(nodes[0], 1);
485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
486 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[1], 1);
490 fn do_test_sanity_on_in_flight_opens(steps: u8) {
491 // Previously, we had issues deserializing channels when we hadn't connected the first block
492 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
493 // serialization round-trips and simply do steps towards opening a channel and then drop the
496 let chanmon_cfgs = create_chanmon_cfgs(2);
497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
501 if steps & 0b1000_0000 != 0{
503 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
506 connect_block(&nodes[0], &block);
507 connect_block(&nodes[1], &block);
510 if steps & 0x0f == 0 { return; }
511 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
512 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
514 if steps & 0x0f == 1 { return; }
515 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
516 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
518 if steps & 0x0f == 2 { return; }
519 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
521 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
523 if steps & 0x0f == 3 { return; }
524 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
525 check_added_monitors!(nodes[0], 0);
526 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
528 if steps & 0x0f == 4 { return; }
529 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
531 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
532 assert_eq!(added_monitors.len(), 1);
533 assert_eq!(added_monitors[0].0, funding_output);
534 added_monitors.clear();
536 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
538 if steps & 0x0f == 5 { return; }
539 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
541 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
542 assert_eq!(added_monitors.len(), 1);
543 assert_eq!(added_monitors[0].0, funding_output);
544 added_monitors.clear();
547 let events_4 = nodes[0].node.get_and_clear_pending_events();
548 assert_eq!(events_4.len(), 0);
550 if steps & 0x0f == 6 { return; }
551 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
553 if steps & 0x0f == 7 { return; }
554 confirm_transaction_at(&nodes[0], &tx, 2);
555 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
556 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
560 fn test_sanity_on_in_flight_opens() {
561 do_test_sanity_on_in_flight_opens(0);
562 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
563 do_test_sanity_on_in_flight_opens(1);
564 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
565 do_test_sanity_on_in_flight_opens(2);
566 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
567 do_test_sanity_on_in_flight_opens(3);
568 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
569 do_test_sanity_on_in_flight_opens(4);
570 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(5);
572 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(6);
574 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(7);
576 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(8);
578 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
582 fn test_update_fee_vanilla() {
583 let chanmon_cfgs = create_chanmon_cfgs(2);
584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
590 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
593 nodes[0].node.timer_tick_occurred();
594 check_added_monitors!(nodes[0], 1);
596 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
597 assert_eq!(events_0.len(), 1);
598 let (update_msg, commitment_signed) = match events_0[0] {
599 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
600 (update_fee.as_ref(), commitment_signed)
602 _ => panic!("Unexpected event"),
604 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
606 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
607 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
608 check_added_monitors!(nodes[1], 1);
610 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
611 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
612 check_added_monitors!(nodes[0], 1);
614 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
615 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
616 // No commitment_signed so get_event_msg's assert(len == 1) passes
617 check_added_monitors!(nodes[0], 1);
619 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
620 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
621 check_added_monitors!(nodes[1], 1);
625 fn test_update_fee_that_funder_cannot_afford() {
626 let chanmon_cfgs = create_chanmon_cfgs(2);
627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630 let channel_value = 5000;
632 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
633 let channel_id = chan.2;
634 let secp_ctx = Secp256k1::new();
635 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
637 let opt_anchors = false;
639 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
640 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
641 // calculate two different feerates here - the expected local limit as well as the expected
643 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
644 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
646 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
647 *feerate_lock = feerate;
649 nodes[0].node.timer_tick_occurred();
650 check_added_monitors!(nodes[0], 1);
651 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
653 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
655 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
657 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
659 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
661 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
662 assert_eq!(commitment_tx.output.len(), 2);
663 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
664 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
665 actual_fee = channel_value - actual_fee;
666 assert_eq!(total_fee, actual_fee);
670 // Increment the feerate by a small constant, accounting for rounding errors
671 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
674 nodes[0].node.timer_tick_occurred();
675 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
676 check_added_monitors!(nodes[0], 0);
678 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
680 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
681 // needed to sign the new commitment tx and (2) sign the new commitment tx.
682 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
683 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
684 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
685 let chan_signer = local_chan.get_signer();
686 let pubkeys = chan_signer.pubkeys();
687 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
688 pubkeys.funding_pubkey)
690 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
691 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
692 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
693 let chan_signer = remote_chan.get_signer();
694 let pubkeys = chan_signer.pubkeys();
695 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
696 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
697 pubkeys.funding_pubkey)
700 // Assemble the set of keys we can use for signatures for our commitment_signed message.
701 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
702 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
705 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
706 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
707 let local_chan_signer = local_chan.get_signer();
708 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
709 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
710 INITIAL_COMMITMENT_NUMBER - 1,
712 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
713 opt_anchors, local_funding, remote_funding,
714 commit_tx_keys.clone(),
715 non_buffer_feerate + 4,
717 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
719 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
722 let commit_signed_msg = msgs::CommitmentSigned {
725 htlc_signatures: res.1
728 let update_fee = msgs::UpdateFee {
730 feerate_per_kw: non_buffer_feerate + 4,
733 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
735 //While producing the commitment_signed response after handling a received update_fee request the
736 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
737 //Should produce and error.
738 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
739 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
740 check_added_monitors!(nodes[1], 1);
741 check_closed_broadcast!(nodes[1], true);
742 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
746 fn test_update_fee_with_fundee_update_add_htlc() {
747 let chanmon_cfgs = create_chanmon_cfgs(2);
748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
750 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
751 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
754 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
757 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
760 nodes[0].node.timer_tick_occurred();
761 check_added_monitors!(nodes[0], 1);
763 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
764 assert_eq!(events_0.len(), 1);
765 let (update_msg, commitment_signed) = match events_0[0] {
766 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
767 (update_fee.as_ref(), commitment_signed)
769 _ => panic!("Unexpected event"),
771 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
772 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
773 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
774 check_added_monitors!(nodes[1], 1);
776 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
778 // nothing happens since node[1] is in AwaitingRemoteRevoke
779 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
781 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
782 assert_eq!(added_monitors.len(), 0);
783 added_monitors.clear();
785 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
786 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
787 // node[1] has nothing to do
789 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
790 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
791 check_added_monitors!(nodes[0], 1);
793 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
794 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
795 // No commitment_signed so get_event_msg's assert(len == 1) passes
796 check_added_monitors!(nodes[0], 1);
797 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
798 check_added_monitors!(nodes[1], 1);
799 // AwaitingRemoteRevoke ends here
801 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
803 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
804 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
805 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
806 assert_eq!(commitment_update.update_fee.is_none(), true);
808 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
809 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
810 check_added_monitors!(nodes[0], 1);
811 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
813 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
814 check_added_monitors!(nodes[1], 1);
815 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
818 check_added_monitors!(nodes[1], 1);
819 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
820 // No commitment_signed so get_event_msg's assert(len == 1) passes
822 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
823 check_added_monitors!(nodes[0], 1);
824 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
826 expect_pending_htlcs_forwardable!(nodes[0]);
828 let events = nodes[0].node.get_and_clear_pending_events();
829 assert_eq!(events.len(), 1);
831 Event::PaymentReceived { .. } => { },
832 _ => panic!("Unexpected event"),
835 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
837 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
838 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
839 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
840 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
841 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
845 fn test_update_fee() {
846 let chanmon_cfgs = create_chanmon_cfgs(2);
847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
850 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851 let channel_id = chan.2;
854 // (1) update_fee/commitment_signed ->
855 // <- (2) revoke_and_ack
856 // .- send (3) commitment_signed
857 // (4) update_fee/commitment_signed ->
858 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
859 // <- (3) commitment_signed delivered
860 // send (6) revoke_and_ack -.
861 // <- (5) deliver revoke_and_ack
862 // (6) deliver revoke_and_ack ->
863 // .- send (7) commitment_signed in response to (4)
864 // <- (7) deliver commitment_signed
867 // Create and deliver (1)...
870 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
871 feerate = *feerate_lock;
872 *feerate_lock = feerate + 20;
874 nodes[0].node.timer_tick_occurred();
875 check_added_monitors!(nodes[0], 1);
877 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
878 assert_eq!(events_0.len(), 1);
879 let (update_msg, commitment_signed) = match events_0[0] {
880 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
881 (update_fee.as_ref(), commitment_signed)
883 _ => panic!("Unexpected event"),
885 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
887 // Generate (2) and (3):
888 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
889 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890 check_added_monitors!(nodes[1], 1);
893 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
894 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
895 check_added_monitors!(nodes[0], 1);
897 // Create and deliver (4)...
899 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
900 *feerate_lock = feerate + 30;
902 nodes[0].node.timer_tick_occurred();
903 check_added_monitors!(nodes[0], 1);
904 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
905 assert_eq!(events_0.len(), 1);
906 let (update_msg, commitment_signed) = match events_0[0] {
907 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
908 (update_fee.as_ref(), commitment_signed)
910 _ => panic!("Unexpected event"),
913 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
914 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
915 check_added_monitors!(nodes[1], 1);
917 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
918 // No commitment_signed so get_event_msg's assert(len == 1) passes
920 // Handle (3), creating (6):
921 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
922 check_added_monitors!(nodes[0], 1);
923 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
924 // No commitment_signed so get_event_msg's assert(len == 1) passes
927 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929 check_added_monitors!(nodes[0], 1);
931 // Deliver (6), creating (7):
932 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
933 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
934 assert!(commitment_update.update_add_htlcs.is_empty());
935 assert!(commitment_update.update_fulfill_htlcs.is_empty());
936 assert!(commitment_update.update_fail_htlcs.is_empty());
937 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
938 assert!(commitment_update.update_fee.is_none());
939 check_added_monitors!(nodes[1], 1);
942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
943 check_added_monitors!(nodes[0], 1);
944 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
945 // No commitment_signed so get_event_msg's assert(len == 1) passes
947 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
948 check_added_monitors!(nodes[1], 1);
949 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
951 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
952 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
953 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
954 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
955 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
959 fn fake_network_test() {
960 // Simple test which builds a network of ChannelManagers, connects them to each other, and
961 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
962 let chanmon_cfgs = create_chanmon_cfgs(4);
963 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
964 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
965 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
967 // Create some initial channels
968 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
969 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
970 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
972 // Rebalance the network a bit by relaying one payment through all the channels...
973 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
978 // Send some more payments
979 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
980 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
981 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
983 // Test failure packets
984 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
985 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
987 // Add a new channel that skips 3
988 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
991 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
992 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998 // Do some rebalance loop payments, simultaneously
999 let mut hops = Vec::with_capacity(3);
1000 hops.push(RouteHop {
1001 pubkey: nodes[2].node.get_our_node_id(),
1002 node_features: NodeFeatures::empty(),
1003 short_channel_id: chan_2.0.contents.short_channel_id,
1004 channel_features: ChannelFeatures::empty(),
1006 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1008 hops.push(RouteHop {
1009 pubkey: nodes[3].node.get_our_node_id(),
1010 node_features: NodeFeatures::empty(),
1011 short_channel_id: chan_3.0.contents.short_channel_id,
1012 channel_features: ChannelFeatures::empty(),
1014 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1016 hops.push(RouteHop {
1017 pubkey: nodes[1].node.get_our_node_id(),
1018 node_features: NodeFeatures::known(),
1019 short_channel_id: chan_4.0.contents.short_channel_id,
1020 channel_features: ChannelFeatures::known(),
1022 cltv_expiry_delta: TEST_FINAL_CLTV,
1024 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1025 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1026 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1028 let mut hops = Vec::with_capacity(3);
1029 hops.push(RouteHop {
1030 pubkey: nodes[3].node.get_our_node_id(),
1031 node_features: NodeFeatures::empty(),
1032 short_channel_id: chan_4.0.contents.short_channel_id,
1033 channel_features: ChannelFeatures::empty(),
1035 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1037 hops.push(RouteHop {
1038 pubkey: nodes[2].node.get_our_node_id(),
1039 node_features: NodeFeatures::empty(),
1040 short_channel_id: chan_3.0.contents.short_channel_id,
1041 channel_features: ChannelFeatures::empty(),
1043 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1045 hops.push(RouteHop {
1046 pubkey: nodes[1].node.get_our_node_id(),
1047 node_features: NodeFeatures::known(),
1048 short_channel_id: chan_2.0.contents.short_channel_id,
1049 channel_features: ChannelFeatures::known(),
1051 cltv_expiry_delta: TEST_FINAL_CLTV,
1053 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1054 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1055 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1057 // Claim the rebalances...
1058 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1059 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1061 // Add a duplicate new channel from 2 to 4
1062 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1064 // Send some payments across both channels
1065 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1066 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1070 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1071 let events = nodes[0].node.get_and_clear_pending_msg_events();
1072 assert_eq!(events.len(), 0);
1073 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1075 //TODO: Test that routes work again here as we've been notified that the channel is full
1077 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1078 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1079 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1081 // Close down the channels...
1082 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1083 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1086 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1089 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1092 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1095 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1100 fn holding_cell_htlc_counting() {
1101 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1102 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1103 // commitment dance rounds.
1104 let chanmon_cfgs = create_chanmon_cfgs(3);
1105 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1106 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1107 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1108 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1109 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1111 let mut payments = Vec::new();
1112 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1113 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1114 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1115 payments.push((payment_preimage, payment_hash));
1117 check_added_monitors!(nodes[1], 1);
1119 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1120 assert_eq!(events.len(), 1);
1121 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1122 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1124 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1125 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1127 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1129 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1130 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1131 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1135 // This should also be true if we try to forward a payment.
1136 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1138 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1139 check_added_monitors!(nodes[0], 1);
1142 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143 assert_eq!(events.len(), 1);
1144 let payment_event = SendEvent::from_event(events.pop().unwrap());
1145 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150 // fails), the second will process the resulting failure and fail the HTLC backward.
1151 expect_pending_htlcs_forwardable!(nodes[1]);
1152 expect_pending_htlcs_forwardable!(nodes[1]);
1153 check_added_monitors!(nodes[1], 1);
1155 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161 // Now forward all the pending HTLCs and claim them back
1162 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164 check_added_monitors!(nodes[2], 1);
1166 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172 check_added_monitors!(nodes[1], 1);
1173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175 for ref update in as_updates.update_add_htlcs.iter() {
1176 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179 check_added_monitors!(nodes[2], 1);
1180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181 check_added_monitors!(nodes[2], 1);
1182 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185 check_added_monitors!(nodes[1], 1);
1186 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187 check_added_monitors!(nodes[1], 1);
1188 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191 check_added_monitors!(nodes[2], 1);
1193 expect_pending_htlcs_forwardable!(nodes[2]);
1195 let events = nodes[2].node.get_and_clear_pending_events();
1196 assert_eq!(events.len(), payments.len());
1197 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199 &Event::PaymentReceived { ref payment_hash, .. } => {
1200 assert_eq!(*payment_hash, *hash);
1202 _ => panic!("Unexpected event"),
1206 for (preimage, _) in payments.drain(..) {
1207 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1214 fn duplicate_htlc_test() {
1215 // Test that we accept duplicate payment_hash HTLCs across the network and that
1216 // claiming/failing them are all separate and don't affect each other
1217 let chanmon_cfgs = create_chanmon_cfgs(6);
1218 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1224 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1225 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1226 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1227 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1229 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234 *nodes[0].network_payment_count.borrow_mut() -= 1;
1235 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244 // Test that ChannelMonitor doesn't generate 2 preimage txn
1245 // when we have 2 HTLCs with same preimage that go across a node
1246 // in opposite directions, even with the same payment secret.
1247 let chanmon_cfgs = create_chanmon_cfgs(2);
1248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1255 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1261 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263 // Provide preimage to node 0 by claiming payment
1264 nodes[0].node.claim_funds(payment_preimage);
1265 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266 check_added_monitors!(nodes[0], 1);
1268 // Broadcast node 1 commitment txn
1269 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272 let mut has_both_htlcs = 0; // check htlcs match ones committed
1273 for outp in remote_txn[0].output.iter() {
1274 if outp.value == 800_000 / 1000 {
1275 has_both_htlcs += 1;
1276 } else if outp.value == 900_000 / 1000 {
1277 has_both_htlcs += 1;
1280 assert_eq!(has_both_htlcs, 2);
1282 mine_transaction(&nodes[0], &remote_txn[0]);
1283 check_added_monitors!(nodes[0], 1);
1284 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1287 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288 assert_eq!(claim_txn.len(), 8);
1290 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1292 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1293 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1295 let bump_tx = if claim_txn[1] == claim_txn[4] {
1296 assert_eq!(claim_txn[1], claim_txn[4]);
1297 assert_eq!(claim_txn[2], claim_txn[5]);
1299 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1301 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1304 assert_eq!(claim_txn[1], claim_txn[3]);
1305 assert_eq!(claim_txn[2], claim_txn[4]);
1307 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1309 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1314 assert_eq!(claim_txn[0].input.len(), 1);
1315 assert_eq!(bump_tx.input.len(), 1);
1316 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1318 assert_eq!(claim_txn[0].input.len(), 1);
1319 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1320 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1322 assert_eq!(claim_txn[6].input.len(), 1);
1323 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1324 check_spends!(claim_txn[6], remote_txn[0]);
1325 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1327 let events = nodes[0].node.get_and_clear_pending_msg_events();
1328 assert_eq!(events.len(), 3);
1331 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1332 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1333 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1334 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1336 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1337 assert!(update_add_htlcs.is_empty());
1338 assert!(update_fail_htlcs.is_empty());
1339 assert_eq!(update_fulfill_htlcs.len(), 1);
1340 assert!(update_fail_malformed_htlcs.is_empty());
1341 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1343 _ => panic!("Unexpected event"),
1349 fn test_basic_channel_reserve() {
1350 let chanmon_cfgs = create_chanmon_cfgs(2);
1351 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1352 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1353 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1354 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1356 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1357 let channel_reserve = chan_stat.channel_reserve_msat;
1359 // The 2* and +1 are for the fee spike reserve.
1360 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1361 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1362 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1363 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1365 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1367 &APIError::ChannelUnavailable{ref err} =>
1368 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1369 _ => panic!("Unexpected error variant"),
1372 _ => panic!("Unexpected error variant"),
1374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1375 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1377 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1381 fn test_fee_spike_violation_fails_htlc() {
1382 let chanmon_cfgs = create_chanmon_cfgs(2);
1383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1385 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1386 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1388 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1389 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1390 let secp_ctx = Secp256k1::new();
1391 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1393 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1395 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1396 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1397 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1398 let msg = msgs::UpdateAddHTLC {
1401 amount_msat: htlc_msat,
1402 payment_hash: payment_hash,
1403 cltv_expiry: htlc_cltv,
1404 onion_routing_packet: onion_packet,
1407 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1409 // Now manually create the commitment_signed message corresponding to the update_add
1410 // nodes[0] just sent. In the code for construction of this message, "local" refers
1411 // to the sender of the message, and "remote" refers to the receiver.
1413 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1415 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1417 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1418 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1419 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1420 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1421 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1422 let chan_signer = local_chan.get_signer();
1423 // Make the signer believe we validated another commitment, so we can release the secret
1424 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1426 let pubkeys = chan_signer.pubkeys();
1427 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1428 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1429 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1430 chan_signer.pubkeys().funding_pubkey)
1432 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1433 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1434 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1435 let chan_signer = remote_chan.get_signer();
1436 let pubkeys = chan_signer.pubkeys();
1437 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1438 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1439 chan_signer.pubkeys().funding_pubkey)
1442 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1443 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1444 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1446 // Build the remote commitment transaction so we can sign it, and then later use the
1447 // signature for the commitment_signed message.
1448 let local_chan_balance = 1313;
1450 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1452 amount_msat: 3460001,
1453 cltv_expiry: htlc_cltv,
1455 transaction_output_index: Some(1),
1458 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1461 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1462 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1463 let local_chan_signer = local_chan.get_signer();
1464 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1468 local_chan.opt_anchors(), local_funding, remote_funding,
1469 commit_tx_keys.clone(),
1471 &mut vec![(accepted_htlc_info, ())],
1472 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1474 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1477 let commit_signed_msg = msgs::CommitmentSigned {
1480 htlc_signatures: res.1
1483 // Send the commitment_signed message to the nodes[1].
1484 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1485 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1487 // Send the RAA to nodes[1].
1488 let raa_msg = msgs::RevokeAndACK {
1490 per_commitment_secret: local_secret,
1491 next_per_commitment_point: next_local_point
1493 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1495 let events = nodes[1].node.get_and_clear_pending_msg_events();
1496 assert_eq!(events.len(), 1);
1497 // Make sure the HTLC failed in the way we expect.
1499 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1500 assert_eq!(update_fail_htlcs.len(), 1);
1501 update_fail_htlcs[0].clone()
1503 _ => panic!("Unexpected event"),
1505 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1506 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1508 check_added_monitors!(nodes[1], 2);
1512 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1513 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1514 // Set the fee rate for the channel very high, to the point where the fundee
1515 // sending any above-dust amount would result in a channel reserve violation.
1516 // In this test we check that we would be prevented from sending an HTLC in
1518 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1521 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1523 let opt_anchors = false;
1525 let mut push_amt = 100_000_000;
1526 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1527 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1529 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1531 // Sending exactly enough to hit the reserve amount should be accepted
1532 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1533 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1536 // However one more HTLC should be significantly over the reserve amount and fail.
1537 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1538 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1539 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1540 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1541 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1545 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1546 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1547 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1550 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1552 let opt_anchors = false;
1554 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1555 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1556 // transaction fee with 0 HTLCs (183 sats)).
1557 let mut push_amt = 100_000_000;
1558 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1559 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1560 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1562 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1563 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1564 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1567 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1568 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1569 let secp_ctx = Secp256k1::new();
1570 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1571 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1572 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1573 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1574 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1575 let msg = msgs::UpdateAddHTLC {
1577 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578 amount_msat: htlc_msat,
1579 payment_hash: payment_hash,
1580 cltv_expiry: htlc_cltv,
1581 onion_routing_packet: onion_packet,
1584 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1587 assert_eq!(nodes[0].node.list_channels().len(), 0);
1588 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590 check_added_monitors!(nodes[0], 1);
1591 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597 // calculating our commitment transaction fee (this was previously broken).
1598 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1601 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1605 let opt_anchors = false;
1607 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609 // transaction fee with 0 HTLCs (183 sats)).
1610 let mut push_amt = 100_000_000;
1611 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1613 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1615 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619 // commitment transaction fee.
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1622 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1627 // One more than the dust amt should fail, however.
1628 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1630 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1634 fn test_chan_init_feerate_unaffordability() {
1635 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636 // channel reserve and feerate requirements.
1637 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1643 let opt_anchors = false;
1645 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1647 let mut push_amt = 100_000_000;
1648 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1652 // During open, we don't have a "counterparty channel reserve" to check against, so that
1653 // requirement only comes into play on the open_channel handling side.
1654 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1655 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657 open_channel_msg.push_msat += 1;
1658 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1660 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661 assert_eq!(msg_events.len(), 1);
1662 match msg_events[0] {
1663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1666 _ => panic!("Unexpected event"),
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673 // calculating our counterparty's commitment transaction fee (this was previously broken).
1674 let chanmon_cfgs = create_chanmon_cfgs(2);
1675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1680 let payment_amt = 46000; // Dust amount
1681 // In the previous code, these first four payments would succeed.
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702 let chanmon_cfgs = create_chanmon_cfgs(3);
1703 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1707 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1710 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1712 let feerate = get_feerate!(nodes[0], chan.2);
1713 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1715 // Add a 2* and +1 for the fee spike reserve.
1716 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1718 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1720 // Add a pending HTLC.
1721 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722 let payment_event_1 = {
1723 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1724 check_added_monitors!(nodes[0], 1);
1726 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1727 assert_eq!(events.len(), 1);
1728 SendEvent::from_event(events.remove(0))
1730 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1732 // Attempt to trigger a channel reserve violation --> payment failure.
1733 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1734 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1735 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1736 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1738 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1739 let secp_ctx = Secp256k1::new();
1740 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1741 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1742 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1743 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1744 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1745 let msg = msgs::UpdateAddHTLC {
1748 amount_msat: htlc_msat + 1,
1749 payment_hash: our_payment_hash_1,
1750 cltv_expiry: htlc_cltv,
1751 onion_routing_packet: onion_packet,
1754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757 assert_eq!(nodes[1].node.list_channels().len(), 1);
1758 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760 check_added_monitors!(nodes[1], 1);
1761 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766 let chanmon_cfgs = create_chanmon_cfgs(2);
1767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1771 let channels0 = node_chanmgrs[0].list_channels();
1772 let channels1 = node_chanmgrs[1].list_channels();
1773 assert_eq!(channels0.len(), 1);
1774 assert_eq!(channels1.len(), 1);
1776 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1777 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1778 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1780 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1781 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1784 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1785 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1789 fn test_channel_reserve_holding_cell_htlcs() {
1790 let chanmon_cfgs = create_chanmon_cfgs(3);
1791 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1792 // When this test was written, the default base fee floated based on the HTLC count.
1793 // It is now fixed, so we simply set the fee to the expected value here.
1794 let mut config = test_default_channel_config();
1795 config.channel_config.forwarding_fee_base_msat = 239;
1796 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1797 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1798 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1799 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1801 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1802 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1804 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1805 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1807 macro_rules! expect_forward {
1809 let mut events = $node.node.get_and_clear_pending_msg_events();
1810 assert_eq!(events.len(), 1);
1811 check_added_monitors!($node, 1);
1812 let payment_event = SendEvent::from_event(events.remove(0));
1817 let feemsat = 239; // set above
1818 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1819 let feerate = get_feerate!(nodes[0], chan_1.2);
1820 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1822 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1824 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1826 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1827 route.paths[0].last_mut().unwrap().fee_msat += 1;
1828 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1829 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1830 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1831 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1832 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1835 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1836 // nodes[0]'s wealth
1838 let amt_msat = recv_value_0 + total_fee_msat;
1839 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1840 // Also, ensure that each payment has enough to be over the dust limit to
1841 // ensure it'll be included in each commit tx fee calculation.
1842 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1843 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1844 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1847 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1849 let (stat01_, stat11_, stat12_, stat22_) = (
1850 get_channel_value_stat!(nodes[0], chan_1.2),
1851 get_channel_value_stat!(nodes[1], chan_1.2),
1852 get_channel_value_stat!(nodes[1], chan_2.2),
1853 get_channel_value_stat!(nodes[2], chan_2.2),
1856 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1857 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1858 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1859 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1860 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1863 // adding pending output.
1864 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1865 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1866 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1867 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1868 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1869 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1870 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1871 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1872 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1874 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1875 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1876 let amt_msat_1 = recv_value_1 + total_fee_msat;
1878 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1879 let payment_event_1 = {
1880 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1881 check_added_monitors!(nodes[0], 1);
1883 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1884 assert_eq!(events.len(), 1);
1885 SendEvent::from_event(events.remove(0))
1887 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1889 // channel reserve test with htlc pending output > 0
1890 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1892 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1893 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1894 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1895 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1898 // split the rest to test holding cell
1899 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1900 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1901 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1902 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1904 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1905 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1908 // now see if they go through on both sides
1909 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1910 // but this will stuck in the holding cell
1911 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1912 check_added_monitors!(nodes[0], 0);
1913 let events = nodes[0].node.get_and_clear_pending_events();
1914 assert_eq!(events.len(), 0);
1916 // test with outbound holding cell amount > 0
1918 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1919 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1920 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1921 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1922 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1925 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1926 // this will also stuck in the holding cell
1927 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1928 check_added_monitors!(nodes[0], 0);
1929 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1930 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1932 // flush the pending htlc
1933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1934 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1935 check_added_monitors!(nodes[1], 1);
1937 // the pending htlc should be promoted to committed
1938 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1939 check_added_monitors!(nodes[0], 1);
1940 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1943 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1944 // No commitment_signed so get_event_msg's assert(len == 1) passes
1945 check_added_monitors!(nodes[0], 1);
1947 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1948 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1949 check_added_monitors!(nodes[1], 1);
1951 expect_pending_htlcs_forwardable!(nodes[1]);
1953 let ref payment_event_11 = expect_forward!(nodes[1]);
1954 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1955 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1957 expect_pending_htlcs_forwardable!(nodes[2]);
1958 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1960 // flush the htlcs in the holding cell
1961 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1962 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1963 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1964 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1965 expect_pending_htlcs_forwardable!(nodes[1]);
1967 let ref payment_event_3 = expect_forward!(nodes[1]);
1968 assert_eq!(payment_event_3.msgs.len(), 2);
1969 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1970 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1972 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1973 expect_pending_htlcs_forwardable!(nodes[2]);
1975 let events = nodes[2].node.get_and_clear_pending_events();
1976 assert_eq!(events.len(), 2);
1978 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1979 assert_eq!(our_payment_hash_21, *payment_hash);
1980 assert_eq!(recv_value_21, amount_msat);
1982 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1983 assert!(payment_preimage.is_none());
1984 assert_eq!(our_payment_secret_21, *payment_secret);
1986 _ => panic!("expected PaymentPurpose::InvoicePayment")
1989 _ => panic!("Unexpected event"),
1992 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1993 assert_eq!(our_payment_hash_22, *payment_hash);
1994 assert_eq!(recv_value_22, amount_msat);
1996 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1997 assert!(payment_preimage.is_none());
1998 assert_eq!(our_payment_secret_22, *payment_secret);
2000 _ => panic!("expected PaymentPurpose::InvoicePayment")
2003 _ => panic!("Unexpected event"),
2006 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2007 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2008 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2010 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2011 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2012 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2014 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2015 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2016 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2017 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2018 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2020 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2021 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2025 fn channel_reserve_in_flight_removes() {
2026 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2027 // can send to its counterparty, but due to update ordering, the other side may not yet have
2028 // considered those HTLCs fully removed.
2029 // This tests that we don't count HTLCs which will not be included in the next remote
2030 // commitment transaction towards the reserve value (as it implies no commitment transaction
2031 // will be generated which violates the remote reserve value).
2032 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2034 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2035 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2036 // you only consider the value of the first HTLC, it may not),
2037 // * start routing a third HTLC from A to B,
2038 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2039 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2040 // * deliver the first fulfill from B
2041 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2043 // * deliver A's response CS and RAA.
2044 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2045 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2046 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2047 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2048 let chanmon_cfgs = create_chanmon_cfgs(2);
2049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2050 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2051 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2052 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2054 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2055 // Route the first two HTLCs.
2056 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2057 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2058 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2060 // Start routing the third HTLC (this is just used to get everyone in the right state).
2061 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2063 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2064 check_added_monitors!(nodes[0], 1);
2065 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2066 assert_eq!(events.len(), 1);
2067 SendEvent::from_event(events.remove(0))
2070 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2071 // initial fulfill/CS.
2072 nodes[1].node.claim_funds(payment_preimage_1);
2073 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2074 check_added_monitors!(nodes[1], 1);
2075 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2077 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2078 // remove the second HTLC when we send the HTLC back from B to A.
2079 nodes[1].node.claim_funds(payment_preimage_2);
2080 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2081 check_added_monitors!(nodes[1], 1);
2082 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2084 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2085 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2086 check_added_monitors!(nodes[0], 1);
2087 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2088 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2090 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2091 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2092 check_added_monitors!(nodes[1], 1);
2093 // B is already AwaitingRAA, so cant generate a CS here
2094 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2096 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2097 check_added_monitors!(nodes[1], 1);
2098 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2100 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2101 check_added_monitors!(nodes[0], 1);
2102 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105 check_added_monitors!(nodes[1], 1);
2106 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2108 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2109 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2110 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2111 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2112 // on-chain as necessary).
2113 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2114 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2115 check_added_monitors!(nodes[0], 1);
2116 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2117 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2119 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2120 check_added_monitors!(nodes[1], 1);
2121 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2123 expect_pending_htlcs_forwardable!(nodes[1]);
2124 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2126 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2127 // resolve the second HTLC from A's point of view.
2128 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2129 check_added_monitors!(nodes[0], 1);
2130 expect_payment_path_successful!(nodes[0]);
2131 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2133 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2134 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2135 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2137 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2138 check_added_monitors!(nodes[1], 1);
2139 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2140 assert_eq!(events.len(), 1);
2141 SendEvent::from_event(events.remove(0))
2144 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2145 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2146 check_added_monitors!(nodes[0], 1);
2147 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2149 // Now just resolve all the outstanding messages/HTLCs for completeness...
2151 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2152 check_added_monitors!(nodes[1], 1);
2153 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2155 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2156 check_added_monitors!(nodes[1], 1);
2158 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2159 check_added_monitors!(nodes[0], 1);
2160 expect_payment_path_successful!(nodes[0]);
2161 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2163 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2164 check_added_monitors!(nodes[1], 1);
2165 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2167 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2168 check_added_monitors!(nodes[0], 1);
2170 expect_pending_htlcs_forwardable!(nodes[0]);
2171 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2173 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2174 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2178 fn channel_monitor_network_test() {
2179 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2180 // tests that ChannelMonitor is able to recover from various states.
2181 let chanmon_cfgs = create_chanmon_cfgs(5);
2182 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2183 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2184 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2186 // Create some initial channels
2187 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2188 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2189 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2190 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2192 // Make sure all nodes are at the same starting height
2193 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2194 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2195 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2196 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2197 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2199 // Rebalance the network a bit by relaying one payment through all the channels...
2200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2201 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2202 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2203 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2205 // Simple case with no pending HTLCs:
2206 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2207 check_added_monitors!(nodes[1], 1);
2208 check_closed_broadcast!(nodes[1], true);
2210 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2211 assert_eq!(node_txn.len(), 1);
2212 mine_transaction(&nodes[0], &node_txn[0]);
2213 check_added_monitors!(nodes[0], 1);
2214 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2216 check_closed_broadcast!(nodes[0], true);
2217 assert_eq!(nodes[0].node.list_channels().len(), 0);
2218 assert_eq!(nodes[1].node.list_channels().len(), 1);
2219 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2220 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2222 // One pending HTLC is discarded by the force-close:
2223 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2225 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2226 // broadcasted until we reach the timelock time).
2227 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2228 check_closed_broadcast!(nodes[1], true);
2229 check_added_monitors!(nodes[1], 1);
2231 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2232 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2233 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2234 mine_transaction(&nodes[2], &node_txn[0]);
2235 check_added_monitors!(nodes[2], 1);
2236 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2238 check_closed_broadcast!(nodes[2], true);
2239 assert_eq!(nodes[1].node.list_channels().len(), 0);
2240 assert_eq!(nodes[2].node.list_channels().len(), 1);
2241 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2242 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2244 macro_rules! claim_funds {
2245 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2247 $node.node.claim_funds($preimage);
2248 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2249 check_added_monitors!($node, 1);
2251 let events = $node.node.get_and_clear_pending_msg_events();
2252 assert_eq!(events.len(), 1);
2254 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2255 assert!(update_add_htlcs.is_empty());
2256 assert!(update_fail_htlcs.is_empty());
2257 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2259 _ => panic!("Unexpected event"),
2265 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2266 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2267 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2268 check_added_monitors!(nodes[2], 1);
2269 check_closed_broadcast!(nodes[2], true);
2270 let node2_commitment_txid;
2272 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2273 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2274 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2275 node2_commitment_txid = node_txn[0].txid();
2277 // Claim the payment on nodes[3], giving it knowledge of the preimage
2278 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2279 mine_transaction(&nodes[3], &node_txn[0]);
2280 check_added_monitors!(nodes[3], 1);
2281 check_preimage_claim(&nodes[3], &node_txn);
2283 check_closed_broadcast!(nodes[3], true);
2284 assert_eq!(nodes[2].node.list_channels().len(), 0);
2285 assert_eq!(nodes[3].node.list_channels().len(), 1);
2286 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2287 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2289 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2290 // confusing us in the following tests.
2291 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2293 // One pending HTLC to time out:
2294 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2295 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2298 let (close_chan_update_1, close_chan_update_2) = {
2299 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2300 let events = nodes[3].node.get_and_clear_pending_msg_events();
2301 assert_eq!(events.len(), 2);
2302 let close_chan_update_1 = match events[0] {
2303 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2306 _ => panic!("Unexpected event"),
2309 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2310 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2312 _ => panic!("Unexpected event"),
2314 check_added_monitors!(nodes[3], 1);
2316 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2318 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2319 node_txn.retain(|tx| {
2320 if tx.input[0].previous_output.txid == node2_commitment_txid {
2326 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2328 // Claim the payment on nodes[4], giving it knowledge of the preimage
2329 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2331 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2332 let events = nodes[4].node.get_and_clear_pending_msg_events();
2333 assert_eq!(events.len(), 2);
2334 let close_chan_update_2 = match events[0] {
2335 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2338 _ => panic!("Unexpected event"),
2341 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2342 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2344 _ => panic!("Unexpected event"),
2346 check_added_monitors!(nodes[4], 1);
2347 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2349 mine_transaction(&nodes[4], &node_txn[0]);
2350 check_preimage_claim(&nodes[4], &node_txn);
2351 (close_chan_update_1, close_chan_update_2)
2353 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2354 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2355 assert_eq!(nodes[3].node.list_channels().len(), 0);
2356 assert_eq!(nodes[4].node.list_channels().len(), 0);
2358 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2359 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2360 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2364 fn test_justice_tx() {
2365 // Test justice txn built on revoked HTLC-Success tx, against both sides
2366 let mut alice_config = UserConfig::default();
2367 alice_config.channel_handshake_config.announced_channel = true;
2368 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2369 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2370 let mut bob_config = UserConfig::default();
2371 bob_config.channel_handshake_config.announced_channel = true;
2372 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2373 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2374 let user_cfgs = [Some(alice_config), Some(bob_config)];
2375 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2376 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2377 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2380 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2381 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2382 // Create some new channels:
2383 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2385 // A pending HTLC which will be revoked:
2386 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2387 // Get the will-be-revoked local txn from nodes[0]
2388 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2389 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2390 assert_eq!(revoked_local_txn[0].input.len(), 1);
2391 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2392 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2393 assert_eq!(revoked_local_txn[1].input.len(), 1);
2394 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2395 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2396 // Revoke the old state
2397 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2400 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2402 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2403 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2404 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2406 check_spends!(node_txn[0], revoked_local_txn[0]);
2407 node_txn.swap_remove(0);
2408 node_txn.truncate(1);
2410 check_added_monitors!(nodes[1], 1);
2411 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2412 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2414 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2415 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2416 // Verify broadcast of revoked HTLC-timeout
2417 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2418 check_added_monitors!(nodes[0], 1);
2419 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2420 // Broadcast revoked HTLC-timeout on node 1
2421 mine_transaction(&nodes[1], &node_txn[1]);
2422 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2424 get_announce_close_broadcast_events(&nodes, 0, 1);
2426 assert_eq!(nodes[0].node.list_channels().len(), 0);
2427 assert_eq!(nodes[1].node.list_channels().len(), 0);
2429 // We test justice_tx build by A on B's revoked HTLC-Success tx
2430 // Create some new channels:
2431 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2437 // A pending HTLC which will be revoked:
2438 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2439 // Get the will-be-revoked local txn from B
2440 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2441 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2442 assert_eq!(revoked_local_txn[0].input.len(), 1);
2443 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2444 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2445 // Revoke the old state
2446 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2448 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2450 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2451 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2452 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2454 check_spends!(node_txn[0], revoked_local_txn[0]);
2455 node_txn.swap_remove(0);
2457 check_added_monitors!(nodes[0], 1);
2458 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2460 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2461 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2462 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2463 check_added_monitors!(nodes[1], 1);
2464 mine_transaction(&nodes[0], &node_txn[1]);
2465 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2466 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2468 get_announce_close_broadcast_events(&nodes, 0, 1);
2469 assert_eq!(nodes[0].node.list_channels().len(), 0);
2470 assert_eq!(nodes[1].node.list_channels().len(), 0);
2474 fn revoked_output_claim() {
2475 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2476 // transaction is broadcast by its counterparty
2477 let chanmon_cfgs = create_chanmon_cfgs(2);
2478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2480 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2481 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2482 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2483 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2484 assert_eq!(revoked_local_txn.len(), 1);
2485 // Only output is the full channel value back to nodes[0]:
2486 assert_eq!(revoked_local_txn[0].output.len(), 1);
2487 // Send a payment through, updating everyone's latest commitment txn
2488 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2490 // Inform nodes[1] that nodes[0] broadcast a stale tx
2491 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2492 check_added_monitors!(nodes[1], 1);
2493 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2494 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2495 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2497 check_spends!(node_txn[0], revoked_local_txn[0]);
2498 check_spends!(node_txn[1], chan_1.3);
2500 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2501 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2502 get_announce_close_broadcast_events(&nodes, 0, 1);
2503 check_added_monitors!(nodes[0], 1);
2504 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2508 fn claim_htlc_outputs_shared_tx() {
2509 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2510 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2511 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516 // Create some new channel:
2517 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2519 // Rebalance the network to generate htlc in the two directions
2520 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2521 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2522 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2523 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2525 // Get the will-be-revoked local txn from node[0]
2526 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2527 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2528 assert_eq!(revoked_local_txn[0].input.len(), 1);
2529 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2530 assert_eq!(revoked_local_txn[1].input.len(), 1);
2531 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2532 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2533 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2535 //Revoke the old state
2536 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2539 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2540 check_added_monitors!(nodes[0], 1);
2541 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2542 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543 check_added_monitors!(nodes[1], 1);
2544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2545 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2546 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2548 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2549 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2551 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2552 check_spends!(node_txn[0], revoked_local_txn[0]);
2554 let mut witness_lens = BTreeSet::new();
2555 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2556 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2557 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2558 assert_eq!(witness_lens.len(), 3);
2559 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2560 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2561 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2563 // Next nodes[1] broadcasts its current local tx state:
2564 assert_eq!(node_txn[1].input.len(), 1);
2565 check_spends!(node_txn[1], chan_1.3);
2567 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2568 // ANTI_REORG_DELAY confirmations.
2569 mine_transaction(&nodes[1], &node_txn[0]);
2570 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2571 expect_payment_failed!(nodes[1], payment_hash_2, true);
2573 get_announce_close_broadcast_events(&nodes, 0, 1);
2574 assert_eq!(nodes[0].node.list_channels().len(), 0);
2575 assert_eq!(nodes[1].node.list_channels().len(), 0);
2579 fn claim_htlc_outputs_single_tx() {
2580 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2581 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2582 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2585 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2587 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2589 // Rebalance the network to generate htlc in the two directions
2590 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2591 // 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
2592 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2593 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2594 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2596 // Get the will-be-revoked local txn from node[0]
2597 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2599 //Revoke the old state
2600 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2603 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2604 check_added_monitors!(nodes[0], 1);
2605 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2606 check_added_monitors!(nodes[1], 1);
2607 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2608 let mut events = nodes[0].node.get_and_clear_pending_events();
2609 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2611 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2612 _ => panic!("Unexpected event"),
2615 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2616 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2618 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2619 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2621 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2622 assert_eq!(node_txn[0].input.len(), 1);
2623 check_spends!(node_txn[0], chan_1.3);
2624 assert_eq!(node_txn[1].input.len(), 1);
2625 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2626 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2627 check_spends!(node_txn[1], node_txn[0]);
2629 // Justice transactions are indices 1-2-4
2630 assert_eq!(node_txn[2].input.len(), 1);
2631 assert_eq!(node_txn[3].input.len(), 1);
2632 assert_eq!(node_txn[4].input.len(), 1);
2634 check_spends!(node_txn[2], revoked_local_txn[0]);
2635 check_spends!(node_txn[3], revoked_local_txn[0]);
2636 check_spends!(node_txn[4], revoked_local_txn[0]);
2638 let mut witness_lens = BTreeSet::new();
2639 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2640 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2641 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2642 assert_eq!(witness_lens.len(), 3);
2643 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2644 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2645 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2647 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2648 // ANTI_REORG_DELAY confirmations.
2649 mine_transaction(&nodes[1], &node_txn[2]);
2650 mine_transaction(&nodes[1], &node_txn[3]);
2651 mine_transaction(&nodes[1], &node_txn[4]);
2652 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2653 expect_payment_failed!(nodes[1], payment_hash_2, true);
2655 get_announce_close_broadcast_events(&nodes, 0, 1);
2656 assert_eq!(nodes[0].node.list_channels().len(), 0);
2657 assert_eq!(nodes[1].node.list_channels().len(), 0);
2661 fn test_htlc_on_chain_success() {
2662 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2663 // the preimage backward accordingly. So here we test that ChannelManager is
2664 // broadcasting the right event to other nodes in payment path.
2665 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2666 // A --------------------> B ----------------------> C (preimage)
2667 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2668 // commitment transaction was broadcast.
2669 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2671 // B should be able to claim via preimage if A then broadcasts its local tx.
2672 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2673 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2674 // PaymentSent event).
2676 let chanmon_cfgs = create_chanmon_cfgs(3);
2677 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2678 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2679 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2681 // Create some initial channels
2682 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2683 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2685 // Ensure all nodes are at the same height
2686 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2687 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2688 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2689 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2691 // Rebalance the network a bit by relaying one payment through all the channels...
2692 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2693 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2695 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2696 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2698 // Broadcast legit commitment tx from C on B's chain
2699 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2700 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2701 assert_eq!(commitment_tx.len(), 1);
2702 check_spends!(commitment_tx[0], chan_2.3);
2703 nodes[2].node.claim_funds(our_payment_preimage);
2704 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2705 nodes[2].node.claim_funds(our_payment_preimage_2);
2706 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2707 check_added_monitors!(nodes[2], 2);
2708 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2709 assert!(updates.update_add_htlcs.is_empty());
2710 assert!(updates.update_fail_htlcs.is_empty());
2711 assert!(updates.update_fail_malformed_htlcs.is_empty());
2712 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2714 mine_transaction(&nodes[2], &commitment_tx[0]);
2715 check_closed_broadcast!(nodes[2], true);
2716 check_added_monitors!(nodes[2], 1);
2717 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2718 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)
2719 assert_eq!(node_txn.len(), 5);
2720 assert_eq!(node_txn[0], node_txn[3]);
2721 assert_eq!(node_txn[1], node_txn[4]);
2722 assert_eq!(node_txn[2], commitment_tx[0]);
2723 check_spends!(node_txn[0], commitment_tx[0]);
2724 check_spends!(node_txn[1], commitment_tx[0]);
2725 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2726 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2727 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2728 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2729 assert_eq!(node_txn[0].lock_time, 0);
2730 assert_eq!(node_txn[1].lock_time, 0);
2732 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2733 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2734 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2735 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2737 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2738 assert_eq!(added_monitors.len(), 1);
2739 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2740 added_monitors.clear();
2742 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2743 assert_eq!(forwarded_events.len(), 3);
2744 match forwarded_events[0] {
2745 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2746 _ => panic!("Unexpected event"),
2748 let chan_id = Some(chan_1.2);
2749 match forwarded_events[1] {
2750 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2751 assert_eq!(fee_earned_msat, Some(1000));
2752 assert_eq!(prev_channel_id, chan_id);
2753 assert_eq!(claim_from_onchain_tx, true);
2754 assert_eq!(next_channel_id, Some(chan_2.2));
2758 match forwarded_events[2] {
2759 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2760 assert_eq!(fee_earned_msat, Some(1000));
2761 assert_eq!(prev_channel_id, chan_id);
2762 assert_eq!(claim_from_onchain_tx, true);
2763 assert_eq!(next_channel_id, Some(chan_2.2));
2767 let events = nodes[1].node.get_and_clear_pending_msg_events();
2769 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2770 assert_eq!(added_monitors.len(), 2);
2771 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2772 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2773 added_monitors.clear();
2775 assert_eq!(events.len(), 3);
2777 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2778 _ => panic!("Unexpected event"),
2781 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2782 _ => panic!("Unexpected event"),
2786 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, .. } } => {
2787 assert!(update_add_htlcs.is_empty());
2788 assert!(update_fail_htlcs.is_empty());
2789 assert_eq!(update_fulfill_htlcs.len(), 1);
2790 assert!(update_fail_malformed_htlcs.is_empty());
2791 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2793 _ => panic!("Unexpected event"),
2795 macro_rules! check_tx_local_broadcast {
2796 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2797 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2798 assert_eq!(node_txn.len(), 3);
2799 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2800 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2801 check_spends!(node_txn[1], $commitment_tx);
2802 check_spends!(node_txn[2], $commitment_tx);
2803 assert_ne!(node_txn[1].lock_time, 0);
2804 assert_ne!(node_txn[2].lock_time, 0);
2806 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2807 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2808 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2809 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2811 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2812 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2813 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2814 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2816 check_spends!(node_txn[0], $chan_tx);
2817 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2821 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2822 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2823 // timeout-claim of the output that nodes[2] just claimed via success.
2824 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2826 // Broadcast legit commitment tx from A on B's chain
2827 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2828 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2829 check_spends!(node_a_commitment_tx[0], chan_1.3);
2830 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2831 check_closed_broadcast!(nodes[1], true);
2832 check_added_monitors!(nodes[1], 1);
2833 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2834 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2835 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2836 let commitment_spend =
2837 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2838 check_spends!(node_txn[1], commitment_tx[0]);
2839 check_spends!(node_txn[2], commitment_tx[0]);
2840 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2843 check_spends!(node_txn[0], commitment_tx[0]);
2844 check_spends!(node_txn[1], commitment_tx[0]);
2845 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2849 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2850 assert_eq!(commitment_spend.input.len(), 2);
2851 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2852 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853 assert_eq!(commitment_spend.lock_time, 0);
2854 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2855 check_spends!(node_txn[3], chan_1.3);
2856 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2857 check_spends!(node_txn[4], node_txn[3]);
2858 check_spends!(node_txn[5], node_txn[3]);
2859 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2860 // we already checked the same situation with A.
2862 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2863 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2864 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2865 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2866 check_closed_broadcast!(nodes[0], true);
2867 check_added_monitors!(nodes[0], 1);
2868 let events = nodes[0].node.get_and_clear_pending_events();
2869 assert_eq!(events.len(), 5);
2870 let mut first_claimed = false;
2871 for event in events {
2873 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2874 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2875 assert!(!first_claimed);
2876 first_claimed = true;
2878 assert_eq!(payment_preimage, our_payment_preimage_2);
2879 assert_eq!(payment_hash, payment_hash_2);
2882 Event::PaymentPathSuccessful { .. } => {},
2883 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2884 _ => panic!("Unexpected event"),
2887 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2890 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2891 // Test that in case of a unilateral close onchain, we detect the state of output and
2892 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2893 // broadcasting the right event to other nodes in payment path.
2894 // A ------------------> B ----------------------> C (timeout)
2895 // B's commitment tx C's commitment tx
2897 // B's HTLC timeout tx B's timeout tx
2899 let chanmon_cfgs = create_chanmon_cfgs(3);
2900 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2901 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2902 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2903 *nodes[0].connect_style.borrow_mut() = connect_style;
2904 *nodes[1].connect_style.borrow_mut() = connect_style;
2905 *nodes[2].connect_style.borrow_mut() = connect_style;
2907 // Create some intial channels
2908 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2909 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2911 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2912 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2913 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2915 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2917 // Broadcast legit commitment tx from C on B's chain
2918 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2919 check_spends!(commitment_tx[0], chan_2.3);
2920 nodes[2].node.fail_htlc_backwards(&payment_hash);
2921 check_added_monitors!(nodes[2], 0);
2922 expect_pending_htlcs_forwardable!(nodes[2]);
2923 check_added_monitors!(nodes[2], 1);
2925 let events = nodes[2].node.get_and_clear_pending_msg_events();
2926 assert_eq!(events.len(), 1);
2928 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, .. } } => {
2929 assert!(update_add_htlcs.is_empty());
2930 assert!(!update_fail_htlcs.is_empty());
2931 assert!(update_fulfill_htlcs.is_empty());
2932 assert!(update_fail_malformed_htlcs.is_empty());
2933 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2935 _ => panic!("Unexpected event"),
2937 mine_transaction(&nodes[2], &commitment_tx[0]);
2938 check_closed_broadcast!(nodes[2], true);
2939 check_added_monitors!(nodes[2], 1);
2940 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2941 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2942 assert_eq!(node_txn.len(), 1);
2943 check_spends!(node_txn[0], chan_2.3);
2944 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2946 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2947 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2948 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2949 mine_transaction(&nodes[1], &commitment_tx[0]);
2950 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2953 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2954 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2955 assert_eq!(node_txn[0], node_txn[3]);
2956 assert_eq!(node_txn[1], node_txn[4]);
2958 check_spends!(node_txn[2], commitment_tx[0]);
2959 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2961 check_spends!(node_txn[0], chan_2.3);
2962 check_spends!(node_txn[1], node_txn[0]);
2963 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2964 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2966 timeout_tx = node_txn[2].clone();
2970 mine_transaction(&nodes[1], &timeout_tx);
2971 check_added_monitors!(nodes[1], 1);
2972 check_closed_broadcast!(nodes[1], true);
2974 // B will rebroadcast a fee-bumped timeout transaction here.
2975 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2976 assert_eq!(node_txn.len(), 1);
2977 check_spends!(node_txn[0], commitment_tx[0]);
2980 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2982 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2983 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2984 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2985 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2986 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2987 if node_txn.len() == 1 {
2988 check_spends!(node_txn[0], chan_2.3);
2990 assert_eq!(node_txn.len(), 0);
2994 expect_pending_htlcs_forwardable!(nodes[1]);
2995 check_added_monitors!(nodes[1], 1);
2996 let events = nodes[1].node.get_and_clear_pending_msg_events();
2997 assert_eq!(events.len(), 1);
2999 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, .. } } => {
3000 assert!(update_add_htlcs.is_empty());
3001 assert!(!update_fail_htlcs.is_empty());
3002 assert!(update_fulfill_htlcs.is_empty());
3003 assert!(update_fail_malformed_htlcs.is_empty());
3004 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3006 _ => panic!("Unexpected event"),
3009 // Broadcast legit commitment tx from B on A's chain
3010 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3011 check_spends!(commitment_tx[0], chan_1.3);
3013 mine_transaction(&nodes[0], &commitment_tx[0]);
3014 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3016 check_closed_broadcast!(nodes[0], true);
3017 check_added_monitors!(nodes[0], 1);
3018 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3019 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3020 assert_eq!(node_txn.len(), 2);
3021 check_spends!(node_txn[0], chan_1.3);
3022 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3023 check_spends!(node_txn[1], commitment_tx[0]);
3024 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3028 fn test_htlc_on_chain_timeout() {
3029 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3030 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3031 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3035 fn test_simple_commitment_revoked_fail_backward() {
3036 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3037 // and fail backward accordingly.
3039 let chanmon_cfgs = create_chanmon_cfgs(3);
3040 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3041 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3042 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3044 // Create some initial channels
3045 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3046 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3048 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3049 // Get the will-be-revoked local txn from nodes[2]
3050 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3051 // Revoke the old state
3052 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3054 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3056 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3057 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3058 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3059 check_added_monitors!(nodes[1], 1);
3060 check_closed_broadcast!(nodes[1], true);
3062 expect_pending_htlcs_forwardable!(nodes[1]);
3063 check_added_monitors!(nodes[1], 1);
3064 let events = nodes[1].node.get_and_clear_pending_msg_events();
3065 assert_eq!(events.len(), 1);
3067 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, .. } } => {
3068 assert!(update_add_htlcs.is_empty());
3069 assert_eq!(update_fail_htlcs.len(), 1);
3070 assert!(update_fulfill_htlcs.is_empty());
3071 assert!(update_fail_malformed_htlcs.is_empty());
3072 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3074 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3075 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3076 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3078 _ => panic!("Unexpected event"),
3082 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3083 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3084 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3085 // commitment transaction anymore.
3086 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3087 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3088 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3089 // technically disallowed and we should probably handle it reasonably.
3090 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3091 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3093 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3094 // commitment_signed (implying it will be in the latest remote commitment transaction).
3095 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3096 // and once they revoke the previous commitment transaction (allowing us to send a new
3097 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3098 let chanmon_cfgs = create_chanmon_cfgs(3);
3099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3103 // Create some initial channels
3104 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3105 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3107 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 });
3108 // Get the will-be-revoked local txn from nodes[2]
3109 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3110 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3111 // Revoke the old state
3112 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3114 let value = if use_dust {
3115 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3116 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3117 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3120 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3121 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3122 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3124 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3125 expect_pending_htlcs_forwardable!(nodes[2]);
3126 check_added_monitors!(nodes[2], 1);
3127 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3128 assert!(updates.update_add_htlcs.is_empty());
3129 assert!(updates.update_fulfill_htlcs.is_empty());
3130 assert!(updates.update_fail_malformed_htlcs.is_empty());
3131 assert_eq!(updates.update_fail_htlcs.len(), 1);
3132 assert!(updates.update_fee.is_none());
3133 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3134 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3135 // Drop the last RAA from 3 -> 2
3137 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3138 expect_pending_htlcs_forwardable!(nodes[2]);
3139 check_added_monitors!(nodes[2], 1);
3140 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3141 assert!(updates.update_add_htlcs.is_empty());
3142 assert!(updates.update_fulfill_htlcs.is_empty());
3143 assert!(updates.update_fail_malformed_htlcs.is_empty());
3144 assert_eq!(updates.update_fail_htlcs.len(), 1);
3145 assert!(updates.update_fee.is_none());
3146 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3147 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3148 check_added_monitors!(nodes[1], 1);
3149 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3150 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3151 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3152 check_added_monitors!(nodes[2], 1);
3154 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3155 expect_pending_htlcs_forwardable!(nodes[2]);
3156 check_added_monitors!(nodes[2], 1);
3157 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3158 assert!(updates.update_add_htlcs.is_empty());
3159 assert!(updates.update_fulfill_htlcs.is_empty());
3160 assert!(updates.update_fail_malformed_htlcs.is_empty());
3161 assert_eq!(updates.update_fail_htlcs.len(), 1);
3162 assert!(updates.update_fee.is_none());
3163 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3164 // At this point first_payment_hash has dropped out of the latest two commitment
3165 // transactions that nodes[1] is tracking...
3166 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3167 check_added_monitors!(nodes[1], 1);
3168 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3169 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3170 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3171 check_added_monitors!(nodes[2], 1);
3173 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3174 // on nodes[2]'s RAA.
3175 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3176 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3177 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3178 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3179 check_added_monitors!(nodes[1], 0);
3182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3183 // One monitor for the new revocation preimage, no second on as we won't generate a new
3184 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3185 check_added_monitors!(nodes[1], 1);
3186 let events = nodes[1].node.get_and_clear_pending_events();
3187 assert_eq!(events.len(), 1);
3189 Event::PendingHTLCsForwardable { .. } => { },
3190 _ => panic!("Unexpected event"),
3192 // Deliberately don't process the pending fail-back so they all fail back at once after
3193 // block connection just like the !deliver_bs_raa case
3196 let mut failed_htlcs = HashSet::new();
3197 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3199 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3200 check_added_monitors!(nodes[1], 1);
3201 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3202 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3204 let events = nodes[1].node.get_and_clear_pending_events();
3205 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3207 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3208 _ => panic!("Unexepected event"),
3211 Event::PaymentPathFailed { ref payment_hash, .. } => {
3212 assert_eq!(*payment_hash, fourth_payment_hash);
3214 _ => panic!("Unexpected event"),
3216 if !deliver_bs_raa {
3218 Event::PaymentFailed { ref payment_hash, .. } => {
3219 assert_eq!(*payment_hash, fourth_payment_hash);
3221 _ => panic!("Unexpected event"),
3224 Event::PendingHTLCsForwardable { .. } => { },
3225 _ => panic!("Unexpected event"),
3228 nodes[1].node.process_pending_htlc_forwards();
3229 check_added_monitors!(nodes[1], 1);
3231 let events = nodes[1].node.get_and_clear_pending_msg_events();
3232 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3233 match events[if deliver_bs_raa { 1 } else { 0 }] {
3234 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3235 _ => panic!("Unexpected event"),
3237 match events[if deliver_bs_raa { 2 } else { 1 }] {
3238 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3239 assert_eq!(channel_id, chan_2.2);
3240 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3242 _ => panic!("Unexpected event"),
3246 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, .. } } => {
3247 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3248 assert_eq!(update_add_htlcs.len(), 1);
3249 assert!(update_fulfill_htlcs.is_empty());
3250 assert!(update_fail_htlcs.is_empty());
3251 assert!(update_fail_malformed_htlcs.is_empty());
3253 _ => panic!("Unexpected event"),
3256 match events[if deliver_bs_raa { 3 } else { 2 }] {
3257 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, .. } } => {
3258 assert!(update_add_htlcs.is_empty());
3259 assert_eq!(update_fail_htlcs.len(), 3);
3260 assert!(update_fulfill_htlcs.is_empty());
3261 assert!(update_fail_malformed_htlcs.is_empty());
3262 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3264 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3265 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3266 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3268 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3270 let events = nodes[0].node.get_and_clear_pending_events();
3271 assert_eq!(events.len(), 3);
3273 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3274 assert!(failed_htlcs.insert(payment_hash.0));
3275 // If we delivered B's RAA we got an unknown preimage error, not something
3276 // that we should update our routing table for.
3277 if !deliver_bs_raa {
3278 assert!(network_update.is_some());
3281 _ => panic!("Unexpected event"),
3284 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3285 assert!(failed_htlcs.insert(payment_hash.0));
3286 assert!(network_update.is_some());
3288 _ => panic!("Unexpected event"),
3291 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3292 assert!(failed_htlcs.insert(payment_hash.0));
3293 assert!(network_update.is_some());
3295 _ => panic!("Unexpected event"),
3298 _ => panic!("Unexpected event"),
3301 assert!(failed_htlcs.contains(&first_payment_hash.0));
3302 assert!(failed_htlcs.contains(&second_payment_hash.0));
3303 assert!(failed_htlcs.contains(&third_payment_hash.0));
3307 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3308 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3309 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3310 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3311 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3315 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3316 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3317 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3318 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3319 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3323 fn fail_backward_pending_htlc_upon_channel_failure() {
3324 let chanmon_cfgs = create_chanmon_cfgs(2);
3325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3327 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3328 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3330 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3332 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3333 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3334 check_added_monitors!(nodes[0], 1);
3336 let payment_event = {
3337 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3338 assert_eq!(events.len(), 1);
3339 SendEvent::from_event(events.remove(0))
3341 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3342 assert_eq!(payment_event.msgs.len(), 1);
3345 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3346 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3348 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3349 check_added_monitors!(nodes[0], 0);
3351 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3354 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3356 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3358 let secp_ctx = Secp256k1::new();
3359 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3360 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3361 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3362 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3363 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3365 // Send a 0-msat update_add_htlc to fail the channel.
3366 let update_add_htlc = msgs::UpdateAddHTLC {
3372 onion_routing_packet,
3374 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3376 let events = nodes[0].node.get_and_clear_pending_events();
3377 assert_eq!(events.len(), 2);
3378 // Check that Alice fails backward the pending HTLC from the second payment.
3380 Event::PaymentPathFailed { payment_hash, .. } => {
3381 assert_eq!(payment_hash, failed_payment_hash);
3383 _ => panic!("Unexpected event"),
3386 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3387 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3389 _ => panic!("Unexpected event {:?}", events[1]),
3391 check_closed_broadcast!(nodes[0], true);
3392 check_added_monitors!(nodes[0], 1);
3396 fn test_htlc_ignore_latest_remote_commitment() {
3397 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3398 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3399 let chanmon_cfgs = create_chanmon_cfgs(2);
3400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3403 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3405 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3406 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3407 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3408 check_closed_broadcast!(nodes[0], true);
3409 check_added_monitors!(nodes[0], 1);
3410 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3412 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3413 assert_eq!(node_txn.len(), 3);
3414 assert_eq!(node_txn[0], node_txn[1]);
3416 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3417 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3418 check_closed_broadcast!(nodes[1], true);
3419 check_added_monitors!(nodes[1], 1);
3420 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3422 // Duplicate the connect_block call since this may happen due to other listeners
3423 // registering new transactions
3424 header.prev_blockhash = header.block_hash();
3425 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3429 fn test_force_close_fail_back() {
3430 // Check which HTLCs are failed-backwards on channel force-closure
3431 let chanmon_cfgs = create_chanmon_cfgs(3);
3432 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3433 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3434 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3435 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3436 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3438 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3440 let mut payment_event = {
3441 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3442 check_added_monitors!(nodes[0], 1);
3444 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3445 assert_eq!(events.len(), 1);
3446 SendEvent::from_event(events.remove(0))
3449 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3450 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3452 expect_pending_htlcs_forwardable!(nodes[1]);
3454 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3455 assert_eq!(events_2.len(), 1);
3456 payment_event = SendEvent::from_event(events_2.remove(0));
3457 assert_eq!(payment_event.msgs.len(), 1);
3459 check_added_monitors!(nodes[1], 1);
3460 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3461 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3462 check_added_monitors!(nodes[2], 1);
3463 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3465 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3466 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3467 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3469 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3470 check_closed_broadcast!(nodes[2], true);
3471 check_added_monitors!(nodes[2], 1);
3472 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3474 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3475 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3476 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3477 // back to nodes[1] upon timeout otherwise.
3478 assert_eq!(node_txn.len(), 1);
3482 mine_transaction(&nodes[1], &tx);
3484 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3485 check_closed_broadcast!(nodes[1], true);
3486 check_added_monitors!(nodes[1], 1);
3487 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3489 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3491 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3492 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3494 mine_transaction(&nodes[2], &tx);
3495 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3496 assert_eq!(node_txn.len(), 1);
3497 assert_eq!(node_txn[0].input.len(), 1);
3498 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3499 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3500 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3502 check_spends!(node_txn[0], tx);
3506 fn test_dup_events_on_peer_disconnect() {
3507 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3508 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3509 // as we used to generate the event immediately upon receipt of the payment preimage in the
3510 // update_fulfill_htlc message.
3512 let chanmon_cfgs = create_chanmon_cfgs(2);
3513 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3514 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3515 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3516 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3518 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3520 nodes[1].node.claim_funds(payment_preimage);
3521 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3522 check_added_monitors!(nodes[1], 1);
3523 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3524 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3525 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3527 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3528 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3530 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3531 expect_payment_path_successful!(nodes[0]);
3535 fn test_peer_disconnected_before_funding_broadcasted() {
3536 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3537 // before the funding transaction has been broadcasted.
3538 let chanmon_cfgs = create_chanmon_cfgs(2);
3539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3543 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3544 // broadcasted, even though it's created by `nodes[0]`.
3545 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();
3546 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3547 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3548 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3549 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3551 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3552 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3554 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3556 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3557 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3559 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3560 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3563 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3566 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3567 // disconnected before the funding transaction was broadcasted.
3568 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3569 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3571 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3572 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3576 fn test_simple_peer_disconnect() {
3577 // Test that we can reconnect when there are no lost messages
3578 let chanmon_cfgs = create_chanmon_cfgs(3);
3579 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3580 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3581 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3582 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3583 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3585 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3586 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3587 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3590 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3591 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3592 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3594 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3595 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3596 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3598 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3599 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3600 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3601 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3603 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3604 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3606 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3607 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3609 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3611 let events = nodes[0].node.get_and_clear_pending_events();
3612 assert_eq!(events.len(), 3);
3614 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3615 assert_eq!(payment_preimage, payment_preimage_3);
3616 assert_eq!(payment_hash, payment_hash_3);
3618 _ => panic!("Unexpected event"),
3621 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3622 assert_eq!(payment_hash, payment_hash_5);
3623 assert!(rejected_by_dest);
3625 _ => panic!("Unexpected event"),
3628 Event::PaymentPathSuccessful { .. } => {},
3629 _ => panic!("Unexpected event"),
3633 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3634 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3637 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3638 // Test that we can reconnect when in-flight HTLC updates get dropped
3639 let chanmon_cfgs = create_chanmon_cfgs(2);
3640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3642 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3644 let mut as_channel_ready = None;
3645 if messages_delivered == 0 {
3646 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3647 as_channel_ready = Some(channel_ready);
3648 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3649 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3650 // it before the channel_reestablish message.
3652 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3655 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3657 let payment_event = {
3658 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3659 check_added_monitors!(nodes[0], 1);
3661 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3662 assert_eq!(events.len(), 1);
3663 SendEvent::from_event(events.remove(0))
3665 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3667 if messages_delivered < 2 {
3668 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3670 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3671 if messages_delivered >= 3 {
3672 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3673 check_added_monitors!(nodes[1], 1);
3674 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3676 if messages_delivered >= 4 {
3677 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3678 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3679 check_added_monitors!(nodes[0], 1);
3681 if messages_delivered >= 5 {
3682 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3683 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3684 // No commitment_signed so get_event_msg's assert(len == 1) passes
3685 check_added_monitors!(nodes[0], 1);
3687 if messages_delivered >= 6 {
3688 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3689 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3690 check_added_monitors!(nodes[1], 1);
3697 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3698 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3699 if messages_delivered < 3 {
3700 if simulate_broken_lnd {
3701 // lnd has a long-standing bug where they send a channel_ready prior to a
3702 // channel_reestablish if you reconnect prior to channel_ready time.
3704 // Here we simulate that behavior, delivering a channel_ready immediately on
3705 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3706 // in `reconnect_nodes` but we currently don't fail based on that.
3708 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3709 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3711 // Even if the channel_ready messages get exchanged, as long as nothing further was
3712 // received on either side, both sides will need to resend them.
3713 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714 } else if messages_delivered == 3 {
3715 // nodes[0] still wants its RAA + commitment_signed
3716 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3717 } else if messages_delivered == 4 {
3718 // nodes[0] still wants its commitment_signed
3719 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720 } else if messages_delivered == 5 {
3721 // nodes[1] still wants its final RAA
3722 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3723 } else if messages_delivered == 6 {
3724 // Everything was delivered...
3725 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728 let events_1 = nodes[1].node.get_and_clear_pending_events();
3729 assert_eq!(events_1.len(), 1);
3731 Event::PendingHTLCsForwardable { .. } => { },
3732 _ => panic!("Unexpected event"),
3735 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3736 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3737 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3739 nodes[1].node.process_pending_htlc_forwards();
3741 let events_2 = nodes[1].node.get_and_clear_pending_events();
3742 assert_eq!(events_2.len(), 1);
3744 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3745 assert_eq!(payment_hash_1, *payment_hash);
3746 assert_eq!(amount_msat, 1_000_000);
3748 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3749 assert!(payment_preimage.is_none());
3750 assert_eq!(payment_secret_1, *payment_secret);
3752 _ => panic!("expected PaymentPurpose::InvoicePayment")
3755 _ => panic!("Unexpected event"),
3758 nodes[1].node.claim_funds(payment_preimage_1);
3759 check_added_monitors!(nodes[1], 1);
3760 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3762 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3763 assert_eq!(events_3.len(), 1);
3764 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3765 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3766 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3767 assert!(updates.update_add_htlcs.is_empty());
3768 assert!(updates.update_fail_htlcs.is_empty());
3769 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3770 assert!(updates.update_fail_malformed_htlcs.is_empty());
3771 assert!(updates.update_fee.is_none());
3772 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3774 _ => panic!("Unexpected event"),
3777 if messages_delivered >= 1 {
3778 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3780 let events_4 = nodes[0].node.get_and_clear_pending_events();
3781 assert_eq!(events_4.len(), 1);
3783 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3784 assert_eq!(payment_preimage_1, *payment_preimage);
3785 assert_eq!(payment_hash_1, *payment_hash);
3787 _ => panic!("Unexpected event"),
3790 if messages_delivered >= 2 {
3791 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3792 check_added_monitors!(nodes[0], 1);
3793 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3795 if messages_delivered >= 3 {
3796 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3797 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3798 check_added_monitors!(nodes[1], 1);
3800 if messages_delivered >= 4 {
3801 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3802 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3803 // No commitment_signed so get_event_msg's assert(len == 1) passes
3804 check_added_monitors!(nodes[1], 1);
3806 if messages_delivered >= 5 {
3807 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3808 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3809 check_added_monitors!(nodes[0], 1);
3816 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818 if messages_delivered < 2 {
3819 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820 if messages_delivered < 1 {
3821 expect_payment_sent!(nodes[0], payment_preimage_1);
3823 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3825 } else if messages_delivered == 2 {
3826 // nodes[0] still wants its RAA + commitment_signed
3827 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3828 } else if messages_delivered == 3 {
3829 // nodes[0] still wants its commitment_signed
3830 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831 } else if messages_delivered == 4 {
3832 // nodes[1] still wants its final RAA
3833 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3834 } else if messages_delivered == 5 {
3835 // Everything was delivered...
3836 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3839 if messages_delivered == 1 || messages_delivered == 2 {
3840 expect_payment_path_successful!(nodes[0]);
3843 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3844 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3845 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3847 if messages_delivered > 2 {
3848 expect_payment_path_successful!(nodes[0]);
3851 // Channel should still work fine...
3852 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3853 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3854 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3858 fn test_drop_messages_peer_disconnect_a() {
3859 do_test_drop_messages_peer_disconnect(0, true);
3860 do_test_drop_messages_peer_disconnect(0, false);
3861 do_test_drop_messages_peer_disconnect(1, false);
3862 do_test_drop_messages_peer_disconnect(2, false);
3866 fn test_drop_messages_peer_disconnect_b() {
3867 do_test_drop_messages_peer_disconnect(3, false);
3868 do_test_drop_messages_peer_disconnect(4, false);
3869 do_test_drop_messages_peer_disconnect(5, false);
3870 do_test_drop_messages_peer_disconnect(6, false);
3874 fn test_funding_peer_disconnect() {
3875 // Test that we can lock in our funding tx while disconnected
3876 let chanmon_cfgs = create_chanmon_cfgs(2);
3877 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3878 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3879 let persister: test_utils::TestPersister;
3880 let new_chain_monitor: test_utils::TestChainMonitor;
3881 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3882 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3883 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3885 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3886 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3888 confirm_transaction(&nodes[0], &tx);
3889 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3890 assert!(events_1.is_empty());
3892 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3894 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3895 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3897 confirm_transaction(&nodes[1], &tx);
3898 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3899 assert!(events_2.is_empty());
3901 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3902 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3903 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3904 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3906 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3907 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3908 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3909 assert_eq!(events_3.len(), 1);
3910 let as_channel_ready = match events_3[0] {
3911 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3912 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3915 _ => panic!("Unexpected event {:?}", events_3[0]),
3918 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3919 // announcement_signatures as well as channel_update.
3920 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3921 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3922 assert_eq!(events_4.len(), 3);
3924 let bs_channel_ready = match events_4[0] {
3925 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3926 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3927 chan_id = msg.channel_id;
3930 _ => panic!("Unexpected event {:?}", events_4[0]),
3932 let bs_announcement_sigs = match events_4[1] {
3933 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3934 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3937 _ => panic!("Unexpected event {:?}", events_4[1]),
3940 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3941 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3943 _ => panic!("Unexpected event {:?}", events_4[2]),
3946 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3947 // generates a duplicative private channel_update
3948 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3949 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3950 assert_eq!(events_5.len(), 1);
3952 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3953 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3955 _ => panic!("Unexpected event {:?}", events_5[0]),
3958 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3959 // announcement_signatures.
3960 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3961 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3962 assert_eq!(events_6.len(), 1);
3963 let as_announcement_sigs = match events_6[0] {
3964 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3965 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3968 _ => panic!("Unexpected event {:?}", events_6[0]),
3971 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3972 // broadcast the channel announcement globally, as well as re-send its (now-public)
3974 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3975 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3976 assert_eq!(events_7.len(), 1);
3977 let (chan_announcement, as_update) = match events_7[0] {
3978 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3979 (msg.clone(), update_msg.clone())
3981 _ => panic!("Unexpected event {:?}", events_7[0]),
3984 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3985 // same channel_announcement.
3986 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3987 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3988 assert_eq!(events_8.len(), 1);
3989 let bs_update = match events_8[0] {
3990 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3991 assert_eq!(*msg, chan_announcement);
3994 _ => panic!("Unexpected event {:?}", events_8[0]),
3997 // Provide the channel announcement and public updates to the network graph
3998 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3999 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4000 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4002 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4003 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4004 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4006 // Check that after deserialization and reconnection we can still generate an identical
4007 // channel_announcement from the cached signatures.
4008 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4010 let nodes_0_serialized = nodes[0].node.encode();
4011 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4012 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4014 persister = test_utils::TestPersister::new();
4015 let keys_manager = &chanmon_cfgs[0].keys_manager;
4016 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);
4017 nodes[0].chain_monitor = &new_chain_monitor;
4018 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4019 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4020 &mut chan_0_monitor_read, keys_manager).unwrap();
4021 assert!(chan_0_monitor_read.is_empty());
4023 let mut nodes_0_read = &nodes_0_serialized[..];
4024 let (_, nodes_0_deserialized_tmp) = {
4025 let mut channel_monitors = HashMap::new();
4026 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4027 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4028 default_config: UserConfig::default(),
4030 fee_estimator: node_cfgs[0].fee_estimator,
4031 chain_monitor: nodes[0].chain_monitor,
4032 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4033 logger: nodes[0].logger,
4037 nodes_0_deserialized = nodes_0_deserialized_tmp;
4038 assert!(nodes_0_read.is_empty());
4040 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4041 nodes[0].node = &nodes_0_deserialized;
4042 check_added_monitors!(nodes[0], 1);
4044 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4046 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4047 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4048 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4049 let mut found_announcement = false;
4050 for event in msgs.iter() {
4052 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4053 if *msg == chan_announcement { found_announcement = true; }
4055 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4056 _ => panic!("Unexpected event"),
4059 assert!(found_announcement);
4063 fn test_channel_ready_without_best_block_updated() {
4064 // Previously, if we were offline when a funding transaction was locked in, and then we came
4065 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4066 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4067 // channel_ready immediately instead.
4068 let chanmon_cfgs = create_chanmon_cfgs(2);
4069 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4070 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4071 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4072 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4074 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4076 let conf_height = nodes[0].best_block_info().1 + 1;
4077 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4078 let block_txn = [funding_tx];
4079 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4080 let conf_block_header = nodes[0].get_block_header(conf_height);
4081 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4083 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4084 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4085 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4089 fn test_drop_messages_peer_disconnect_dual_htlc() {
4090 // Test that we can handle reconnecting when both sides of a channel have pending
4091 // commitment_updates when we disconnect.
4092 let chanmon_cfgs = create_chanmon_cfgs(2);
4093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4095 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4096 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4098 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4100 // Now try to send a second payment which will fail to send
4101 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4102 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4103 check_added_monitors!(nodes[0], 1);
4105 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4106 assert_eq!(events_1.len(), 1);
4108 MessageSendEvent::UpdateHTLCs { .. } => {},
4109 _ => panic!("Unexpected event"),
4112 nodes[1].node.claim_funds(payment_preimage_1);
4113 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4114 check_added_monitors!(nodes[1], 1);
4116 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4117 assert_eq!(events_2.len(), 1);
4119 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 } } => {
4120 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4121 assert!(update_add_htlcs.is_empty());
4122 assert_eq!(update_fulfill_htlcs.len(), 1);
4123 assert!(update_fail_htlcs.is_empty());
4124 assert!(update_fail_malformed_htlcs.is_empty());
4125 assert!(update_fee.is_none());
4127 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4128 let events_3 = nodes[0].node.get_and_clear_pending_events();
4129 assert_eq!(events_3.len(), 1);
4131 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4132 assert_eq!(*payment_preimage, payment_preimage_1);
4133 assert_eq!(*payment_hash, payment_hash_1);
4135 _ => panic!("Unexpected event"),
4138 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4139 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4140 // No commitment_signed so get_event_msg's assert(len == 1) passes
4141 check_added_monitors!(nodes[0], 1);
4143 _ => panic!("Unexpected event"),
4146 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4147 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4149 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4150 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4151 assert_eq!(reestablish_1.len(), 1);
4152 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4153 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4154 assert_eq!(reestablish_2.len(), 1);
4156 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4157 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4158 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4159 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4161 assert!(as_resp.0.is_none());
4162 assert!(bs_resp.0.is_none());
4164 assert!(bs_resp.1.is_none());
4165 assert!(bs_resp.2.is_none());
4167 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4169 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4170 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4171 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4172 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4173 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4174 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4175 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4176 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4177 // No commitment_signed so get_event_msg's assert(len == 1) passes
4178 check_added_monitors!(nodes[1], 1);
4180 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4181 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4182 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4183 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4184 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4185 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4186 assert!(bs_second_commitment_signed.update_fee.is_none());
4187 check_added_monitors!(nodes[1], 1);
4189 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4190 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4191 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4192 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4193 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4194 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4195 assert!(as_commitment_signed.update_fee.is_none());
4196 check_added_monitors!(nodes[0], 1);
4198 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4199 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4200 // No commitment_signed so get_event_msg's assert(len == 1) passes
4201 check_added_monitors!(nodes[0], 1);
4203 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4204 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4205 // No commitment_signed so get_event_msg's assert(len == 1) passes
4206 check_added_monitors!(nodes[1], 1);
4208 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4209 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4210 check_added_monitors!(nodes[1], 1);
4212 expect_pending_htlcs_forwardable!(nodes[1]);
4214 let events_5 = nodes[1].node.get_and_clear_pending_events();
4215 assert_eq!(events_5.len(), 1);
4217 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4218 assert_eq!(payment_hash_2, *payment_hash);
4220 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4221 assert!(payment_preimage.is_none());
4222 assert_eq!(payment_secret_2, *payment_secret);
4224 _ => panic!("expected PaymentPurpose::InvoicePayment")
4227 _ => panic!("Unexpected event"),
4230 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4231 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4232 check_added_monitors!(nodes[0], 1);
4234 expect_payment_path_successful!(nodes[0]);
4235 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4238 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4239 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4240 // to avoid our counterparty failing the channel.
4241 let chanmon_cfgs = create_chanmon_cfgs(2);
4242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4244 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4246 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4248 let our_payment_hash = if send_partial_mpp {
4249 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4250 // Use the utility function send_payment_along_path to send the payment with MPP data which
4251 // indicates there are more HTLCs coming.
4252 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.
4253 let payment_id = PaymentId([42; 32]);
4254 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();
4255 check_added_monitors!(nodes[0], 1);
4256 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4257 assert_eq!(events.len(), 1);
4258 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4259 // hop should *not* yet generate any PaymentReceived event(s).
4260 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4263 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4266 let mut block = Block {
4267 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4270 connect_block(&nodes[0], &block);
4271 connect_block(&nodes[1], &block);
4272 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4273 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4274 block.header.prev_blockhash = block.block_hash();
4275 connect_block(&nodes[0], &block);
4276 connect_block(&nodes[1], &block);
4279 expect_pending_htlcs_forwardable!(nodes[1]);
4281 check_added_monitors!(nodes[1], 1);
4282 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4283 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4284 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4285 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4286 assert!(htlc_timeout_updates.update_fee.is_none());
4288 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4289 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4290 // 100_000 msat as u64, followed by the height at which we failed back above
4291 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4292 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4293 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4297 fn test_htlc_timeout() {
4298 do_test_htlc_timeout(true);
4299 do_test_htlc_timeout(false);
4302 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4303 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4304 let chanmon_cfgs = create_chanmon_cfgs(3);
4305 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4306 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4307 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4308 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4309 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4311 // Make sure all nodes are at the same starting height
4312 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4313 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4314 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4316 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4317 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4319 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4321 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4322 check_added_monitors!(nodes[1], 1);
4324 // Now attempt to route a second payment, which should be placed in the holding cell
4325 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4326 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4327 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4329 check_added_monitors!(nodes[0], 1);
4330 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4331 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4332 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4333 expect_pending_htlcs_forwardable!(nodes[1]);
4335 check_added_monitors!(nodes[1], 0);
4337 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4338 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4339 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4340 connect_blocks(&nodes[1], 1);
4343 expect_pending_htlcs_forwardable!(nodes[1]);
4344 check_added_monitors!(nodes[1], 1);
4345 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4346 assert_eq!(fail_commit.len(), 1);
4347 match fail_commit[0] {
4348 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4349 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4350 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4352 _ => unreachable!(),
4354 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4356 let events = nodes[1].node.get_and_clear_pending_events();
4357 assert_eq!(events.len(), 2);
4358 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4359 assert_eq!(*payment_hash, second_payment_hash);
4360 } else { panic!("Unexpected event"); }
4361 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4362 assert_eq!(*payment_hash, second_payment_hash);
4363 } else { panic!("Unexpected event"); }
4368 fn test_holding_cell_htlc_add_timeouts() {
4369 do_test_holding_cell_htlc_add_timeouts(false);
4370 do_test_holding_cell_htlc_add_timeouts(true);
4374 fn test_no_txn_manager_serialize_deserialize() {
4375 let chanmon_cfgs = create_chanmon_cfgs(2);
4376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4378 let logger: test_utils::TestLogger;
4379 let fee_estimator: test_utils::TestFeeEstimator;
4380 let persister: test_utils::TestPersister;
4381 let new_chain_monitor: test_utils::TestChainMonitor;
4382 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4383 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4385 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4387 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4389 let nodes_0_serialized = nodes[0].node.encode();
4390 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4391 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4392 .write(&mut chan_0_monitor_serialized).unwrap();
4394 logger = test_utils::TestLogger::new();
4395 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4396 persister = test_utils::TestPersister::new();
4397 let keys_manager = &chanmon_cfgs[0].keys_manager;
4398 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4399 nodes[0].chain_monitor = &new_chain_monitor;
4400 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4401 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4402 &mut chan_0_monitor_read, keys_manager).unwrap();
4403 assert!(chan_0_monitor_read.is_empty());
4405 let mut nodes_0_read = &nodes_0_serialized[..];
4406 let config = UserConfig::default();
4407 let (_, nodes_0_deserialized_tmp) = {
4408 let mut channel_monitors = HashMap::new();
4409 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4410 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4411 default_config: config,
4413 fee_estimator: &fee_estimator,
4414 chain_monitor: nodes[0].chain_monitor,
4415 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4420 nodes_0_deserialized = nodes_0_deserialized_tmp;
4421 assert!(nodes_0_read.is_empty());
4423 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4424 nodes[0].node = &nodes_0_deserialized;
4425 assert_eq!(nodes[0].node.list_channels().len(), 1);
4426 check_added_monitors!(nodes[0], 1);
4428 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4429 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4430 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4431 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4433 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4434 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4435 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4436 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4438 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4439 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4440 for node in nodes.iter() {
4441 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4442 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4443 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4446 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4450 fn test_manager_serialize_deserialize_events() {
4451 // This test makes sure the events field in ChannelManager survives de/serialization
4452 let chanmon_cfgs = create_chanmon_cfgs(2);
4453 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4454 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4455 let fee_estimator: test_utils::TestFeeEstimator;
4456 let persister: test_utils::TestPersister;
4457 let logger: test_utils::TestLogger;
4458 let new_chain_monitor: test_utils::TestChainMonitor;
4459 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4460 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4462 // Start creating a channel, but stop right before broadcasting the funding transaction
4463 let channel_value = 100000;
4464 let push_msat = 10001;
4465 let a_flags = InitFeatures::known();
4466 let b_flags = InitFeatures::known();
4467 let node_a = nodes.remove(0);
4468 let node_b = nodes.remove(0);
4469 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4470 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()));
4471 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()));
4473 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4475 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4476 check_added_monitors!(node_a, 0);
4478 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()));
4480 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4481 assert_eq!(added_monitors.len(), 1);
4482 assert_eq!(added_monitors[0].0, funding_output);
4483 added_monitors.clear();
4486 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4487 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4489 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4490 assert_eq!(added_monitors.len(), 1);
4491 assert_eq!(added_monitors[0].0, funding_output);
4492 added_monitors.clear();
4494 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4499 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4500 let nodes_0_serialized = nodes[0].node.encode();
4501 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4502 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4504 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4505 logger = test_utils::TestLogger::new();
4506 persister = test_utils::TestPersister::new();
4507 let keys_manager = &chanmon_cfgs[0].keys_manager;
4508 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4509 nodes[0].chain_monitor = &new_chain_monitor;
4510 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4511 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4512 &mut chan_0_monitor_read, keys_manager).unwrap();
4513 assert!(chan_0_monitor_read.is_empty());
4515 let mut nodes_0_read = &nodes_0_serialized[..];
4516 let config = UserConfig::default();
4517 let (_, nodes_0_deserialized_tmp) = {
4518 let mut channel_monitors = HashMap::new();
4519 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4520 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4521 default_config: config,
4523 fee_estimator: &fee_estimator,
4524 chain_monitor: nodes[0].chain_monitor,
4525 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4530 nodes_0_deserialized = nodes_0_deserialized_tmp;
4531 assert!(nodes_0_read.is_empty());
4533 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4535 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4536 nodes[0].node = &nodes_0_deserialized;
4538 // After deserializing, make sure the funding_transaction is still held by the channel manager
4539 let events_4 = nodes[0].node.get_and_clear_pending_events();
4540 assert_eq!(events_4.len(), 0);
4541 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4542 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4544 // Make sure the channel is functioning as though the de/serialization never happened
4545 assert_eq!(nodes[0].node.list_channels().len(), 1);
4546 check_added_monitors!(nodes[0], 1);
4548 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4549 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4550 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4551 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4553 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4554 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4555 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4556 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4558 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4559 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4560 for node in nodes.iter() {
4561 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4562 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4563 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4566 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4570 fn test_simple_manager_serialize_deserialize() {
4571 let chanmon_cfgs = create_chanmon_cfgs(2);
4572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4574 let logger: test_utils::TestLogger;
4575 let fee_estimator: test_utils::TestFeeEstimator;
4576 let persister: test_utils::TestPersister;
4577 let new_chain_monitor: test_utils::TestChainMonitor;
4578 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4579 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4580 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4582 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4583 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4585 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4587 let nodes_0_serialized = nodes[0].node.encode();
4588 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4589 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4591 logger = test_utils::TestLogger::new();
4592 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4593 persister = test_utils::TestPersister::new();
4594 let keys_manager = &chanmon_cfgs[0].keys_manager;
4595 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4596 nodes[0].chain_monitor = &new_chain_monitor;
4597 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4598 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4599 &mut chan_0_monitor_read, keys_manager).unwrap();
4600 assert!(chan_0_monitor_read.is_empty());
4602 let mut nodes_0_read = &nodes_0_serialized[..];
4603 let (_, nodes_0_deserialized_tmp) = {
4604 let mut channel_monitors = HashMap::new();
4605 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4606 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4607 default_config: UserConfig::default(),
4609 fee_estimator: &fee_estimator,
4610 chain_monitor: nodes[0].chain_monitor,
4611 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4616 nodes_0_deserialized = nodes_0_deserialized_tmp;
4617 assert!(nodes_0_read.is_empty());
4619 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4620 nodes[0].node = &nodes_0_deserialized;
4621 check_added_monitors!(nodes[0], 1);
4623 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4625 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4626 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4630 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4631 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4632 let chanmon_cfgs = create_chanmon_cfgs(4);
4633 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4634 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4635 let logger: test_utils::TestLogger;
4636 let fee_estimator: test_utils::TestFeeEstimator;
4637 let persister: test_utils::TestPersister;
4638 let new_chain_monitor: test_utils::TestChainMonitor;
4639 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4640 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4641 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4642 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4643 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4645 let mut node_0_stale_monitors_serialized = Vec::new();
4646 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4647 let mut writer = test_utils::TestVecWriter(Vec::new());
4648 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4649 node_0_stale_monitors_serialized.push(writer.0);
4652 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4654 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4655 let nodes_0_serialized = nodes[0].node.encode();
4657 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4658 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4659 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4660 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4662 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4664 let mut node_0_monitors_serialized = Vec::new();
4665 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4666 let mut writer = test_utils::TestVecWriter(Vec::new());
4667 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4668 node_0_monitors_serialized.push(writer.0);
4671 logger = test_utils::TestLogger::new();
4672 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4673 persister = test_utils::TestPersister::new();
4674 let keys_manager = &chanmon_cfgs[0].keys_manager;
4675 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4676 nodes[0].chain_monitor = &new_chain_monitor;
4679 let mut node_0_stale_monitors = Vec::new();
4680 for serialized in node_0_stale_monitors_serialized.iter() {
4681 let mut read = &serialized[..];
4682 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4683 assert!(read.is_empty());
4684 node_0_stale_monitors.push(monitor);
4687 let mut node_0_monitors = Vec::new();
4688 for serialized in node_0_monitors_serialized.iter() {
4689 let mut read = &serialized[..];
4690 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4691 assert!(read.is_empty());
4692 node_0_monitors.push(monitor);
4695 let mut nodes_0_read = &nodes_0_serialized[..];
4696 if let Err(msgs::DecodeError::InvalidValue) =
4697 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4698 default_config: UserConfig::default(),
4700 fee_estimator: &fee_estimator,
4701 chain_monitor: nodes[0].chain_monitor,
4702 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4704 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4706 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4709 let mut nodes_0_read = &nodes_0_serialized[..];
4710 let (_, nodes_0_deserialized_tmp) =
4711 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4712 default_config: UserConfig::default(),
4714 fee_estimator: &fee_estimator,
4715 chain_monitor: nodes[0].chain_monitor,
4716 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4718 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4720 nodes_0_deserialized = nodes_0_deserialized_tmp;
4721 assert!(nodes_0_read.is_empty());
4723 { // Channel close should result in a commitment tx
4724 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4725 assert_eq!(txn.len(), 1);
4726 check_spends!(txn[0], funding_tx);
4727 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4730 for monitor in node_0_monitors.drain(..) {
4731 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4732 check_added_monitors!(nodes[0], 1);
4734 nodes[0].node = &nodes_0_deserialized;
4735 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4737 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4738 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4739 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4740 //... and we can even still claim the payment!
4741 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4743 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4744 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4745 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4746 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4747 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4748 assert_eq!(msg_events.len(), 1);
4749 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4751 &ErrorAction::SendErrorMessage { ref msg } => {
4752 assert_eq!(msg.channel_id, channel_id);
4754 _ => panic!("Unexpected event!"),
4759 macro_rules! check_spendable_outputs {
4760 ($node: expr, $keysinterface: expr) => {
4762 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4763 let mut txn = Vec::new();
4764 let mut all_outputs = Vec::new();
4765 let secp_ctx = Secp256k1::new();
4766 for event in events.drain(..) {
4768 Event::SpendableOutputs { mut outputs } => {
4769 for outp in outputs.drain(..) {
4770 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4771 all_outputs.push(outp);
4774 _ => panic!("Unexpected event"),
4777 if all_outputs.len() > 1 {
4778 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) {
4788 fn test_claim_sizeable_push_msat() {
4789 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4790 let chanmon_cfgs = create_chanmon_cfgs(2);
4791 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4792 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4793 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4795 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4796 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4797 check_closed_broadcast!(nodes[1], true);
4798 check_added_monitors!(nodes[1], 1);
4799 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4800 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4801 assert_eq!(node_txn.len(), 1);
4802 check_spends!(node_txn[0], chan.3);
4803 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
4805 mine_transaction(&nodes[1], &node_txn[0]);
4806 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4808 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4809 assert_eq!(spend_txn.len(), 1);
4810 assert_eq!(spend_txn[0].input.len(), 1);
4811 check_spends!(spend_txn[0], node_txn[0]);
4812 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4816 fn test_claim_on_remote_sizeable_push_msat() {
4817 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4818 // to_remote output is encumbered by a P2WPKH
4819 let chanmon_cfgs = create_chanmon_cfgs(2);
4820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4825 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4826 check_closed_broadcast!(nodes[0], true);
4827 check_added_monitors!(nodes[0], 1);
4828 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4830 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4831 assert_eq!(node_txn.len(), 1);
4832 check_spends!(node_txn[0], chan.3);
4833 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
4835 mine_transaction(&nodes[1], &node_txn[0]);
4836 check_closed_broadcast!(nodes[1], true);
4837 check_added_monitors!(nodes[1], 1);
4838 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4839 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4841 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4842 assert_eq!(spend_txn.len(), 1);
4843 check_spends!(spend_txn[0], node_txn[0]);
4847 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4848 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4849 // to_remote output is encumbered by a P2WPKH
4851 let chanmon_cfgs = create_chanmon_cfgs(2);
4852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4856 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4857 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4858 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4859 assert_eq!(revoked_local_txn[0].input.len(), 1);
4860 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4862 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4863 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4864 check_closed_broadcast!(nodes[1], true);
4865 check_added_monitors!(nodes[1], 1);
4866 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4868 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4869 mine_transaction(&nodes[1], &node_txn[0]);
4870 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4872 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4873 assert_eq!(spend_txn.len(), 3);
4874 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4875 check_spends!(spend_txn[1], node_txn[0]);
4876 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4880 fn test_static_spendable_outputs_preimage_tx() {
4881 let chanmon_cfgs = create_chanmon_cfgs(2);
4882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4884 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4886 // Create some initial channels
4887 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4889 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4891 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4892 assert_eq!(commitment_tx[0].input.len(), 1);
4893 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4895 // Settle A's commitment tx on B's chain
4896 nodes[1].node.claim_funds(payment_preimage);
4897 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4898 check_added_monitors!(nodes[1], 1);
4899 mine_transaction(&nodes[1], &commitment_tx[0]);
4900 check_added_monitors!(nodes[1], 1);
4901 let events = nodes[1].node.get_and_clear_pending_msg_events();
4903 MessageSendEvent::UpdateHTLCs { .. } => {},
4904 _ => panic!("Unexpected event"),
4907 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4908 _ => panic!("Unexepected event"),
4911 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4912 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4913 assert_eq!(node_txn.len(), 3);
4914 check_spends!(node_txn[0], commitment_tx[0]);
4915 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4916 check_spends!(node_txn[1], chan_1.3);
4917 check_spends!(node_txn[2], node_txn[1]);
4919 mine_transaction(&nodes[1], &node_txn[0]);
4920 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4921 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4923 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4924 assert_eq!(spend_txn.len(), 1);
4925 check_spends!(spend_txn[0], node_txn[0]);
4929 fn test_static_spendable_outputs_timeout_tx() {
4930 let chanmon_cfgs = create_chanmon_cfgs(2);
4931 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4932 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4933 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4935 // Create some initial channels
4936 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4938 // Rebalance the network a bit by relaying one payment through all the channels ...
4939 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4941 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4943 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4944 assert_eq!(commitment_tx[0].input.len(), 1);
4945 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4947 // Settle A's commitment tx on B' chain
4948 mine_transaction(&nodes[1], &commitment_tx[0]);
4949 check_added_monitors!(nodes[1], 1);
4950 let events = nodes[1].node.get_and_clear_pending_msg_events();
4952 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4953 _ => panic!("Unexpected event"),
4955 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4957 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4958 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4959 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4960 check_spends!(node_txn[0], chan_1.3.clone());
4961 check_spends!(node_txn[1], commitment_tx[0].clone());
4962 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4964 mine_transaction(&nodes[1], &node_txn[1]);
4965 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4966 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4967 expect_payment_failed!(nodes[1], our_payment_hash, true);
4969 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4970 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4971 check_spends!(spend_txn[0], commitment_tx[0]);
4972 check_spends!(spend_txn[1], node_txn[1]);
4973 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4977 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4978 let chanmon_cfgs = create_chanmon_cfgs(2);
4979 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4980 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4981 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4983 // Create some initial channels
4984 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4986 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4987 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4988 assert_eq!(revoked_local_txn[0].input.len(), 1);
4989 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4991 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4993 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4994 check_closed_broadcast!(nodes[1], true);
4995 check_added_monitors!(nodes[1], 1);
4996 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4998 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4999 assert_eq!(node_txn.len(), 2);
5000 assert_eq!(node_txn[0].input.len(), 2);
5001 check_spends!(node_txn[0], revoked_local_txn[0]);
5003 mine_transaction(&nodes[1], &node_txn[0]);
5004 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5006 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5007 assert_eq!(spend_txn.len(), 1);
5008 check_spends!(spend_txn[0], node_txn[0]);
5012 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5013 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5014 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5017 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5019 // Create some initial channels
5020 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5022 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5023 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5024 assert_eq!(revoked_local_txn[0].input.len(), 1);
5025 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5027 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5029 // A will generate HTLC-Timeout from revoked commitment tx
5030 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5031 check_closed_broadcast!(nodes[0], true);
5032 check_added_monitors!(nodes[0], 1);
5033 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5034 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5036 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5037 assert_eq!(revoked_htlc_txn.len(), 2);
5038 check_spends!(revoked_htlc_txn[0], chan_1.3);
5039 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5040 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5041 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5042 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5044 // B will generate justice tx from A's revoked commitment/HTLC tx
5045 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5046 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5047 check_closed_broadcast!(nodes[1], true);
5048 check_added_monitors!(nodes[1], 1);
5049 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5051 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5052 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5053 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5054 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5055 // transactions next...
5056 assert_eq!(node_txn[0].input.len(), 3);
5057 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5059 assert_eq!(node_txn[1].input.len(), 2);
5060 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5061 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5062 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5064 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5065 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5068 assert_eq!(node_txn[2].input.len(), 1);
5069 check_spends!(node_txn[2], chan_1.3);
5071 mine_transaction(&nodes[1], &node_txn[1]);
5072 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5074 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5075 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5076 assert_eq!(spend_txn.len(), 1);
5077 assert_eq!(spend_txn[0].input.len(), 1);
5078 check_spends!(spend_txn[0], node_txn[1]);
5082 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5083 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5084 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5085 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5086 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5087 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5089 // Create some initial channels
5090 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5092 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5093 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5094 assert_eq!(revoked_local_txn[0].input.len(), 1);
5095 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5097 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5098 assert_eq!(revoked_local_txn[0].output.len(), 2);
5100 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5102 // B will generate HTLC-Success from revoked commitment tx
5103 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5104 check_closed_broadcast!(nodes[1], true);
5105 check_added_monitors!(nodes[1], 1);
5106 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5107 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5109 assert_eq!(revoked_htlc_txn.len(), 2);
5110 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5111 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5112 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5114 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5115 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5116 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5118 // A will generate justice tx from B's revoked commitment/HTLC tx
5119 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5120 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5121 check_closed_broadcast!(nodes[0], true);
5122 check_added_monitors!(nodes[0], 1);
5123 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5125 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5126 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5128 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5129 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5130 // transactions next...
5131 assert_eq!(node_txn[0].input.len(), 2);
5132 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5133 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5134 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5136 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5137 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5140 assert_eq!(node_txn[1].input.len(), 1);
5141 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5143 check_spends!(node_txn[2], chan_1.3);
5145 mine_transaction(&nodes[0], &node_txn[1]);
5146 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5148 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5149 // didn't try to generate any new transactions.
5151 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5152 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5153 assert_eq!(spend_txn.len(), 3);
5154 assert_eq!(spend_txn[0].input.len(), 1);
5155 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5156 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5157 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5158 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5162 fn test_onchain_to_onchain_claim() {
5163 // Test that in case of channel closure, we detect the state of output and claim HTLC
5164 // on downstream peer's remote commitment tx.
5165 // First, have C claim an HTLC against its own latest commitment transaction.
5166 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5168 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5171 let chanmon_cfgs = create_chanmon_cfgs(3);
5172 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5173 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5174 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5176 // Create some initial channels
5177 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5178 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5180 // Ensure all nodes are at the same height
5181 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5182 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5183 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5184 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5186 // Rebalance the network a bit by relaying one payment through all the channels ...
5187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5190 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5191 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5192 check_spends!(commitment_tx[0], chan_2.3);
5193 nodes[2].node.claim_funds(payment_preimage);
5194 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5195 check_added_monitors!(nodes[2], 1);
5196 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5197 assert!(updates.update_add_htlcs.is_empty());
5198 assert!(updates.update_fail_htlcs.is_empty());
5199 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5200 assert!(updates.update_fail_malformed_htlcs.is_empty());
5202 mine_transaction(&nodes[2], &commitment_tx[0]);
5203 check_closed_broadcast!(nodes[2], true);
5204 check_added_monitors!(nodes[2], 1);
5205 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5207 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5208 assert_eq!(c_txn.len(), 3);
5209 assert_eq!(c_txn[0], c_txn[2]);
5210 assert_eq!(commitment_tx[0], c_txn[1]);
5211 check_spends!(c_txn[1], chan_2.3);
5212 check_spends!(c_txn[2], c_txn[1]);
5213 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5214 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5215 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5216 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5218 // 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
5219 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5220 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5221 check_added_monitors!(nodes[1], 1);
5222 let events = nodes[1].node.get_and_clear_pending_events();
5223 assert_eq!(events.len(), 2);
5225 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5226 _ => panic!("Unexpected event"),
5229 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5230 assert_eq!(fee_earned_msat, Some(1000));
5231 assert_eq!(prev_channel_id, Some(chan_1.2));
5232 assert_eq!(claim_from_onchain_tx, true);
5233 assert_eq!(next_channel_id, Some(chan_2.2));
5235 _ => panic!("Unexpected event"),
5238 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5239 // ChannelMonitor: claim tx
5240 assert_eq!(b_txn.len(), 1);
5241 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5244 check_added_monitors!(nodes[1], 1);
5245 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5246 assert_eq!(msg_events.len(), 3);
5247 match msg_events[0] {
5248 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5249 _ => panic!("Unexpected event"),
5251 match msg_events[1] {
5252 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5253 _ => panic!("Unexpected event"),
5255 match msg_events[2] {
5256 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, .. } } => {
5257 assert!(update_add_htlcs.is_empty());
5258 assert!(update_fail_htlcs.is_empty());
5259 assert_eq!(update_fulfill_htlcs.len(), 1);
5260 assert!(update_fail_malformed_htlcs.is_empty());
5261 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5263 _ => panic!("Unexpected event"),
5265 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5266 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5267 mine_transaction(&nodes[1], &commitment_tx[0]);
5268 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5269 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5270 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5271 assert_eq!(b_txn.len(), 3);
5272 check_spends!(b_txn[1], chan_1.3);
5273 check_spends!(b_txn[2], b_txn[1]);
5274 check_spends!(b_txn[0], commitment_tx[0]);
5275 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5276 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5277 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5279 check_closed_broadcast!(nodes[1], true);
5280 check_added_monitors!(nodes[1], 1);
5284 fn test_duplicate_payment_hash_one_failure_one_success() {
5285 // Topology : A --> B --> C --> D
5286 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5287 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5288 // we forward one of the payments onwards to D.
5289 let chanmon_cfgs = create_chanmon_cfgs(4);
5290 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5291 // When this test was written, the default base fee floated based on the HTLC count.
5292 // It is now fixed, so we simply set the fee to the expected value here.
5293 let mut config = test_default_channel_config();
5294 config.channel_config.forwarding_fee_base_msat = 196;
5295 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5296 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5297 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5299 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5300 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5301 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5303 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5304 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5305 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5306 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5307 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5309 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5311 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5312 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5313 // script push size limit so that the below script length checks match
5314 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5315 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5316 .with_features(InvoiceFeatures::known());
5317 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5318 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5320 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5321 assert_eq!(commitment_txn[0].input.len(), 1);
5322 check_spends!(commitment_txn[0], chan_2.3);
5324 mine_transaction(&nodes[1], &commitment_txn[0]);
5325 check_closed_broadcast!(nodes[1], true);
5326 check_added_monitors!(nodes[1], 1);
5327 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5328 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5330 let htlc_timeout_tx;
5331 { // Extract one of the two HTLC-Timeout transaction
5332 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5333 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5334 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5335 check_spends!(node_txn[0], chan_2.3);
5337 check_spends!(node_txn[1], commitment_txn[0]);
5338 assert_eq!(node_txn[1].input.len(), 1);
5340 if node_txn.len() > 3 {
5341 check_spends!(node_txn[2], commitment_txn[0]);
5342 assert_eq!(node_txn[2].input.len(), 1);
5343 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5345 check_spends!(node_txn[3], commitment_txn[0]);
5346 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5348 check_spends!(node_txn[2], commitment_txn[0]);
5349 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5352 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5353 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5354 if node_txn.len() > 3 {
5355 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5357 htlc_timeout_tx = node_txn[1].clone();
5360 nodes[2].node.claim_funds(our_payment_preimage);
5361 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5363 mine_transaction(&nodes[2], &commitment_txn[0]);
5364 check_added_monitors!(nodes[2], 2);
5365 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5366 let events = nodes[2].node.get_and_clear_pending_msg_events();
5368 MessageSendEvent::UpdateHTLCs { .. } => {},
5369 _ => panic!("Unexpected event"),
5372 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5373 _ => panic!("Unexepected event"),
5375 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5376 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)
5377 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5378 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5379 assert_eq!(htlc_success_txn[0].input.len(), 1);
5380 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5381 assert_eq!(htlc_success_txn[1].input.len(), 1);
5382 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5383 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5384 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5385 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5386 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5387 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5389 mine_transaction(&nodes[1], &htlc_timeout_tx);
5390 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5391 expect_pending_htlcs_forwardable!(nodes[1]);
5392 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5393 assert!(htlc_updates.update_add_htlcs.is_empty());
5394 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5395 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5396 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5397 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5398 check_added_monitors!(nodes[1], 1);
5400 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5401 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5403 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5405 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5407 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5408 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5409 // and nodes[2] fee) is rounded down and then claimed in full.
5410 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5411 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5412 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5413 assert!(updates.update_add_htlcs.is_empty());
5414 assert!(updates.update_fail_htlcs.is_empty());
5415 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5416 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5417 assert!(updates.update_fail_malformed_htlcs.is_empty());
5418 check_added_monitors!(nodes[1], 1);
5420 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5421 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5423 let events = nodes[0].node.get_and_clear_pending_events();
5425 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5426 assert_eq!(*payment_preimage, our_payment_preimage);
5427 assert_eq!(*payment_hash, duplicate_payment_hash);
5429 _ => panic!("Unexpected event"),
5434 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5435 let chanmon_cfgs = create_chanmon_cfgs(2);
5436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5440 // Create some initial channels
5441 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5443 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5444 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5445 assert_eq!(local_txn.len(), 1);
5446 assert_eq!(local_txn[0].input.len(), 1);
5447 check_spends!(local_txn[0], chan_1.3);
5449 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5450 nodes[1].node.claim_funds(payment_preimage);
5451 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5452 check_added_monitors!(nodes[1], 1);
5454 mine_transaction(&nodes[1], &local_txn[0]);
5455 check_added_monitors!(nodes[1], 1);
5456 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5457 let events = nodes[1].node.get_and_clear_pending_msg_events();
5459 MessageSendEvent::UpdateHTLCs { .. } => {},
5460 _ => panic!("Unexpected event"),
5463 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5464 _ => panic!("Unexepected event"),
5467 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5468 assert_eq!(node_txn.len(), 3);
5469 assert_eq!(node_txn[0], node_txn[2]);
5470 assert_eq!(node_txn[1], local_txn[0]);
5471 assert_eq!(node_txn[0].input.len(), 1);
5472 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5473 check_spends!(node_txn[0], local_txn[0]);
5477 mine_transaction(&nodes[1], &node_tx);
5478 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5480 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5481 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5482 assert_eq!(spend_txn.len(), 1);
5483 assert_eq!(spend_txn[0].input.len(), 1);
5484 check_spends!(spend_txn[0], node_tx);
5485 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5488 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5489 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5490 // unrevoked commitment transaction.
5491 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5492 // a remote RAA before they could be failed backwards (and combinations thereof).
5493 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5494 // use the same payment hashes.
5495 // Thus, we use a six-node network:
5500 // And test where C fails back to A/B when D announces its latest commitment transaction
5501 let chanmon_cfgs = create_chanmon_cfgs(6);
5502 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5503 // When this test was written, the default base fee floated based on the HTLC count.
5504 // It is now fixed, so we simply set the fee to the expected value here.
5505 let mut config = test_default_channel_config();
5506 config.channel_config.forwarding_fee_base_msat = 196;
5507 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5508 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5509 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5511 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5512 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5513 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5514 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5515 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5517 // Rebalance and check output sanity...
5518 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5519 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5520 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5522 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5524 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
5526 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
5527 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5529 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
5531 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
5533 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5535 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5536 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5538 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());
5540 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());
5543 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5545 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5546 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
5549 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
5551 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5552 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());
5554 // Double-check that six of the new HTLC were added
5555 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5556 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5557 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5558 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5560 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5561 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5562 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5563 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5564 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5565 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5566 check_added_monitors!(nodes[4], 0);
5567 expect_pending_htlcs_forwardable!(nodes[4]);
5568 check_added_monitors!(nodes[4], 1);
5570 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5571 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5572 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5573 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5574 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5575 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5577 // Fail 3rd below-dust and 7th above-dust HTLCs
5578 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5579 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5580 check_added_monitors!(nodes[5], 0);
5581 expect_pending_htlcs_forwardable!(nodes[5]);
5582 check_added_monitors!(nodes[5], 1);
5584 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5585 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5586 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5587 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5589 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5591 expect_pending_htlcs_forwardable!(nodes[3]);
5592 check_added_monitors!(nodes[3], 1);
5593 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5594 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5595 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5596 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5597 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5598 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5599 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5600 if deliver_last_raa {
5601 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5603 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5606 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5607 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5608 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5609 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5611 // We now broadcast the latest commitment transaction, which *should* result in failures for
5612 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5613 // the non-broadcast above-dust HTLCs.
5615 // Alternatively, we may broadcast the previous commitment transaction, which should only
5616 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5617 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5619 if announce_latest {
5620 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5622 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5624 let events = nodes[2].node.get_and_clear_pending_events();
5625 let close_event = if deliver_last_raa {
5626 assert_eq!(events.len(), 2);
5629 assert_eq!(events.len(), 1);
5633 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5634 _ => panic!("Unexpected event"),
5637 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5638 check_closed_broadcast!(nodes[2], true);
5639 if deliver_last_raa {
5640 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5642 expect_pending_htlcs_forwardable!(nodes[2]);
5644 check_added_monitors!(nodes[2], 3);
5646 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5647 assert_eq!(cs_msgs.len(), 2);
5648 let mut a_done = false;
5649 for msg in cs_msgs {
5651 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5652 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5653 // should be failed-backwards here.
5654 let target = if *node_id == nodes[0].node.get_our_node_id() {
5655 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5656 for htlc in &updates.update_fail_htlcs {
5657 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 });
5659 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5664 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5665 for htlc in &updates.update_fail_htlcs {
5666 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5668 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5669 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5672 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5673 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5674 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5675 if announce_latest {
5676 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5677 if *node_id == nodes[0].node.get_our_node_id() {
5678 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5681 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5683 _ => panic!("Unexpected event"),
5687 let as_events = nodes[0].node.get_and_clear_pending_events();
5688 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5689 let mut as_failds = HashSet::new();
5690 let mut as_updates = 0;
5691 for event in as_events.iter() {
5692 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5693 assert!(as_failds.insert(*payment_hash));
5694 if *payment_hash != payment_hash_2 {
5695 assert_eq!(*rejected_by_dest, deliver_last_raa);
5697 assert!(!rejected_by_dest);
5699 if network_update.is_some() {
5702 } else { panic!("Unexpected event"); }
5704 assert!(as_failds.contains(&payment_hash_1));
5705 assert!(as_failds.contains(&payment_hash_2));
5706 if announce_latest {
5707 assert!(as_failds.contains(&payment_hash_3));
5708 assert!(as_failds.contains(&payment_hash_5));
5710 assert!(as_failds.contains(&payment_hash_6));
5712 let bs_events = nodes[1].node.get_and_clear_pending_events();
5713 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5714 let mut bs_failds = HashSet::new();
5715 let mut bs_updates = 0;
5716 for event in bs_events.iter() {
5717 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5718 assert!(bs_failds.insert(*payment_hash));
5719 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5720 assert_eq!(*rejected_by_dest, deliver_last_raa);
5722 assert!(!rejected_by_dest);
5724 if network_update.is_some() {
5727 } else { panic!("Unexpected event"); }
5729 assert!(bs_failds.contains(&payment_hash_1));
5730 assert!(bs_failds.contains(&payment_hash_2));
5731 if announce_latest {
5732 assert!(bs_failds.contains(&payment_hash_4));
5734 assert!(bs_failds.contains(&payment_hash_5));
5736 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5737 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5738 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5739 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5740 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5741 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5745 fn test_fail_backwards_latest_remote_announce_a() {
5746 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5750 fn test_fail_backwards_latest_remote_announce_b() {
5751 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5755 fn test_fail_backwards_previous_remote_announce() {
5756 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5757 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5758 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5762 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5763 let chanmon_cfgs = create_chanmon_cfgs(2);
5764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5766 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5768 // Create some initial channels
5769 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5771 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5772 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5773 assert_eq!(local_txn[0].input.len(), 1);
5774 check_spends!(local_txn[0], chan_1.3);
5776 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5777 mine_transaction(&nodes[0], &local_txn[0]);
5778 check_closed_broadcast!(nodes[0], true);
5779 check_added_monitors!(nodes[0], 1);
5780 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5781 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5783 let htlc_timeout = {
5784 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5785 assert_eq!(node_txn.len(), 2);
5786 check_spends!(node_txn[0], chan_1.3);
5787 assert_eq!(node_txn[1].input.len(), 1);
5788 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5789 check_spends!(node_txn[1], local_txn[0]);
5793 mine_transaction(&nodes[0], &htlc_timeout);
5794 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5795 expect_payment_failed!(nodes[0], our_payment_hash, true);
5797 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5798 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5799 assert_eq!(spend_txn.len(), 3);
5800 check_spends!(spend_txn[0], local_txn[0]);
5801 assert_eq!(spend_txn[1].input.len(), 1);
5802 check_spends!(spend_txn[1], htlc_timeout);
5803 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5804 assert_eq!(spend_txn[2].input.len(), 2);
5805 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5806 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5807 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5811 fn test_key_derivation_params() {
5812 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5813 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5814 // let us re-derive the channel key set to then derive a delayed_payment_key.
5816 let chanmon_cfgs = create_chanmon_cfgs(3);
5818 // We manually create the node configuration to backup the seed.
5819 let seed = [42; 32];
5820 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5821 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);
5822 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5823 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() };
5824 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5825 node_cfgs.remove(0);
5826 node_cfgs.insert(0, node);
5828 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5829 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5831 // Create some initial channels
5832 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5834 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5835 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5836 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5838 // Ensure all nodes are at the same height
5839 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5840 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5841 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5842 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5844 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5845 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5846 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5847 assert_eq!(local_txn_1[0].input.len(), 1);
5848 check_spends!(local_txn_1[0], chan_1.3);
5850 // We check funding pubkey are unique
5851 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]));
5852 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]));
5853 if from_0_funding_key_0 == from_1_funding_key_0
5854 || from_0_funding_key_0 == from_1_funding_key_1
5855 || from_0_funding_key_1 == from_1_funding_key_0
5856 || from_0_funding_key_1 == from_1_funding_key_1 {
5857 panic!("Funding pubkeys aren't unique");
5860 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5861 mine_transaction(&nodes[0], &local_txn_1[0]);
5862 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5863 check_closed_broadcast!(nodes[0], true);
5864 check_added_monitors!(nodes[0], 1);
5865 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5867 let htlc_timeout = {
5868 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5869 assert_eq!(node_txn[1].input.len(), 1);
5870 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5871 check_spends!(node_txn[1], local_txn_1[0]);
5875 mine_transaction(&nodes[0], &htlc_timeout);
5876 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5877 expect_payment_failed!(nodes[0], our_payment_hash, true);
5879 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5880 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5881 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5882 assert_eq!(spend_txn.len(), 3);
5883 check_spends!(spend_txn[0], local_txn_1[0]);
5884 assert_eq!(spend_txn[1].input.len(), 1);
5885 check_spends!(spend_txn[1], htlc_timeout);
5886 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5887 assert_eq!(spend_txn[2].input.len(), 2);
5888 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5889 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5890 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5894 fn test_static_output_closing_tx() {
5895 let chanmon_cfgs = create_chanmon_cfgs(2);
5896 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5897 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5898 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5900 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5902 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5903 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5905 mine_transaction(&nodes[0], &closing_tx);
5906 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5907 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5909 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5910 assert_eq!(spend_txn.len(), 1);
5911 check_spends!(spend_txn[0], closing_tx);
5913 mine_transaction(&nodes[1], &closing_tx);
5914 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5915 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5917 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5918 assert_eq!(spend_txn.len(), 1);
5919 check_spends!(spend_txn[0], closing_tx);
5922 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5923 let chanmon_cfgs = create_chanmon_cfgs(2);
5924 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5925 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5926 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5927 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5929 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5931 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5932 // present in B's local commitment transaction, but none of A's commitment transactions.
5933 nodes[1].node.claim_funds(payment_preimage);
5934 check_added_monitors!(nodes[1], 1);
5935 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5937 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5938 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5939 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5941 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5942 check_added_monitors!(nodes[0], 1);
5943 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5944 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5945 check_added_monitors!(nodes[1], 1);
5947 let starting_block = nodes[1].best_block_info();
5948 let mut block = Block {
5949 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5952 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5953 connect_block(&nodes[1], &block);
5954 block.header.prev_blockhash = block.block_hash();
5956 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5957 check_closed_broadcast!(nodes[1], true);
5958 check_added_monitors!(nodes[1], 1);
5959 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5962 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5963 let chanmon_cfgs = create_chanmon_cfgs(2);
5964 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5965 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5966 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5967 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5969 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5970 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5971 check_added_monitors!(nodes[0], 1);
5973 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5975 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5976 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5977 // to "time out" the HTLC.
5979 let starting_block = nodes[1].best_block_info();
5980 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5982 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5983 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5984 header.prev_blockhash = header.block_hash();
5986 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5987 check_closed_broadcast!(nodes[0], true);
5988 check_added_monitors!(nodes[0], 1);
5989 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5992 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5993 let chanmon_cfgs = create_chanmon_cfgs(3);
5994 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5995 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5996 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5997 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5999 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6000 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6001 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6002 // actually revoked.
6003 let htlc_value = if use_dust { 50000 } else { 3000000 };
6004 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6005 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6006 expect_pending_htlcs_forwardable!(nodes[1]);
6007 check_added_monitors!(nodes[1], 1);
6009 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6010 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6011 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6012 check_added_monitors!(nodes[0], 1);
6013 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6014 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6015 check_added_monitors!(nodes[1], 1);
6016 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6017 check_added_monitors!(nodes[1], 1);
6018 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6020 if check_revoke_no_close {
6021 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6022 check_added_monitors!(nodes[0], 1);
6025 let starting_block = nodes[1].best_block_info();
6026 let mut block = Block {
6027 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6030 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6031 connect_block(&nodes[0], &block);
6032 block.header.prev_blockhash = block.block_hash();
6034 if !check_revoke_no_close {
6035 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6036 check_closed_broadcast!(nodes[0], true);
6037 check_added_monitors!(nodes[0], 1);
6038 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6040 let events = nodes[0].node.get_and_clear_pending_events();
6041 assert_eq!(events.len(), 2);
6042 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6043 assert_eq!(*payment_hash, our_payment_hash);
6044 } else { panic!("Unexpected event"); }
6045 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6046 assert_eq!(*payment_hash, our_payment_hash);
6047 } else { panic!("Unexpected event"); }
6051 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6052 // There are only a few cases to test here:
6053 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6054 // broadcastable commitment transactions result in channel closure,
6055 // * its included in an unrevoked-but-previous remote commitment transaction,
6056 // * its included in the latest remote or local commitment transactions.
6057 // We test each of the three possible commitment transactions individually and use both dust and
6059 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6060 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6061 // tested for at least one of the cases in other tests.
6063 fn htlc_claim_single_commitment_only_a() {
6064 do_htlc_claim_local_commitment_only(true);
6065 do_htlc_claim_local_commitment_only(false);
6067 do_htlc_claim_current_remote_commitment_only(true);
6068 do_htlc_claim_current_remote_commitment_only(false);
6072 fn htlc_claim_single_commitment_only_b() {
6073 do_htlc_claim_previous_remote_commitment_only(true, false);
6074 do_htlc_claim_previous_remote_commitment_only(false, false);
6075 do_htlc_claim_previous_remote_commitment_only(true, true);
6076 do_htlc_claim_previous_remote_commitment_only(false, true);
6081 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6082 let chanmon_cfgs = create_chanmon_cfgs(2);
6083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6086 // Force duplicate randomness for every get-random call
6087 for node in nodes.iter() {
6088 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6091 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6092 let channel_value_satoshis=10000;
6093 let push_msat=10001;
6094 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6095 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6096 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6097 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6099 // Create a second channel with the same random values. This used to panic due to a colliding
6100 // channel_id, but now panics due to a colliding outbound SCID alias.
6101 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6105 fn bolt2_open_channel_sending_node_checks_part2() {
6106 let chanmon_cfgs = create_chanmon_cfgs(2);
6107 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6108 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6109 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6111 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6112 let channel_value_satoshis=2^24;
6113 let push_msat=10001;
6114 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6116 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6117 let channel_value_satoshis=10000;
6118 // Test when push_msat is equal to 1000 * funding_satoshis.
6119 let push_msat=1000*channel_value_satoshis+1;
6120 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6122 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6123 let channel_value_satoshis=10000;
6124 let push_msat=10001;
6125 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
6126 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6127 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6129 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6130 // 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
6131 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6133 // 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.
6134 assert!(BREAKDOWN_TIMEOUT>0);
6135 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6137 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6138 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6139 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6141 // 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.
6142 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6143 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6144 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6145 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6146 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6150 fn bolt2_open_channel_sane_dust_limit() {
6151 let chanmon_cfgs = create_chanmon_cfgs(2);
6152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6156 let channel_value_satoshis=1000000;
6157 let push_msat=10001;
6158 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6159 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6160 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6161 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6163 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6164 let events = nodes[1].node.get_and_clear_pending_msg_events();
6165 let err_msg = match events[0] {
6166 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6169 _ => panic!("Unexpected event"),
6171 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6174 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6175 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6176 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6177 // is no longer affordable once it's freed.
6179 fn test_fail_holding_cell_htlc_upon_free() {
6180 let chanmon_cfgs = create_chanmon_cfgs(2);
6181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6184 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6186 // First nodes[0] generates an update_fee, setting the channel's
6187 // pending_update_fee.
6189 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6190 *feerate_lock += 20;
6192 nodes[0].node.timer_tick_occurred();
6193 check_added_monitors!(nodes[0], 1);
6195 let events = nodes[0].node.get_and_clear_pending_msg_events();
6196 assert_eq!(events.len(), 1);
6197 let (update_msg, commitment_signed) = match events[0] {
6198 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6199 (update_fee.as_ref(), commitment_signed)
6201 _ => panic!("Unexpected event"),
6204 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6206 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6207 let channel_reserve = chan_stat.channel_reserve_msat;
6208 let feerate = get_feerate!(nodes[0], chan.2);
6209 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6211 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6212 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6213 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6215 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6216 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6217 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6218 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6220 // Flush the pending fee update.
6221 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6222 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6223 check_added_monitors!(nodes[1], 1);
6224 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6225 check_added_monitors!(nodes[0], 1);
6227 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6228 // HTLC, but now that the fee has been raised the payment will now fail, causing
6229 // us to surface its failure to the user.
6230 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6231 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6232 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);
6233 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 {}",
6234 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6235 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6237 // Check that the payment failed to be sent out.
6238 let events = nodes[0].node.get_and_clear_pending_events();
6239 assert_eq!(events.len(), 1);
6241 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6242 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6243 assert_eq!(our_payment_hash.clone(), *payment_hash);
6244 assert_eq!(*rejected_by_dest, false);
6245 assert_eq!(*all_paths_failed, true);
6246 assert_eq!(*network_update, None);
6247 assert_eq!(*short_channel_id, None);
6248 assert_eq!(*error_code, None);
6249 assert_eq!(*error_data, None);
6251 _ => panic!("Unexpected event"),
6255 // Test that if multiple HTLCs are released from the holding cell and one is
6256 // valid but the other is no longer valid upon release, the valid HTLC can be
6257 // successfully completed while the other one fails as expected.
6259 fn test_free_and_fail_holding_cell_htlcs() {
6260 let chanmon_cfgs = create_chanmon_cfgs(2);
6261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6263 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6264 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6266 // First nodes[0] generates an update_fee, setting the channel's
6267 // pending_update_fee.
6269 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6270 *feerate_lock += 200;
6272 nodes[0].node.timer_tick_occurred();
6273 check_added_monitors!(nodes[0], 1);
6275 let events = nodes[0].node.get_and_clear_pending_msg_events();
6276 assert_eq!(events.len(), 1);
6277 let (update_msg, commitment_signed) = match events[0] {
6278 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6279 (update_fee.as_ref(), commitment_signed)
6281 _ => panic!("Unexpected event"),
6284 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6286 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6287 let channel_reserve = chan_stat.channel_reserve_msat;
6288 let feerate = get_feerate!(nodes[0], chan.2);
6289 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6291 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6293 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6294 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6295 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6297 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6298 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6299 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6300 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6301 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6302 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6303 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6305 // Flush the pending fee update.
6306 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6307 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6308 check_added_monitors!(nodes[1], 1);
6309 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6310 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6311 check_added_monitors!(nodes[0], 2);
6313 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6314 // but now that the fee has been raised the second payment will now fail, causing us
6315 // to surface its failure to the user. The first payment should succeed.
6316 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6317 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6318 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);
6319 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 {}",
6320 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6321 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6323 // Check that the second payment failed to be sent out.
6324 let events = nodes[0].node.get_and_clear_pending_events();
6325 assert_eq!(events.len(), 1);
6327 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6328 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6329 assert_eq!(payment_hash_2.clone(), *payment_hash);
6330 assert_eq!(*rejected_by_dest, false);
6331 assert_eq!(*all_paths_failed, true);
6332 assert_eq!(*network_update, None);
6333 assert_eq!(*short_channel_id, None);
6334 assert_eq!(*error_code, None);
6335 assert_eq!(*error_data, None);
6337 _ => panic!("Unexpected event"),
6340 // Complete the first payment and the RAA from the fee update.
6341 let (payment_event, send_raa_event) = {
6342 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6343 assert_eq!(msgs.len(), 2);
6344 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6346 let raa = match send_raa_event {
6347 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6348 _ => panic!("Unexpected event"),
6350 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6351 check_added_monitors!(nodes[1], 1);
6352 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6353 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6354 let events = nodes[1].node.get_and_clear_pending_events();
6355 assert_eq!(events.len(), 1);
6357 Event::PendingHTLCsForwardable { .. } => {},
6358 _ => panic!("Unexpected event"),
6360 nodes[1].node.process_pending_htlc_forwards();
6361 let events = nodes[1].node.get_and_clear_pending_events();
6362 assert_eq!(events.len(), 1);
6364 Event::PaymentReceived { .. } => {},
6365 _ => panic!("Unexpected event"),
6367 nodes[1].node.claim_funds(payment_preimage_1);
6368 check_added_monitors!(nodes[1], 1);
6369 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6371 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6372 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6373 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6374 expect_payment_sent!(nodes[0], payment_preimage_1);
6377 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6378 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6379 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6382 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6383 let chanmon_cfgs = create_chanmon_cfgs(3);
6384 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6385 // When this test was written, the default base fee floated based on the HTLC count.
6386 // It is now fixed, so we simply set the fee to the expected value here.
6387 let mut config = test_default_channel_config();
6388 config.channel_config.forwarding_fee_base_msat = 196;
6389 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6390 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6391 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6392 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6394 // First nodes[1] generates an update_fee, setting the channel's
6395 // pending_update_fee.
6397 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6398 *feerate_lock += 20;
6400 nodes[1].node.timer_tick_occurred();
6401 check_added_monitors!(nodes[1], 1);
6403 let events = nodes[1].node.get_and_clear_pending_msg_events();
6404 assert_eq!(events.len(), 1);
6405 let (update_msg, commitment_signed) = match events[0] {
6406 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6407 (update_fee.as_ref(), commitment_signed)
6409 _ => panic!("Unexpected event"),
6412 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6414 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6415 let channel_reserve = chan_stat.channel_reserve_msat;
6416 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6417 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6419 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6421 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6422 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6423 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6424 let payment_event = {
6425 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6426 check_added_monitors!(nodes[0], 1);
6428 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6429 assert_eq!(events.len(), 1);
6431 SendEvent::from_event(events.remove(0))
6433 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6434 check_added_monitors!(nodes[1], 0);
6435 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6436 expect_pending_htlcs_forwardable!(nodes[1]);
6438 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6439 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6441 // Flush the pending fee update.
6442 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6443 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6444 check_added_monitors!(nodes[2], 1);
6445 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6446 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6447 check_added_monitors!(nodes[1], 2);
6449 // A final RAA message is generated to finalize the fee update.
6450 let events = nodes[1].node.get_and_clear_pending_msg_events();
6451 assert_eq!(events.len(), 1);
6453 let raa_msg = match &events[0] {
6454 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6457 _ => panic!("Unexpected event"),
6460 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6461 check_added_monitors!(nodes[2], 1);
6462 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6464 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6465 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6466 assert_eq!(process_htlc_forwards_event.len(), 1);
6467 match &process_htlc_forwards_event[0] {
6468 &Event::PendingHTLCsForwardable { .. } => {},
6469 _ => panic!("Unexpected event"),
6472 // In response, we call ChannelManager's process_pending_htlc_forwards
6473 nodes[1].node.process_pending_htlc_forwards();
6474 check_added_monitors!(nodes[1], 1);
6476 // This causes the HTLC to be failed backwards.
6477 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6478 assert_eq!(fail_event.len(), 1);
6479 let (fail_msg, commitment_signed) = match &fail_event[0] {
6480 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6481 assert_eq!(updates.update_add_htlcs.len(), 0);
6482 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6483 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6484 assert_eq!(updates.update_fail_htlcs.len(), 1);
6485 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6487 _ => panic!("Unexpected event"),
6490 // Pass the failure messages back to nodes[0].
6491 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6492 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6494 // Complete the HTLC failure+removal process.
6495 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6496 check_added_monitors!(nodes[0], 1);
6497 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6498 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6499 check_added_monitors!(nodes[1], 2);
6500 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6501 assert_eq!(final_raa_event.len(), 1);
6502 let raa = match &final_raa_event[0] {
6503 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6504 _ => panic!("Unexpected event"),
6506 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6507 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6508 check_added_monitors!(nodes[0], 1);
6511 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6512 // 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.
6513 //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.
6516 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6517 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6518 let chanmon_cfgs = create_chanmon_cfgs(2);
6519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6521 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6522 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6524 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6525 route.paths[0][0].fee_msat = 100;
6527 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6528 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6529 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6530 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6534 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6535 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6536 let chanmon_cfgs = create_chanmon_cfgs(2);
6537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6539 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6540 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6542 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6543 route.paths[0][0].fee_msat = 0;
6544 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6545 assert_eq!(err, "Cannot send 0-msat HTLC"));
6547 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6548 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6552 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6553 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6554 let chanmon_cfgs = create_chanmon_cfgs(2);
6555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6557 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6558 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6560 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6561 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6562 check_added_monitors!(nodes[0], 1);
6563 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6564 updates.update_add_htlcs[0].amount_msat = 0;
6566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6567 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6568 check_closed_broadcast!(nodes[1], true).unwrap();
6569 check_added_monitors!(nodes[1], 1);
6570 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6574 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6575 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6576 //It is enforced when constructing a route.
6577 let chanmon_cfgs = create_chanmon_cfgs(2);
6578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6580 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6581 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6583 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6584 .with_features(InvoiceFeatures::known());
6585 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6586 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6587 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6588 assert_eq!(err, &"Channel CLTV overflowed?"));
6592 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6593 //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.
6594 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6595 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6596 let chanmon_cfgs = create_chanmon_cfgs(2);
6597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6599 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6600 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6601 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6603 for i in 0..max_accepted_htlcs {
6604 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6605 let payment_event = {
6606 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6607 check_added_monitors!(nodes[0], 1);
6609 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6610 assert_eq!(events.len(), 1);
6611 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6612 assert_eq!(htlcs[0].htlc_id, i);
6616 SendEvent::from_event(events.remove(0))
6618 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6619 check_added_monitors!(nodes[1], 0);
6620 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6622 expect_pending_htlcs_forwardable!(nodes[1]);
6623 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6625 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6626 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6627 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6629 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6630 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6634 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6635 //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.
6636 let chanmon_cfgs = create_chanmon_cfgs(2);
6637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6640 let channel_value = 100000;
6641 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6642 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6644 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6646 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6647 // Manually create a route over our max in flight (which our router normally automatically
6649 route.paths[0][0].fee_msat = max_in_flight + 1;
6650 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6651 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)));
6653 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6654 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);
6656 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6659 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6661 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6662 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6663 let chanmon_cfgs = create_chanmon_cfgs(2);
6664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6666 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6667 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6668 let htlc_minimum_msat: u64;
6670 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6671 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6672 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6675 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6676 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6677 check_added_monitors!(nodes[0], 1);
6678 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6679 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6680 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6681 assert!(nodes[1].node.list_channels().is_empty());
6682 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6683 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()));
6684 check_added_monitors!(nodes[1], 1);
6685 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6689 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6690 //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
6691 let chanmon_cfgs = create_chanmon_cfgs(2);
6692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6694 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6695 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6697 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6698 let channel_reserve = chan_stat.channel_reserve_msat;
6699 let feerate = get_feerate!(nodes[0], chan.2);
6700 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6701 // The 2* and +1 are for the fee spike reserve.
6702 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6704 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6705 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6706 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6707 check_added_monitors!(nodes[0], 1);
6708 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6710 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6711 // at this time channel-initiatee receivers are not required to enforce that senders
6712 // respect the fee_spike_reserve.
6713 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6714 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6716 assert!(nodes[1].node.list_channels().is_empty());
6717 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6718 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6719 check_added_monitors!(nodes[1], 1);
6720 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6724 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6725 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6726 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6727 let chanmon_cfgs = create_chanmon_cfgs(2);
6728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6730 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6731 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6733 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6734 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6735 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6736 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6737 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6738 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6740 let mut msg = msgs::UpdateAddHTLC {
6744 payment_hash: our_payment_hash,
6745 cltv_expiry: htlc_cltv,
6746 onion_routing_packet: onion_packet.clone(),
6749 for i in 0..super::channel::OUR_MAX_HTLCS {
6750 msg.htlc_id = i as u64;
6751 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6753 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6756 assert!(nodes[1].node.list_channels().is_empty());
6757 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6758 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6759 check_added_monitors!(nodes[1], 1);
6760 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6764 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6765 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6766 let chanmon_cfgs = create_chanmon_cfgs(2);
6767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6769 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6770 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6772 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6773 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6774 check_added_monitors!(nodes[0], 1);
6775 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6776 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6777 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6779 assert!(nodes[1].node.list_channels().is_empty());
6780 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6781 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6782 check_added_monitors!(nodes[1], 1);
6783 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6787 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6788 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6789 let chanmon_cfgs = create_chanmon_cfgs(2);
6790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6794 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6795 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6796 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6797 check_added_monitors!(nodes[0], 1);
6798 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6799 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6800 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6802 assert!(nodes[1].node.list_channels().is_empty());
6803 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6804 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6805 check_added_monitors!(nodes[1], 1);
6806 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6810 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6811 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6812 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6813 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6814 let chanmon_cfgs = create_chanmon_cfgs(2);
6815 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6816 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6817 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6819 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6820 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6821 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6822 check_added_monitors!(nodes[0], 1);
6823 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6824 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6826 //Disconnect and Reconnect
6827 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6828 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6829 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6830 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6831 assert_eq!(reestablish_1.len(), 1);
6832 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6833 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6834 assert_eq!(reestablish_2.len(), 1);
6835 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6836 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6837 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6838 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6841 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6842 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6843 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6844 check_added_monitors!(nodes[1], 1);
6845 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6847 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6849 assert!(nodes[1].node.list_channels().is_empty());
6850 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6851 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6852 check_added_monitors!(nodes[1], 1);
6853 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6857 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6858 //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.
6860 let chanmon_cfgs = create_chanmon_cfgs(2);
6861 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6862 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6863 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6864 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6865 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6866 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6868 check_added_monitors!(nodes[0], 1);
6869 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6870 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6872 let update_msg = msgs::UpdateFulfillHTLC{
6875 payment_preimage: our_payment_preimage,
6878 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6880 assert!(nodes[0].node.list_channels().is_empty());
6881 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6882 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()));
6883 check_added_monitors!(nodes[0], 1);
6884 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6888 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6889 //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.
6891 let chanmon_cfgs = create_chanmon_cfgs(2);
6892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6894 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6895 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6897 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6898 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6899 check_added_monitors!(nodes[0], 1);
6900 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6901 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6903 let update_msg = msgs::UpdateFailHTLC{
6906 reason: msgs::OnionErrorPacket { data: Vec::new()},
6909 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6911 assert!(nodes[0].node.list_channels().is_empty());
6912 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6913 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()));
6914 check_added_monitors!(nodes[0], 1);
6915 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6919 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6920 //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.
6922 let chanmon_cfgs = create_chanmon_cfgs(2);
6923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6925 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6926 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6928 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6929 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6930 check_added_monitors!(nodes[0], 1);
6931 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6932 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6933 let update_msg = msgs::UpdateFailMalformedHTLC{
6936 sha256_of_onion: [1; 32],
6937 failure_code: 0x8000,
6940 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6942 assert!(nodes[0].node.list_channels().is_empty());
6943 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6944 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()));
6945 check_added_monitors!(nodes[0], 1);
6946 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6950 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6951 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6953 let chanmon_cfgs = create_chanmon_cfgs(2);
6954 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6955 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6956 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6957 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6959 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6961 nodes[1].node.claim_funds(our_payment_preimage);
6962 check_added_monitors!(nodes[1], 1);
6963 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6965 let events = nodes[1].node.get_and_clear_pending_msg_events();
6966 assert_eq!(events.len(), 1);
6967 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6969 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, .. } } => {
6970 assert!(update_add_htlcs.is_empty());
6971 assert_eq!(update_fulfill_htlcs.len(), 1);
6972 assert!(update_fail_htlcs.is_empty());
6973 assert!(update_fail_malformed_htlcs.is_empty());
6974 assert!(update_fee.is_none());
6975 update_fulfill_htlcs[0].clone()
6977 _ => panic!("Unexpected event"),
6981 update_fulfill_msg.htlc_id = 1;
6983 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6985 assert!(nodes[0].node.list_channels().is_empty());
6986 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6987 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6988 check_added_monitors!(nodes[0], 1);
6989 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6993 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6994 //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.
6996 let chanmon_cfgs = create_chanmon_cfgs(2);
6997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7000 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7002 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7004 nodes[1].node.claim_funds(our_payment_preimage);
7005 check_added_monitors!(nodes[1], 1);
7006 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7008 let events = nodes[1].node.get_and_clear_pending_msg_events();
7009 assert_eq!(events.len(), 1);
7010 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7012 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, .. } } => {
7013 assert!(update_add_htlcs.is_empty());
7014 assert_eq!(update_fulfill_htlcs.len(), 1);
7015 assert!(update_fail_htlcs.is_empty());
7016 assert!(update_fail_malformed_htlcs.is_empty());
7017 assert!(update_fee.is_none());
7018 update_fulfill_htlcs[0].clone()
7020 _ => panic!("Unexpected event"),
7024 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7026 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7028 assert!(nodes[0].node.list_channels().is_empty());
7029 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7030 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7031 check_added_monitors!(nodes[0], 1);
7032 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7036 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7037 //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.
7039 let chanmon_cfgs = create_chanmon_cfgs(2);
7040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7042 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7043 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7045 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7046 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7047 check_added_monitors!(nodes[0], 1);
7049 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7050 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7052 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7053 check_added_monitors!(nodes[1], 0);
7054 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7056 let events = nodes[1].node.get_and_clear_pending_msg_events();
7058 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7060 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, .. } } => {
7061 assert!(update_add_htlcs.is_empty());
7062 assert!(update_fulfill_htlcs.is_empty());
7063 assert!(update_fail_htlcs.is_empty());
7064 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7065 assert!(update_fee.is_none());
7066 update_fail_malformed_htlcs[0].clone()
7068 _ => panic!("Unexpected event"),
7071 update_msg.failure_code &= !0x8000;
7072 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7074 assert!(nodes[0].node.list_channels().is_empty());
7075 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7076 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7077 check_added_monitors!(nodes[0], 1);
7078 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7082 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7083 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7084 // * 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.
7086 let chanmon_cfgs = create_chanmon_cfgs(3);
7087 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7088 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7089 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7090 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7091 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7093 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7096 let mut payment_event = {
7097 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7098 check_added_monitors!(nodes[0], 1);
7099 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7100 assert_eq!(events.len(), 1);
7101 SendEvent::from_event(events.remove(0))
7103 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7104 check_added_monitors!(nodes[1], 0);
7105 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7106 expect_pending_htlcs_forwardable!(nodes[1]);
7107 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7108 assert_eq!(events_2.len(), 1);
7109 check_added_monitors!(nodes[1], 1);
7110 payment_event = SendEvent::from_event(events_2.remove(0));
7111 assert_eq!(payment_event.msgs.len(), 1);
7114 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7115 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7116 check_added_monitors!(nodes[2], 0);
7117 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7119 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7120 assert_eq!(events_3.len(), 1);
7121 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7123 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 } } => {
7124 assert!(update_add_htlcs.is_empty());
7125 assert!(update_fulfill_htlcs.is_empty());
7126 assert!(update_fail_htlcs.is_empty());
7127 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7128 assert!(update_fee.is_none());
7129 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7131 _ => panic!("Unexpected event"),
7135 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7137 check_added_monitors!(nodes[1], 0);
7138 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7139 expect_pending_htlcs_forwardable!(nodes[1]);
7140 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7141 assert_eq!(events_4.len(), 1);
7143 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
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, .. } } => {
7146 assert!(update_add_htlcs.is_empty());
7147 assert!(update_fulfill_htlcs.is_empty());
7148 assert_eq!(update_fail_htlcs.len(), 1);
7149 assert!(update_fail_malformed_htlcs.is_empty());
7150 assert!(update_fee.is_none());
7152 _ => panic!("Unexpected event"),
7155 check_added_monitors!(nodes[1], 1);
7158 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7159 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7160 // 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
7161 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7163 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7164 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7168 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7170 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7172 // We route 2 dust-HTLCs between A and B
7173 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7174 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7175 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7177 // Cache one local commitment tx as previous
7178 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7180 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7181 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7182 check_added_monitors!(nodes[1], 0);
7183 expect_pending_htlcs_forwardable!(nodes[1]);
7184 check_added_monitors!(nodes[1], 1);
7186 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7187 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7188 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7189 check_added_monitors!(nodes[0], 1);
7191 // Cache one local commitment tx as lastest
7192 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7194 let events = nodes[0].node.get_and_clear_pending_msg_events();
7196 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7197 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7199 _ => panic!("Unexpected event"),
7202 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7203 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7205 _ => panic!("Unexpected event"),
7208 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7209 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7210 if announce_latest {
7211 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7213 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7216 check_closed_broadcast!(nodes[0], true);
7217 check_added_monitors!(nodes[0], 1);
7218 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7220 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7221 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7222 let events = nodes[0].node.get_and_clear_pending_events();
7223 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7224 assert_eq!(events.len(), 2);
7225 let mut first_failed = false;
7226 for event in events {
7228 Event::PaymentPathFailed { payment_hash, .. } => {
7229 if payment_hash == payment_hash_1 {
7230 assert!(!first_failed);
7231 first_failed = true;
7233 assert_eq!(payment_hash, payment_hash_2);
7236 _ => panic!("Unexpected event"),
7242 fn test_failure_delay_dust_htlc_local_commitment() {
7243 do_test_failure_delay_dust_htlc_local_commitment(true);
7244 do_test_failure_delay_dust_htlc_local_commitment(false);
7247 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7248 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7249 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7250 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7251 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7252 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7253 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7255 let chanmon_cfgs = create_chanmon_cfgs(3);
7256 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7257 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7258 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7259 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7261 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7263 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7264 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7266 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7267 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7269 // We revoked bs_commitment_tx
7271 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7272 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7275 let mut timeout_tx = Vec::new();
7277 // We fail dust-HTLC 1 by broadcast of local commitment tx
7278 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7279 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7280 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7281 expect_payment_failed!(nodes[0], dust_hash, true);
7283 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7284 check_closed_broadcast!(nodes[0], true);
7285 check_added_monitors!(nodes[0], 1);
7286 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7287 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7288 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7289 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7290 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7291 mine_transaction(&nodes[0], &timeout_tx[0]);
7292 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7293 expect_payment_failed!(nodes[0], non_dust_hash, true);
7295 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7296 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7297 check_closed_broadcast!(nodes[0], true);
7298 check_added_monitors!(nodes[0], 1);
7299 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7300 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7302 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7303 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7304 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7305 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7306 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7307 // dust HTLC should have been failed.
7308 expect_payment_failed!(nodes[0], dust_hash, true);
7311 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7313 assert_eq!(timeout_tx[0].lock_time, 0);
7315 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7316 mine_transaction(&nodes[0], &timeout_tx[0]);
7317 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7318 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7319 expect_payment_failed!(nodes[0], non_dust_hash, true);
7324 fn test_sweep_outbound_htlc_failure_update() {
7325 do_test_sweep_outbound_htlc_failure_update(false, true);
7326 do_test_sweep_outbound_htlc_failure_update(false, false);
7327 do_test_sweep_outbound_htlc_failure_update(true, false);
7331 fn test_user_configurable_csv_delay() {
7332 // We test our channel constructors yield errors when we pass them absurd csv delay
7334 let mut low_our_to_self_config = UserConfig::default();
7335 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7336 let mut high_their_to_self_config = UserConfig::default();
7337 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7338 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7339 let chanmon_cfgs = create_chanmon_cfgs(2);
7340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7342 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7344 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7345 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7346 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7347 &low_our_to_self_config, 0, 42)
7350 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())); },
7351 _ => panic!("Unexpected event"),
7353 } else { assert!(false) }
7355 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7356 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7357 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7358 open_channel.to_self_delay = 200;
7359 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7360 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7361 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7364 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())); },
7365 _ => panic!("Unexpected event"),
7367 } else { assert!(false); }
7369 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7370 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7371 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()));
7372 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7373 accept_channel.to_self_delay = 200;
7374 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7376 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7378 &ErrorAction::SendErrorMessage { ref msg } => {
7379 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()));
7380 reason_msg = msg.data.clone();
7384 } else { panic!(); }
7385 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7387 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7388 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7389 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7390 open_channel.to_self_delay = 200;
7391 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7392 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7393 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7396 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())); },
7397 _ => panic!("Unexpected event"),
7399 } else { assert!(false); }
7402 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7403 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7404 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7405 // panic message informs the user they should force-close without broadcasting, which is tested
7406 // if `reconnect_panicing` is not set.
7412 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7413 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7414 // during signing due to revoked tx
7415 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7416 let keys_manager = &chanmon_cfgs[0].keys_manager;
7419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7421 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7423 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7425 // Cache node A state before any channel update
7426 let previous_node_state = nodes[0].node.encode();
7427 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7428 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7430 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7431 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7433 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7434 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7436 // Restore node A from previous state
7437 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7438 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7439 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7440 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7441 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7442 persister = test_utils::TestPersister::new();
7443 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7445 let mut channel_monitors = HashMap::new();
7446 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7447 <(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 {
7448 keys_manager: keys_manager,
7449 fee_estimator: &fee_estimator,
7450 chain_monitor: &monitor,
7452 tx_broadcaster: &tx_broadcaster,
7453 default_config: UserConfig::default(),
7457 nodes[0].node = &node_state_0;
7458 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7459 nodes[0].chain_monitor = &monitor;
7460 nodes[0].chain_source = &chain_source;
7462 check_added_monitors!(nodes[0], 1);
7464 if reconnect_panicing {
7465 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7466 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7468 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7470 // Check we close channel detecting A is fallen-behind
7471 // Check that we sent the warning message when we detected that A has fallen behind,
7472 // and give the possibility for A to recover from the warning.
7473 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7474 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7475 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7478 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7479 // The node B should not broadcast the transaction to force close the channel!
7480 assert!(node_txn.is_empty());
7483 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7484 // Check A panics upon seeing proof it has fallen behind.
7485 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7486 return; // By this point we should have panic'ed!
7489 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7490 check_added_monitors!(nodes[0], 1);
7491 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7493 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7494 assert_eq!(node_txn.len(), 0);
7497 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7498 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7499 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7501 &ErrorAction::SendErrorMessage { ref msg } => {
7502 assert_eq!(msg.data, "Channel force-closed");
7504 _ => panic!("Unexpected event!"),
7507 panic!("Unexpected event {:?}", msg)
7511 // after the warning message sent by B, we should not able to
7512 // use the channel, or reconnect with success to the channel.
7513 assert!(nodes[0].node.list_usable_channels().is_empty());
7514 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7515 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7516 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7518 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7519 let mut err_msgs_0 = Vec::with_capacity(1);
7520 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7521 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7523 &ErrorAction::SendErrorMessage { ref msg } => {
7524 assert_eq!(msg.data, "Failed to find corresponding channel");
7525 err_msgs_0.push(msg.clone());
7527 _ => panic!("Unexpected event!"),
7530 panic!("Unexpected event!");
7533 assert_eq!(err_msgs_0.len(), 1);
7534 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7535 assert!(nodes[1].node.list_usable_channels().is_empty());
7536 check_added_monitors!(nodes[1], 1);
7537 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7538 check_closed_broadcast!(nodes[1], false);
7543 fn test_data_loss_protect_showing_stale_state_panics() {
7544 do_test_data_loss_protect(true);
7548 fn test_force_close_without_broadcast() {
7549 do_test_data_loss_protect(false);
7553 fn test_check_htlc_underpaying() {
7554 // Send payment through A -> B but A is maliciously
7555 // sending a probe payment (i.e less than expected value0
7556 // to B, B should refuse payment.
7558 let chanmon_cfgs = create_chanmon_cfgs(2);
7559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7561 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7563 // Create some initial channels
7564 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7566 let scorer = test_utils::TestScorer::with_penalty(0);
7567 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7568 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7569 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();
7570 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7571 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7572 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7573 check_added_monitors!(nodes[0], 1);
7575 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7576 assert_eq!(events.len(), 1);
7577 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7579 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7581 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7582 // and then will wait a second random delay before failing the HTLC back:
7583 expect_pending_htlcs_forwardable!(nodes[1]);
7584 expect_pending_htlcs_forwardable!(nodes[1]);
7586 // Node 3 is expecting payment of 100_000 but received 10_000,
7587 // it should fail htlc like we didn't know the preimage.
7588 nodes[1].node.process_pending_htlc_forwards();
7590 let events = nodes[1].node.get_and_clear_pending_msg_events();
7591 assert_eq!(events.len(), 1);
7592 let (update_fail_htlc, commitment_signed) = match events[0] {
7593 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 } } => {
7594 assert!(update_add_htlcs.is_empty());
7595 assert!(update_fulfill_htlcs.is_empty());
7596 assert_eq!(update_fail_htlcs.len(), 1);
7597 assert!(update_fail_malformed_htlcs.is_empty());
7598 assert!(update_fee.is_none());
7599 (update_fail_htlcs[0].clone(), commitment_signed)
7601 _ => panic!("Unexpected event"),
7603 check_added_monitors!(nodes[1], 1);
7605 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7606 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7608 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7609 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7610 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7611 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7615 fn test_announce_disable_channels() {
7616 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7617 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7619 let chanmon_cfgs = create_chanmon_cfgs(2);
7620 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7621 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7622 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7624 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7625 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7626 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7629 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7630 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7632 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7633 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7634 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7635 assert_eq!(msg_events.len(), 3);
7636 let mut chans_disabled = HashMap::new();
7637 for e in msg_events {
7639 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7640 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7641 // Check that each channel gets updated exactly once
7642 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7643 panic!("Generated ChannelUpdate for wrong chan!");
7646 _ => panic!("Unexpected event"),
7650 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7651 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7652 assert_eq!(reestablish_1.len(), 3);
7653 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7654 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7655 assert_eq!(reestablish_2.len(), 3);
7657 // Reestablish chan_1
7658 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7659 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7661 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7662 // Reestablish chan_2
7663 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7664 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7665 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7666 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7667 // Reestablish chan_3
7668 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7669 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7670 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7671 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7673 nodes[0].node.timer_tick_occurred();
7674 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7675 nodes[0].node.timer_tick_occurred();
7676 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7677 assert_eq!(msg_events.len(), 3);
7678 for e in msg_events {
7680 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7681 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7682 match chans_disabled.remove(&msg.contents.short_channel_id) {
7683 // Each update should have a higher timestamp than the previous one, replacing
7685 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7686 None => panic!("Generated ChannelUpdate for wrong chan!"),
7689 _ => panic!("Unexpected event"),
7692 // Check that each channel gets updated exactly once
7693 assert!(chans_disabled.is_empty());
7697 fn test_bump_penalty_txn_on_revoked_commitment() {
7698 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7699 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7701 let chanmon_cfgs = create_chanmon_cfgs(2);
7702 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7703 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7704 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7706 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7708 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7709 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7710 .with_features(InvoiceFeatures::known());
7711 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7712 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7714 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7715 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7716 assert_eq!(revoked_txn[0].output.len(), 4);
7717 assert_eq!(revoked_txn[0].input.len(), 1);
7718 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7719 let revoked_txid = revoked_txn[0].txid();
7721 let mut penalty_sum = 0;
7722 for outp in revoked_txn[0].output.iter() {
7723 if outp.script_pubkey.is_v0_p2wsh() {
7724 penalty_sum += outp.value;
7728 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7729 let header_114 = connect_blocks(&nodes[1], 14);
7731 // Actually revoke tx by claiming a HTLC
7732 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7733 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7734 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7735 check_added_monitors!(nodes[1], 1);
7737 // One or more justice tx should have been broadcast, check it
7741 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7742 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7743 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7744 assert_eq!(node_txn[0].output.len(), 1);
7745 check_spends!(node_txn[0], revoked_txn[0]);
7746 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7747 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7748 penalty_1 = node_txn[0].txid();
7752 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7753 connect_blocks(&nodes[1], 15);
7754 let mut penalty_2 = penalty_1;
7755 let mut feerate_2 = 0;
7757 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7758 assert_eq!(node_txn.len(), 1);
7759 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7760 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7761 assert_eq!(node_txn[0].output.len(), 1);
7762 check_spends!(node_txn[0], revoked_txn[0]);
7763 penalty_2 = node_txn[0].txid();
7764 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7765 assert_ne!(penalty_2, penalty_1);
7766 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7767 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7768 // Verify 25% bump heuristic
7769 assert!(feerate_2 * 100 >= feerate_1 * 125);
7773 assert_ne!(feerate_2, 0);
7775 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7776 connect_blocks(&nodes[1], 1);
7778 let mut feerate_3 = 0;
7780 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7781 assert_eq!(node_txn.len(), 1);
7782 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7783 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7784 assert_eq!(node_txn[0].output.len(), 1);
7785 check_spends!(node_txn[0], revoked_txn[0]);
7786 penalty_3 = node_txn[0].txid();
7787 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7788 assert_ne!(penalty_3, penalty_2);
7789 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7790 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7791 // Verify 25% bump heuristic
7792 assert!(feerate_3 * 100 >= feerate_2 * 125);
7796 assert_ne!(feerate_3, 0);
7798 nodes[1].node.get_and_clear_pending_events();
7799 nodes[1].node.get_and_clear_pending_msg_events();
7803 fn test_bump_penalty_txn_on_revoked_htlcs() {
7804 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7805 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7807 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7808 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7811 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7813 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7814 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7815 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7816 let scorer = test_utils::TestScorer::with_penalty(0);
7817 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7818 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7819 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7820 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7821 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7822 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7823 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7824 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7826 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7827 assert_eq!(revoked_local_txn[0].input.len(), 1);
7828 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7830 // Revoke local commitment tx
7831 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7833 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7834 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7835 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7836 check_closed_broadcast!(nodes[1], true);
7837 check_added_monitors!(nodes[1], 1);
7838 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7839 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7841 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7842 assert_eq!(revoked_htlc_txn.len(), 3);
7843 check_spends!(revoked_htlc_txn[1], chan.3);
7845 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7846 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7847 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7849 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7850 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7851 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7852 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7854 // Broadcast set of revoked txn on A
7855 let hash_128 = connect_blocks(&nodes[0], 40);
7856 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7857 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7858 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7859 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7860 let events = nodes[0].node.get_and_clear_pending_events();
7861 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7863 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7864 _ => panic!("Unexpected event"),
7870 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7871 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7872 // Verify claim tx are spending revoked HTLC txn
7874 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7875 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7876 // which are included in the same block (they are broadcasted because we scan the
7877 // transactions linearly and generate claims as we go, they likely should be removed in the
7879 assert_eq!(node_txn[0].input.len(), 1);
7880 check_spends!(node_txn[0], revoked_local_txn[0]);
7881 assert_eq!(node_txn[1].input.len(), 1);
7882 check_spends!(node_txn[1], revoked_local_txn[0]);
7883 assert_eq!(node_txn[2].input.len(), 1);
7884 check_spends!(node_txn[2], revoked_local_txn[0]);
7886 // Each of the three justice transactions claim a separate (single) output of the three
7887 // available, which we check here:
7888 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7889 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7890 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7892 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7893 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7895 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7896 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7897 // a remote commitment tx has already been confirmed).
7898 check_spends!(node_txn[3], chan.3);
7900 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7901 // output, checked above).
7902 assert_eq!(node_txn[4].input.len(), 2);
7903 assert_eq!(node_txn[4].output.len(), 1);
7904 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7906 first = node_txn[4].txid();
7907 // Store both feerates for later comparison
7908 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7909 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7910 penalty_txn = vec![node_txn[2].clone()];
7914 // Connect one more block to see if bumped penalty are issued for HTLC txn
7915 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7916 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7917 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7918 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7920 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7921 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7923 check_spends!(node_txn[0], revoked_local_txn[0]);
7924 check_spends!(node_txn[1], revoked_local_txn[0]);
7925 // Note that these are both bogus - they spend outputs already claimed in block 129:
7926 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7927 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7929 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7930 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7936 // Few more blocks to confirm penalty txn
7937 connect_blocks(&nodes[0], 4);
7938 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7939 let header_144 = connect_blocks(&nodes[0], 9);
7941 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7942 assert_eq!(node_txn.len(), 1);
7944 assert_eq!(node_txn[0].input.len(), 2);
7945 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7946 // Verify bumped tx is different and 25% bump heuristic
7947 assert_ne!(first, node_txn[0].txid());
7948 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7949 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7950 assert!(feerate_2 * 100 > feerate_1 * 125);
7951 let txn = vec![node_txn[0].clone()];
7955 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7956 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7957 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7958 connect_blocks(&nodes[0], 20);
7960 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7961 // We verify than no new transaction has been broadcast because previously
7962 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7963 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7964 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7965 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7966 // up bumped justice generation.
7967 assert_eq!(node_txn.len(), 0);
7970 check_closed_broadcast!(nodes[0], true);
7971 check_added_monitors!(nodes[0], 1);
7975 fn test_bump_penalty_txn_on_remote_commitment() {
7976 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7977 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7980 // Provide preimage for one
7981 // Check aggregation
7983 let chanmon_cfgs = create_chanmon_cfgs(2);
7984 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7985 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7986 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7988 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7989 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7990 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7992 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7993 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7994 assert_eq!(remote_txn[0].output.len(), 4);
7995 assert_eq!(remote_txn[0].input.len(), 1);
7996 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7998 // Claim a HTLC without revocation (provide B monitor with preimage)
7999 nodes[1].node.claim_funds(payment_preimage);
8000 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8001 mine_transaction(&nodes[1], &remote_txn[0]);
8002 check_added_monitors!(nodes[1], 2);
8003 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8005 // One or more claim tx should have been broadcast, check it
8009 let feerate_timeout;
8010 let feerate_preimage;
8012 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8013 // 9 transactions including:
8014 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8015 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8016 // 2 * HTLC-Success (one RBF bump we'll check later)
8018 assert_eq!(node_txn.len(), 8);
8019 assert_eq!(node_txn[0].input.len(), 1);
8020 assert_eq!(node_txn[6].input.len(), 1);
8021 check_spends!(node_txn[0], remote_txn[0]);
8022 check_spends!(node_txn[6], remote_txn[0]);
8024 check_spends!(node_txn[1], chan.3);
8025 check_spends!(node_txn[2], node_txn[1]);
8027 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8028 preimage_bump = node_txn[3].clone();
8029 check_spends!(node_txn[3], remote_txn[0]);
8031 assert_eq!(node_txn[1], node_txn[4]);
8032 assert_eq!(node_txn[2], node_txn[5]);
8034 preimage_bump = node_txn[7].clone();
8035 check_spends!(node_txn[7], remote_txn[0]);
8036 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8038 assert_eq!(node_txn[1], node_txn[3]);
8039 assert_eq!(node_txn[2], node_txn[4]);
8042 timeout = node_txn[6].txid();
8043 let index = node_txn[6].input[0].previous_output.vout;
8044 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8045 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8047 preimage = node_txn[0].txid();
8048 let index = node_txn[0].input[0].previous_output.vout;
8049 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8050 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8054 assert_ne!(feerate_timeout, 0);
8055 assert_ne!(feerate_preimage, 0);
8057 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8058 connect_blocks(&nodes[1], 15);
8060 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8061 assert_eq!(node_txn.len(), 1);
8062 assert_eq!(node_txn[0].input.len(), 1);
8063 assert_eq!(preimage_bump.input.len(), 1);
8064 check_spends!(node_txn[0], remote_txn[0]);
8065 check_spends!(preimage_bump, remote_txn[0]);
8067 let index = preimage_bump.input[0].previous_output.vout;
8068 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8069 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8070 assert!(new_feerate * 100 > feerate_timeout * 125);
8071 assert_ne!(timeout, preimage_bump.txid());
8073 let index = node_txn[0].input[0].previous_output.vout;
8074 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8075 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8076 assert!(new_feerate * 100 > feerate_preimage * 125);
8077 assert_ne!(preimage, node_txn[0].txid());
8082 nodes[1].node.get_and_clear_pending_events();
8083 nodes[1].node.get_and_clear_pending_msg_events();
8087 fn test_counterparty_raa_skip_no_crash() {
8088 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8089 // commitment transaction, we would have happily carried on and provided them the next
8090 // commitment transaction based on one RAA forward. This would probably eventually have led to
8091 // channel closure, but it would not have resulted in funds loss. Still, our
8092 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8093 // check simply that the channel is closed in response to such an RAA, but don't check whether
8094 // we decide to punish our counterparty for revoking their funds (as we don't currently
8096 let chanmon_cfgs = create_chanmon_cfgs(2);
8097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8099 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8100 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8102 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8103 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8105 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8107 // Make signer believe we got a counterparty signature, so that it allows the revocation
8108 keys.get_enforcement_state().last_holder_commitment -= 1;
8109 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8111 // Must revoke without gaps
8112 keys.get_enforcement_state().last_holder_commitment -= 1;
8113 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8115 keys.get_enforcement_state().last_holder_commitment -= 1;
8116 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8117 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8119 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8120 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8121 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8122 check_added_monitors!(nodes[1], 1);
8123 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8127 fn test_bump_txn_sanitize_tracking_maps() {
8128 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8129 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8131 let chanmon_cfgs = create_chanmon_cfgs(2);
8132 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8136 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8137 // Lock HTLC in both directions
8138 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8139 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8141 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8142 assert_eq!(revoked_local_txn[0].input.len(), 1);
8143 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8145 // Revoke local commitment tx
8146 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8148 // Broadcast set of revoked txn on A
8149 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8150 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8151 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8153 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8154 check_closed_broadcast!(nodes[0], true);
8155 check_added_monitors!(nodes[0], 1);
8156 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8158 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8159 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8160 check_spends!(node_txn[0], revoked_local_txn[0]);
8161 check_spends!(node_txn[1], revoked_local_txn[0]);
8162 check_spends!(node_txn[2], revoked_local_txn[0]);
8163 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8167 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8168 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8169 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8171 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8172 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8173 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8178 fn test_pending_claimed_htlc_no_balance_underflow() {
8179 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8180 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8181 let chanmon_cfgs = create_chanmon_cfgs(2);
8182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8185 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8187 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8188 nodes[1].node.claim_funds(payment_preimage);
8189 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8190 check_added_monitors!(nodes[1], 1);
8191 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8193 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8194 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8195 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8196 check_added_monitors!(nodes[0], 1);
8197 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8199 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8200 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8201 // can get our balance.
8203 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8204 // the public key of the only hop. This works around ChannelDetails not showing the
8205 // almost-claimed HTLC as available balance.
8206 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8207 route.payment_params = None; // This is all wrong, but unnecessary
8208 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8209 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8210 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8212 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8216 fn test_channel_conf_timeout() {
8217 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8218 // confirm within 2016 blocks, as recommended by BOLT 2.
8219 let chanmon_cfgs = create_chanmon_cfgs(2);
8220 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8221 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8222 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8224 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8226 // The outbound node should wait forever for confirmation:
8227 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8228 // copied here instead of directly referencing the constant.
8229 connect_blocks(&nodes[0], 2016);
8230 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8232 // The inbound node should fail the channel after exactly 2016 blocks
8233 connect_blocks(&nodes[1], 2015);
8234 check_added_monitors!(nodes[1], 0);
8235 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8237 connect_blocks(&nodes[1], 1);
8238 check_added_monitors!(nodes[1], 1);
8239 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8240 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8241 assert_eq!(close_ev.len(), 1);
8243 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8244 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8245 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8247 _ => panic!("Unexpected event"),
8252 fn test_override_channel_config() {
8253 let chanmon_cfgs = create_chanmon_cfgs(2);
8254 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8255 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8256 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8258 // Node0 initiates a channel to node1 using the override config.
8259 let mut override_config = UserConfig::default();
8260 override_config.channel_handshake_config.our_to_self_delay = 200;
8262 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8264 // Assert the channel created by node0 is using the override config.
8265 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8266 assert_eq!(res.channel_flags, 0);
8267 assert_eq!(res.to_self_delay, 200);
8271 fn test_override_0msat_htlc_minimum() {
8272 let mut zero_config = UserConfig::default();
8273 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8274 let chanmon_cfgs = create_chanmon_cfgs(2);
8275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8277 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8279 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8280 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8281 assert_eq!(res.htlc_minimum_msat, 1);
8283 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8284 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8285 assert_eq!(res.htlc_minimum_msat, 1);
8289 fn test_channel_update_has_correct_htlc_maximum_msat() {
8290 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8291 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8292 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8293 // 90% of the `channel_value`.
8294 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8296 let mut config_30_percent = UserConfig::default();
8297 config_30_percent.channel_handshake_config.announced_channel = true;
8298 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8299 let mut config_50_percent = UserConfig::default();
8300 config_50_percent.channel_handshake_config.announced_channel = true;
8301 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8302 let mut config_95_percent = UserConfig::default();
8303 config_95_percent.channel_handshake_config.announced_channel = true;
8304 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8305 let mut config_100_percent = UserConfig::default();
8306 config_100_percent.channel_handshake_config.announced_channel = true;
8307 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8309 let chanmon_cfgs = create_chanmon_cfgs(4);
8310 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8311 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)]);
8312 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8314 let channel_value_satoshis = 100000;
8315 let channel_value_msat = channel_value_satoshis * 1000;
8316 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8317 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8318 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8320 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());
8321 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());
8323 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8324 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8325 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8326 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8327 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8328 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8330 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8331 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8333 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8334 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8335 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8337 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8341 fn test_manually_accept_inbound_channel_request() {
8342 let mut manually_accept_conf = UserConfig::default();
8343 manually_accept_conf.manually_accept_inbound_channels = true;
8344 let chanmon_cfgs = create_chanmon_cfgs(2);
8345 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8346 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8347 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8349 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8350 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8352 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8354 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8355 // accepting the inbound channel request.
8356 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8358 let events = nodes[1].node.get_and_clear_pending_events();
8360 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8361 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8363 _ => panic!("Unexpected event"),
8366 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8367 assert_eq!(accept_msg_ev.len(), 1);
8369 match accept_msg_ev[0] {
8370 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8371 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8373 _ => panic!("Unexpected event"),
8376 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8378 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8379 assert_eq!(close_msg_ev.len(), 1);
8381 let events = nodes[1].node.get_and_clear_pending_events();
8383 Event::ChannelClosed { user_channel_id, .. } => {
8384 assert_eq!(user_channel_id, 23);
8386 _ => panic!("Unexpected event"),
8391 fn test_manually_reject_inbound_channel_request() {
8392 let mut manually_accept_conf = UserConfig::default();
8393 manually_accept_conf.manually_accept_inbound_channels = true;
8394 let chanmon_cfgs = create_chanmon_cfgs(2);
8395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8399 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8400 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8402 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8404 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8405 // rejecting the inbound channel request.
8406 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8408 let events = nodes[1].node.get_and_clear_pending_events();
8410 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8411 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8413 _ => panic!("Unexpected event"),
8416 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8417 assert_eq!(close_msg_ev.len(), 1);
8419 match close_msg_ev[0] {
8420 MessageSendEvent::HandleError { ref node_id, .. } => {
8421 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8423 _ => panic!("Unexpected event"),
8425 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8429 fn test_reject_funding_before_inbound_channel_accepted() {
8430 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8431 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8432 // the node operator before the counterparty sends a `FundingCreated` message. If a
8433 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8434 // and the channel should be closed.
8435 let mut manually_accept_conf = UserConfig::default();
8436 manually_accept_conf.manually_accept_inbound_channels = true;
8437 let chanmon_cfgs = create_chanmon_cfgs(2);
8438 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8439 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8440 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8442 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8443 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8444 let temp_channel_id = res.temporary_channel_id;
8446 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8448 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8449 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8451 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8452 nodes[1].node.get_and_clear_pending_events();
8454 // Get the `AcceptChannel` message of `nodes[1]` without calling
8455 // `ChannelManager::accept_inbound_channel`, which generates a
8456 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8457 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8458 // succeed when `nodes[0]` is passed to it.
8461 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8462 let accept_chan_msg = channel.get_accept_channel_message();
8463 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8466 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8468 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8469 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8471 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8472 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8474 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8475 assert_eq!(close_msg_ev.len(), 1);
8477 let expected_err = "FundingCreated message received before the channel was accepted";
8478 match close_msg_ev[0] {
8479 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8480 assert_eq!(msg.channel_id, temp_channel_id);
8481 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8482 assert_eq!(msg.data, expected_err);
8484 _ => panic!("Unexpected event"),
8487 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8491 fn test_can_not_accept_inbound_channel_twice() {
8492 let mut manually_accept_conf = UserConfig::default();
8493 manually_accept_conf.manually_accept_inbound_channels = true;
8494 let chanmon_cfgs = create_chanmon_cfgs(2);
8495 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8496 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8497 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8499 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8500 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8502 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8504 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8505 // accepting the inbound channel request.
8506 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8508 let events = nodes[1].node.get_and_clear_pending_events();
8510 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8511 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8512 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8514 Err(APIError::APIMisuseError { err }) => {
8515 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8517 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8518 Err(_) => panic!("Unexpected Error"),
8521 _ => panic!("Unexpected event"),
8524 // Ensure that the channel wasn't closed after attempting to accept it twice.
8525 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8526 assert_eq!(accept_msg_ev.len(), 1);
8528 match accept_msg_ev[0] {
8529 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8530 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8532 _ => panic!("Unexpected event"),
8537 fn test_can_not_accept_unknown_inbound_channel() {
8538 let chanmon_cfg = create_chanmon_cfgs(2);
8539 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8540 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8541 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8543 let unknown_channel_id = [0; 32];
8544 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8546 Err(APIError::ChannelUnavailable { err }) => {
8547 assert_eq!(err, "Can't accept a channel that doesn't exist");
8549 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8550 Err(_) => panic!("Unexpected Error"),
8555 fn test_simple_mpp() {
8556 // Simple test of sending a multi-path payment.
8557 let chanmon_cfgs = create_chanmon_cfgs(4);
8558 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8559 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8560 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8562 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8563 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8564 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8565 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8567 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8568 let path = route.paths[0].clone();
8569 route.paths.push(path);
8570 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8571 route.paths[0][0].short_channel_id = chan_1_id;
8572 route.paths[0][1].short_channel_id = chan_3_id;
8573 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8574 route.paths[1][0].short_channel_id = chan_2_id;
8575 route.paths[1][1].short_channel_id = chan_4_id;
8576 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8577 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8581 fn test_preimage_storage() {
8582 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8583 let chanmon_cfgs = create_chanmon_cfgs(2);
8584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8588 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8591 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8592 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8593 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8594 check_added_monitors!(nodes[0], 1);
8595 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8596 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8597 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8598 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8600 // Note that after leaving the above scope we have no knowledge of any arguments or return
8601 // values from previous calls.
8602 expect_pending_htlcs_forwardable!(nodes[1]);
8603 let events = nodes[1].node.get_and_clear_pending_events();
8604 assert_eq!(events.len(), 1);
8606 Event::PaymentReceived { ref purpose, .. } => {
8608 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8609 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8611 _ => panic!("expected PaymentPurpose::InvoicePayment")
8614 _ => panic!("Unexpected event"),
8619 #[allow(deprecated)]
8620 fn test_secret_timeout() {
8621 // Simple test of payment secret storage time outs. After
8622 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8623 let chanmon_cfgs = create_chanmon_cfgs(2);
8624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8626 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8628 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8630 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8632 // We should fail to register the same payment hash twice, at least until we've connected a
8633 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8634 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8635 assert_eq!(err, "Duplicate payment hash");
8636 } else { panic!(); }
8638 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8640 header: BlockHeader {
8642 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8643 merkle_root: Default::default(),
8644 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8648 connect_block(&nodes[1], &block);
8649 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8650 assert_eq!(err, "Duplicate payment hash");
8651 } else { panic!(); }
8653 // If we then connect the second block, we should be able to register the same payment hash
8654 // again (this time getting a new payment secret).
8655 block.header.prev_blockhash = block.header.block_hash();
8656 block.header.time += 1;
8657 connect_block(&nodes[1], &block);
8658 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8659 assert_ne!(payment_secret_1, our_payment_secret);
8662 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8663 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8664 check_added_monitors!(nodes[0], 1);
8665 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8666 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8667 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8668 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8670 // Note that after leaving the above scope we have no knowledge of any arguments or return
8671 // values from previous calls.
8672 expect_pending_htlcs_forwardable!(nodes[1]);
8673 let events = nodes[1].node.get_and_clear_pending_events();
8674 assert_eq!(events.len(), 1);
8676 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8677 assert!(payment_preimage.is_none());
8678 assert_eq!(payment_secret, our_payment_secret);
8679 // We don't actually have the payment preimage with which to claim this payment!
8681 _ => panic!("Unexpected event"),
8686 fn test_bad_secret_hash() {
8687 // Simple test of unregistered payment hash/invalid payment secret handling
8688 let chanmon_cfgs = create_chanmon_cfgs(2);
8689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8691 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8693 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8695 let random_payment_hash = PaymentHash([42; 32]);
8696 let random_payment_secret = PaymentSecret([43; 32]);
8697 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8698 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8700 // All the below cases should end up being handled exactly identically, so we macro the
8701 // resulting events.
8702 macro_rules! handle_unknown_invalid_payment_data {
8704 check_added_monitors!(nodes[0], 1);
8705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8706 let payment_event = SendEvent::from_event(events.pop().unwrap());
8707 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8708 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8710 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8711 // again to process the pending backwards-failure of the HTLC
8712 expect_pending_htlcs_forwardable!(nodes[1]);
8713 expect_pending_htlcs_forwardable!(nodes[1]);
8714 check_added_monitors!(nodes[1], 1);
8716 // We should fail the payment back
8717 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8718 match events.pop().unwrap() {
8719 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8720 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8721 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8723 _ => panic!("Unexpected event"),
8728 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8729 // Error data is the HTLC value (100,000) and current block height
8730 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8732 // Send a payment with the right payment hash but the wrong payment secret
8733 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8734 handle_unknown_invalid_payment_data!();
8735 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8737 // Send a payment with a random payment hash, but the right payment secret
8738 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8739 handle_unknown_invalid_payment_data!();
8740 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8742 // Send a payment with a random payment hash and random payment secret
8743 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8744 handle_unknown_invalid_payment_data!();
8745 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8749 fn test_update_err_monitor_lockdown() {
8750 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8751 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8752 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8754 // This scenario may happen in a watchtower setup, where watchtower process a block height
8755 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8756 // commitment at same time.
8758 let chanmon_cfgs = create_chanmon_cfgs(2);
8759 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8760 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8761 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8763 // Create some initial channel
8764 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8765 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8767 // Rebalance the network to generate htlc in the two directions
8768 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8770 // Route a HTLC from node 0 to node 1 (but don't settle)
8771 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8773 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8774 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8775 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8776 let persister = test_utils::TestPersister::new();
8778 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8779 let mut w = test_utils::TestVecWriter(Vec::new());
8780 monitor.write(&mut w).unwrap();
8781 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8782 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8783 assert!(new_monitor == *monitor);
8784 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);
8785 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8788 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8789 let block = Block { header, txdata: vec![] };
8790 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8791 // transaction lock time requirements here.
8792 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8793 watchtower.chain_monitor.block_connected(&block, 200);
8795 // Try to update ChannelMonitor
8796 nodes[1].node.claim_funds(preimage);
8797 check_added_monitors!(nodes[1], 1);
8798 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8800 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8801 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8802 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8803 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8804 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8805 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8806 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8807 } else { assert!(false); }
8808 } else { assert!(false); };
8809 // Our local monitor is in-sync and hasn't processed yet timeout
8810 check_added_monitors!(nodes[0], 1);
8811 let events = nodes[0].node.get_and_clear_pending_events();
8812 assert_eq!(events.len(), 1);
8816 fn test_concurrent_monitor_claim() {
8817 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8818 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8819 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8820 // state N+1 confirms. Alice claims output from state N+1.
8822 let chanmon_cfgs = create_chanmon_cfgs(2);
8823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8825 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8827 // Create some initial channel
8828 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8829 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8831 // Rebalance the network to generate htlc in the two directions
8832 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8834 // Route a HTLC from node 0 to node 1 (but don't settle)
8835 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8837 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8838 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8839 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8840 let persister = test_utils::TestPersister::new();
8841 let watchtower_alice = {
8842 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8843 let mut w = test_utils::TestVecWriter(Vec::new());
8844 monitor.write(&mut w).unwrap();
8845 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8846 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8847 assert!(new_monitor == *monitor);
8848 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);
8849 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8852 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8853 let block = Block { header, txdata: vec![] };
8854 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8855 // transaction lock time requirements here.
8856 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));
8857 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8859 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8861 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8862 assert_eq!(txn.len(), 2);
8866 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8867 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8868 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8869 let persister = test_utils::TestPersister::new();
8870 let watchtower_bob = {
8871 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8872 let mut w = test_utils::TestVecWriter(Vec::new());
8873 monitor.write(&mut w).unwrap();
8874 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8875 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8876 assert!(new_monitor == *monitor);
8877 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);
8878 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8881 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8882 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8884 // Route another payment to generate another update with still previous HTLC pending
8885 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8887 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8889 check_added_monitors!(nodes[1], 1);
8891 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8892 assert_eq!(updates.update_add_htlcs.len(), 1);
8893 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8894 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8895 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8896 // Watchtower Alice should already have seen the block and reject the update
8897 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8898 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8899 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8900 } else { assert!(false); }
8901 } else { assert!(false); };
8902 // Our local monitor is in-sync and hasn't processed yet timeout
8903 check_added_monitors!(nodes[0], 1);
8905 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8906 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8907 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8909 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8912 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8913 assert_eq!(txn.len(), 2);
8914 bob_state_y = txn[0].clone();
8918 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8919 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8920 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);
8922 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8923 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8924 // the onchain detection of the HTLC output
8925 assert_eq!(htlc_txn.len(), 2);
8926 check_spends!(htlc_txn[0], bob_state_y);
8927 check_spends!(htlc_txn[1], bob_state_y);
8932 fn test_pre_lockin_no_chan_closed_update() {
8933 // Test that if a peer closes a channel in response to a funding_created message we don't
8934 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8937 // Doing so would imply a channel monitor update before the initial channel monitor
8938 // registration, violating our API guarantees.
8940 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8941 // then opening a second channel with the same funding output as the first (which is not
8942 // rejected because the first channel does not exist in the ChannelManager) and closing it
8943 // before receiving funding_signed.
8944 let chanmon_cfgs = create_chanmon_cfgs(2);
8945 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8946 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8947 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8949 // Create an initial channel
8950 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8951 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8952 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8953 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8954 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8956 // Move the first channel through the funding flow...
8957 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8959 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8960 check_added_monitors!(nodes[0], 0);
8962 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8963 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8964 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8965 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8966 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8970 fn test_htlc_no_detection() {
8971 // This test is a mutation to underscore the detection logic bug we had
8972 // before #653. HTLC value routed is above the remaining balance, thus
8973 // inverting HTLC and `to_remote` output. HTLC will come second and
8974 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8975 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8976 // outputs order detection for correct spending children filtring.
8978 let chanmon_cfgs = create_chanmon_cfgs(2);
8979 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8980 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8981 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8983 // Create some initial channels
8984 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8986 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8987 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8988 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8989 assert_eq!(local_txn[0].input.len(), 1);
8990 assert_eq!(local_txn[0].output.len(), 3);
8991 check_spends!(local_txn[0], chan_1.3);
8993 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8994 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8995 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8996 // We deliberately connect the local tx twice as this should provoke a failure calling
8997 // this test before #653 fix.
8998 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);
8999 check_closed_broadcast!(nodes[0], true);
9000 check_added_monitors!(nodes[0], 1);
9001 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9002 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9004 let htlc_timeout = {
9005 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9006 assert_eq!(node_txn[1].input.len(), 1);
9007 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9008 check_spends!(node_txn[1], local_txn[0]);
9012 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9013 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9014 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9015 expect_payment_failed!(nodes[0], our_payment_hash, true);
9018 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9019 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9020 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9021 // Carol, Alice would be the upstream node, and Carol the downstream.)
9023 // Steps of the test:
9024 // 1) Alice sends a HTLC to Carol through Bob.
9025 // 2) Carol doesn't settle the HTLC.
9026 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9027 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9028 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9029 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9030 // 5) Carol release the preimage to Bob off-chain.
9031 // 6) Bob claims the offered output on the broadcasted commitment.
9032 let chanmon_cfgs = create_chanmon_cfgs(3);
9033 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9034 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9035 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9037 // Create some initial channels
9038 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9039 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9041 // Steps (1) and (2):
9042 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9043 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9045 // Check that Alice's commitment transaction now contains an output for this HTLC.
9046 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9047 check_spends!(alice_txn[0], chan_ab.3);
9048 assert_eq!(alice_txn[0].output.len(), 2);
9049 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9050 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9051 assert_eq!(alice_txn.len(), 2);
9053 // Steps (3) and (4):
9054 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9055 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9056 let mut force_closing_node = 0; // Alice force-closes
9057 let mut counterparty_node = 1; // Bob if Alice force-closes
9060 if !broadcast_alice {
9061 force_closing_node = 1;
9062 counterparty_node = 0;
9064 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9065 check_closed_broadcast!(nodes[force_closing_node], true);
9066 check_added_monitors!(nodes[force_closing_node], 1);
9067 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9068 if go_onchain_before_fulfill {
9069 let txn_to_broadcast = match broadcast_alice {
9070 true => alice_txn.clone(),
9071 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9073 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9074 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9075 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9076 if broadcast_alice {
9077 check_closed_broadcast!(nodes[1], true);
9078 check_added_monitors!(nodes[1], 1);
9079 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9081 assert_eq!(bob_txn.len(), 1);
9082 check_spends!(bob_txn[0], chan_ab.3);
9086 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9087 // process of removing the HTLC from their commitment transactions.
9088 nodes[2].node.claim_funds(payment_preimage);
9089 check_added_monitors!(nodes[2], 1);
9090 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9092 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9093 assert!(carol_updates.update_add_htlcs.is_empty());
9094 assert!(carol_updates.update_fail_htlcs.is_empty());
9095 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9096 assert!(carol_updates.update_fee.is_none());
9097 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9099 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9100 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9101 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9102 if !go_onchain_before_fulfill && broadcast_alice {
9103 let events = nodes[1].node.get_and_clear_pending_msg_events();
9104 assert_eq!(events.len(), 1);
9106 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9107 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9109 _ => panic!("Unexpected event"),
9112 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9113 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9114 // Carol<->Bob's updated commitment transaction info.
9115 check_added_monitors!(nodes[1], 2);
9117 let events = nodes[1].node.get_and_clear_pending_msg_events();
9118 assert_eq!(events.len(), 2);
9119 let bob_revocation = match events[0] {
9120 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9121 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9124 _ => panic!("Unexpected event"),
9126 let bob_updates = match events[1] {
9127 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9128 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9131 _ => panic!("Unexpected event"),
9134 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9135 check_added_monitors!(nodes[2], 1);
9136 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9137 check_added_monitors!(nodes[2], 1);
9139 let events = nodes[2].node.get_and_clear_pending_msg_events();
9140 assert_eq!(events.len(), 1);
9141 let carol_revocation = match events[0] {
9142 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9143 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9146 _ => panic!("Unexpected event"),
9148 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9149 check_added_monitors!(nodes[1], 1);
9151 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9152 // here's where we put said channel's commitment tx on-chain.
9153 let mut txn_to_broadcast = alice_txn.clone();
9154 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9155 if !go_onchain_before_fulfill {
9156 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9157 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9158 // If Bob was the one to force-close, he will have already passed these checks earlier.
9159 if broadcast_alice {
9160 check_closed_broadcast!(nodes[1], true);
9161 check_added_monitors!(nodes[1], 1);
9162 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9164 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9165 if broadcast_alice {
9166 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9167 // new block being connected. The ChannelManager being notified triggers a monitor update,
9168 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9169 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9171 assert_eq!(bob_txn.len(), 3);
9172 check_spends!(bob_txn[1], chan_ab.3);
9174 assert_eq!(bob_txn.len(), 2);
9175 check_spends!(bob_txn[0], chan_ab.3);
9180 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9181 // broadcasted commitment transaction.
9183 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9184 if go_onchain_before_fulfill {
9185 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9186 assert_eq!(bob_txn.len(), 2);
9188 let script_weight = match broadcast_alice {
9189 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9190 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9192 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9193 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9194 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9195 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9196 if broadcast_alice && !go_onchain_before_fulfill {
9197 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9198 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9200 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9201 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9207 fn test_onchain_htlc_settlement_after_close() {
9208 do_test_onchain_htlc_settlement_after_close(true, true);
9209 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9210 do_test_onchain_htlc_settlement_after_close(true, false);
9211 do_test_onchain_htlc_settlement_after_close(false, false);
9215 fn test_duplicate_chan_id() {
9216 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9217 // already open we reject it and keep the old channel.
9219 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9220 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9221 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9222 // updating logic for the existing channel.
9223 let chanmon_cfgs = create_chanmon_cfgs(2);
9224 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9225 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9226 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9228 // Create an initial channel
9229 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9230 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9231 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9232 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()));
9234 // Try to create a second channel with the same temporary_channel_id as the first and check
9235 // that it is rejected.
9236 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9238 let events = nodes[1].node.get_and_clear_pending_msg_events();
9239 assert_eq!(events.len(), 1);
9241 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9242 // Technically, at this point, nodes[1] would be justified in thinking both the
9243 // first (valid) and second (invalid) channels are closed, given they both have
9244 // the same non-temporary channel_id. However, currently we do not, so we just
9245 // move forward with it.
9246 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9247 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9249 _ => panic!("Unexpected event"),
9253 // Move the first channel through the funding flow...
9254 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9256 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9257 check_added_monitors!(nodes[0], 0);
9259 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9260 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9262 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9263 assert_eq!(added_monitors.len(), 1);
9264 assert_eq!(added_monitors[0].0, funding_output);
9265 added_monitors.clear();
9267 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9269 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9270 let channel_id = funding_outpoint.to_channel_id();
9272 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9275 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9276 // Technically this is allowed by the spec, but we don't support it and there's little reason
9277 // to. Still, it shouldn't cause any other issues.
9278 open_chan_msg.temporary_channel_id = channel_id;
9279 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9281 let events = nodes[1].node.get_and_clear_pending_msg_events();
9282 assert_eq!(events.len(), 1);
9284 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9285 // Technically, at this point, nodes[1] would be justified in thinking both
9286 // channels are closed, but currently we do not, so we just move forward with it.
9287 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9288 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9290 _ => panic!("Unexpected event"),
9294 // Now try to create a second channel which has a duplicate funding output.
9295 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9296 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9297 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9298 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()));
9299 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9301 let funding_created = {
9302 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9303 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9304 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9305 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9306 // channelmanager in a possibly nonsense state instead).
9307 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9308 let logger = test_utils::TestLogger::new();
9309 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9311 check_added_monitors!(nodes[0], 0);
9312 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9313 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9314 // still needs to be cleared here.
9315 check_added_monitors!(nodes[1], 1);
9317 // ...still, nodes[1] will reject the duplicate channel.
9319 let events = nodes[1].node.get_and_clear_pending_msg_events();
9320 assert_eq!(events.len(), 1);
9322 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9323 // Technically, at this point, nodes[1] would be justified in thinking both
9324 // channels are closed, but currently we do not, so we just move forward with it.
9325 assert_eq!(msg.channel_id, channel_id);
9326 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9328 _ => panic!("Unexpected event"),
9332 // finally, finish creating the original channel and send a payment over it to make sure
9333 // everything is functional.
9334 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9336 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9337 assert_eq!(added_monitors.len(), 1);
9338 assert_eq!(added_monitors[0].0, funding_output);
9339 added_monitors.clear();
9342 let events_4 = nodes[0].node.get_and_clear_pending_events();
9343 assert_eq!(events_4.len(), 0);
9344 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9345 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9347 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9348 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9349 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9350 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9354 fn test_error_chans_closed() {
9355 // Test that we properly handle error messages, closing appropriate channels.
9357 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9358 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9359 // we can test various edge cases around it to ensure we don't regress.
9360 let chanmon_cfgs = create_chanmon_cfgs(3);
9361 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9362 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9363 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9365 // Create some initial channels
9366 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9367 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9368 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9370 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9371 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9372 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9374 // Closing a channel from a different peer has no effect
9375 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9376 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9378 // Closing one channel doesn't impact others
9379 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9380 check_added_monitors!(nodes[0], 1);
9381 check_closed_broadcast!(nodes[0], false);
9382 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9383 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9384 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9385 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);
9386 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);
9388 // A null channel ID should close all channels
9389 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9390 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9391 check_added_monitors!(nodes[0], 2);
9392 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9393 let events = nodes[0].node.get_and_clear_pending_msg_events();
9394 assert_eq!(events.len(), 2);
9396 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9397 assert_eq!(msg.contents.flags & 2, 2);
9399 _ => panic!("Unexpected event"),
9402 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9403 assert_eq!(msg.contents.flags & 2, 2);
9405 _ => panic!("Unexpected event"),
9407 // Note that at this point users of a standard PeerHandler will end up calling
9408 // peer_disconnected with no_connection_possible set to false, duplicating the
9409 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9410 // users with their own peer handling logic. We duplicate the call here, however.
9411 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9412 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9414 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9415 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9416 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9420 fn test_invalid_funding_tx() {
9421 // Test that we properly handle invalid funding transactions sent to us from a peer.
9423 // Previously, all other major lightning implementations had failed to properly sanitize
9424 // funding transactions from their counterparties, leading to a multi-implementation critical
9425 // security vulnerability (though we always sanitized properly, we've previously had
9426 // un-released crashes in the sanitization process).
9428 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9429 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9430 // gave up on it. We test this here by generating such a transaction.
9431 let chanmon_cfgs = create_chanmon_cfgs(2);
9432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9434 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9436 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9437 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()));
9438 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()));
9440 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9442 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9443 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9444 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9446 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9447 assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9448 chan_utils::HTLCType::AcceptedHTLC);
9450 let wit_program_script: Script = wit_program.clone().into();
9451 for output in tx.output.iter_mut() {
9452 // Make the confirmed funding transaction have a bogus script_pubkey
9453 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9456 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9457 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()));
9458 check_added_monitors!(nodes[1], 1);
9460 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()));
9461 check_added_monitors!(nodes[0], 1);
9463 let events_1 = nodes[0].node.get_and_clear_pending_events();
9464 assert_eq!(events_1.len(), 0);
9466 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9467 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9468 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9470 let expected_err = "funding tx had wrong script/value or output index";
9471 confirm_transaction_at(&nodes[1], &tx, 1);
9472 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9473 check_added_monitors!(nodes[1], 1);
9474 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9475 assert_eq!(events_2.len(), 1);
9476 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9477 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9478 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9479 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9480 } else { panic!(); }
9481 } else { panic!(); }
9482 assert_eq!(nodes[1].node.list_channels().len(), 0);
9484 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9485 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9486 // as its not 32 bytes long.
9487 let mut spend_tx = Transaction {
9488 version: 2i32, lock_time: 0,
9489 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9490 previous_output: BitcoinOutPoint {
9494 script_sig: Script::new(),
9495 sequence: 0xfffffffd,
9496 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9498 output: vec![TxOut {
9500 script_pubkey: Script::new(),
9503 check_spends!(spend_tx, tx);
9504 mine_transaction(&nodes[1], &spend_tx);
9507 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9508 // In the first version of the chain::Confirm interface, after a refactor was made to not
9509 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9510 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9511 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9512 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9513 // spending transaction until height N+1 (or greater). This was due to the way
9514 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9515 // spending transaction at the height the input transaction was confirmed at, not whether we
9516 // should broadcast a spending transaction at the current height.
9517 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9518 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9519 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9520 // until we learned about an additional block.
9522 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9523 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9524 let chanmon_cfgs = create_chanmon_cfgs(3);
9525 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9526 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9527 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9528 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9530 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9531 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9532 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9533 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9534 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9536 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9537 check_closed_broadcast!(nodes[1], true);
9538 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9539 check_added_monitors!(nodes[1], 1);
9540 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9541 assert_eq!(node_txn.len(), 1);
9543 let conf_height = nodes[1].best_block_info().1;
9544 if !test_height_before_timelock {
9545 connect_blocks(&nodes[1], 24 * 6);
9547 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9548 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9549 if test_height_before_timelock {
9550 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9551 // generate any events or broadcast any transactions
9552 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9553 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9555 // We should broadcast an HTLC transaction spending our funding transaction first
9556 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9557 assert_eq!(spending_txn.len(), 2);
9558 assert_eq!(spending_txn[0], node_txn[0]);
9559 check_spends!(spending_txn[1], node_txn[0]);
9560 // We should also generate a SpendableOutputs event with the to_self output (as its
9562 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9563 assert_eq!(descriptor_spend_txn.len(), 1);
9565 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9566 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9567 // additional block built on top of the current chain.
9568 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9569 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9570 expect_pending_htlcs_forwardable!(nodes[1]);
9571 check_added_monitors!(nodes[1], 1);
9573 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9574 assert!(updates.update_add_htlcs.is_empty());
9575 assert!(updates.update_fulfill_htlcs.is_empty());
9576 assert_eq!(updates.update_fail_htlcs.len(), 1);
9577 assert!(updates.update_fail_malformed_htlcs.is_empty());
9578 assert!(updates.update_fee.is_none());
9579 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9580 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9581 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9586 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9587 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9588 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9592 fn test_forwardable_regen() {
9593 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9594 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9596 // We test it for both payment receipt and payment forwarding.
9598 let chanmon_cfgs = create_chanmon_cfgs(3);
9599 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9600 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9601 let persister: test_utils::TestPersister;
9602 let new_chain_monitor: test_utils::TestChainMonitor;
9603 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9604 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9605 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9606 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9608 // First send a payment to nodes[1]
9609 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9610 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9611 check_added_monitors!(nodes[0], 1);
9613 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9614 assert_eq!(events.len(), 1);
9615 let payment_event = SendEvent::from_event(events.pop().unwrap());
9616 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9617 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9619 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9621 // Next send a payment which is forwarded by nodes[1]
9622 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9623 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9624 check_added_monitors!(nodes[0], 1);
9626 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9627 assert_eq!(events.len(), 1);
9628 let payment_event = SendEvent::from_event(events.pop().unwrap());
9629 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9630 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9632 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9634 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9636 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9637 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9638 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9640 let nodes_1_serialized = nodes[1].node.encode();
9641 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9642 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9643 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9644 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9646 persister = test_utils::TestPersister::new();
9647 let keys_manager = &chanmon_cfgs[1].keys_manager;
9648 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);
9649 nodes[1].chain_monitor = &new_chain_monitor;
9651 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9652 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9653 &mut chan_0_monitor_read, keys_manager).unwrap();
9654 assert!(chan_0_monitor_read.is_empty());
9655 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9656 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9657 &mut chan_1_monitor_read, keys_manager).unwrap();
9658 assert!(chan_1_monitor_read.is_empty());
9660 let mut nodes_1_read = &nodes_1_serialized[..];
9661 let (_, nodes_1_deserialized_tmp) = {
9662 let mut channel_monitors = HashMap::new();
9663 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9664 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9665 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9666 default_config: UserConfig::default(),
9668 fee_estimator: node_cfgs[1].fee_estimator,
9669 chain_monitor: nodes[1].chain_monitor,
9670 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9671 logger: nodes[1].logger,
9675 nodes_1_deserialized = nodes_1_deserialized_tmp;
9676 assert!(nodes_1_read.is_empty());
9678 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9679 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9680 nodes[1].node = &nodes_1_deserialized;
9681 check_added_monitors!(nodes[1], 2);
9683 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9684 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9685 // the commitment state.
9686 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9688 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9690 expect_pending_htlcs_forwardable!(nodes[1]);
9691 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9692 check_added_monitors!(nodes[1], 1);
9694 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9695 assert_eq!(events.len(), 1);
9696 let payment_event = SendEvent::from_event(events.pop().unwrap());
9697 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9698 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9699 expect_pending_htlcs_forwardable!(nodes[2]);
9700 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9702 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9703 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9706 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9707 let chanmon_cfgs = create_chanmon_cfgs(2);
9708 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9709 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9710 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9712 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9714 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9715 .with_features(InvoiceFeatures::known());
9716 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9718 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9721 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9722 check_added_monitors!(nodes[0], 1);
9723 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9724 assert_eq!(events.len(), 1);
9725 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9726 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9727 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9729 expect_pending_htlcs_forwardable!(nodes[1]);
9730 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9733 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9734 check_added_monitors!(nodes[0], 1);
9735 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9736 assert_eq!(events.len(), 1);
9737 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9739 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9740 // At this point, nodes[1] would notice it has too much value for the payment. It will
9741 // assume the second is a privacy attack (no longer particularly relevant
9742 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9743 // the first HTLC delivered above.
9746 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9747 nodes[1].node.process_pending_htlc_forwards();
9749 if test_for_second_fail_panic {
9750 // Now we go fail back the first HTLC from the user end.
9751 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9753 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9754 nodes[1].node.process_pending_htlc_forwards();
9756 check_added_monitors!(nodes[1], 1);
9757 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9758 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9760 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9761 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9762 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9764 let failure_events = nodes[0].node.get_and_clear_pending_events();
9765 assert_eq!(failure_events.len(), 2);
9766 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9767 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9769 // Let the second HTLC fail and claim the first
9770 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9771 nodes[1].node.process_pending_htlc_forwards();
9773 check_added_monitors!(nodes[1], 1);
9774 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9775 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9776 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9778 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9780 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9785 fn test_dup_htlc_second_fail_panic() {
9786 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9787 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9788 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9789 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9790 do_test_dup_htlc_second_rejected(true);
9794 fn test_dup_htlc_second_rejected() {
9795 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9796 // simply reject the second HTLC but are still able to claim the first HTLC.
9797 do_test_dup_htlc_second_rejected(false);
9801 fn test_inconsistent_mpp_params() {
9802 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9803 // such HTLC and allow the second to stay.
9804 let chanmon_cfgs = create_chanmon_cfgs(4);
9805 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9806 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9807 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9809 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9810 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9811 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9812 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9814 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9815 .with_features(InvoiceFeatures::known());
9816 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9817 assert_eq!(route.paths.len(), 2);
9818 route.paths.sort_by(|path_a, _| {
9819 // Sort the path so that the path through nodes[1] comes first
9820 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9821 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9823 let payment_params_opt = Some(payment_params);
9825 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9827 let cur_height = nodes[0].best_block_info().1;
9828 let payment_id = PaymentId([42; 32]);
9830 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();
9831 check_added_monitors!(nodes[0], 1);
9833 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9834 assert_eq!(events.len(), 1);
9835 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9837 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9840 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();
9841 check_added_monitors!(nodes[0], 1);
9843 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9844 assert_eq!(events.len(), 1);
9845 let payment_event = SendEvent::from_event(events.pop().unwrap());
9847 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9848 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9850 expect_pending_htlcs_forwardable!(nodes[2]);
9851 check_added_monitors!(nodes[2], 1);
9853 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9854 assert_eq!(events.len(), 1);
9855 let payment_event = SendEvent::from_event(events.pop().unwrap());
9857 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9858 check_added_monitors!(nodes[3], 0);
9859 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9861 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9862 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9863 // post-payment_secrets) and fail back the new HTLC.
9865 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9866 nodes[3].node.process_pending_htlc_forwards();
9867 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9868 nodes[3].node.process_pending_htlc_forwards();
9870 check_added_monitors!(nodes[3], 1);
9872 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9873 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9874 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9876 expect_pending_htlcs_forwardable!(nodes[2]);
9877 check_added_monitors!(nodes[2], 1);
9879 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9880 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9881 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9883 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9885 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();
9886 check_added_monitors!(nodes[0], 1);
9888 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9889 assert_eq!(events.len(), 1);
9890 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9892 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9896 fn test_keysend_payments_to_public_node() {
9897 let chanmon_cfgs = create_chanmon_cfgs(2);
9898 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9899 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9900 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9902 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9903 let network_graph = nodes[0].network_graph;
9904 let payer_pubkey = nodes[0].node.get_our_node_id();
9905 let payee_pubkey = nodes[1].node.get_our_node_id();
9906 let route_params = RouteParameters {
9907 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9908 final_value_msat: 10000,
9909 final_cltv_expiry_delta: 40,
9911 let scorer = test_utils::TestScorer::with_penalty(0);
9912 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9913 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9915 let test_preimage = PaymentPreimage([42; 32]);
9916 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9917 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 let event = events.pop().unwrap();
9921 let path = vec![&nodes[1]];
9922 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9923 claim_payment(&nodes[0], &path, test_preimage);
9927 fn test_keysend_payments_to_private_node() {
9928 let chanmon_cfgs = create_chanmon_cfgs(2);
9929 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9930 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9931 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9933 let payer_pubkey = nodes[0].node.get_our_node_id();
9934 let payee_pubkey = nodes[1].node.get_our_node_id();
9935 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9936 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9938 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9939 let route_params = RouteParameters {
9940 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9941 final_value_msat: 10000,
9942 final_cltv_expiry_delta: 40,
9944 let network_graph = nodes[0].network_graph;
9945 let first_hops = nodes[0].node.list_usable_channels();
9946 let scorer = test_utils::TestScorer::with_penalty(0);
9947 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9948 let route = find_route(
9949 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9950 nodes[0].logger, &scorer, &random_seed_bytes
9953 let test_preimage = PaymentPreimage([42; 32]);
9954 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9955 check_added_monitors!(nodes[0], 1);
9956 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9957 assert_eq!(events.len(), 1);
9958 let event = events.pop().unwrap();
9959 let path = vec![&nodes[1]];
9960 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9961 claim_payment(&nodes[0], &path, test_preimage);
9965 fn test_double_partial_claim() {
9966 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9967 // time out, the sender resends only some of the MPP parts, then the user processes the
9968 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9970 let chanmon_cfgs = create_chanmon_cfgs(4);
9971 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9972 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9973 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9975 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9976 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9977 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9978 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9980 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9981 assert_eq!(route.paths.len(), 2);
9982 route.paths.sort_by(|path_a, _| {
9983 // Sort the path so that the path through nodes[1] comes first
9984 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9985 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9988 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9989 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9990 // amount of time to respond to.
9992 // Connect some blocks to time out the payment
9993 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9994 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9996 expect_pending_htlcs_forwardable!(nodes[3]);
9998 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10000 // nodes[1] now retries one of the two paths...
10001 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10002 check_added_monitors!(nodes[0], 2);
10004 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10005 assert_eq!(events.len(), 2);
10006 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10008 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10009 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10010 nodes[3].node.claim_funds(payment_preimage);
10011 check_added_monitors!(nodes[3], 0);
10012 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10015 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10016 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10017 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10018 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10019 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10020 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10021 // not have the preimage tied to the still-pending HTLC.
10023 // To get to the correct state, on startup we should propagate the preimage to the
10024 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10025 // receiving the preimage without a state update.
10027 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10028 // definitely claimed.
10029 let chanmon_cfgs = create_chanmon_cfgs(4);
10030 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10031 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10033 let persister: test_utils::TestPersister;
10034 let new_chain_monitor: test_utils::TestChainMonitor;
10035 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10037 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10039 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10040 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10041 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10042 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10044 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10045 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10046 assert_eq!(route.paths.len(), 2);
10047 route.paths.sort_by(|path_a, _| {
10048 // Sort the path so that the path through nodes[1] comes first
10049 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10050 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10053 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10054 check_added_monitors!(nodes[0], 2);
10056 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10057 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10058 assert_eq!(send_events.len(), 2);
10059 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);
10060 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);
10062 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10063 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10064 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10065 if !persist_both_monitors {
10066 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10067 if outpoint.to_channel_id() == chan_id_not_persisted {
10068 assert!(original_monitor.0.is_empty());
10069 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10074 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10075 nodes[3].node.write(&mut original_manager).unwrap();
10077 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10079 nodes[3].node.claim_funds(payment_preimage);
10080 check_added_monitors!(nodes[3], 2);
10081 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10083 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10084 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10085 // with the old ChannelManager.
10086 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10087 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10088 if outpoint.to_channel_id() == chan_id_persisted {
10089 assert!(updated_monitor.0.is_empty());
10090 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10093 // If `persist_both_monitors` is set, get the second monitor here as well
10094 if persist_both_monitors {
10095 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10096 if outpoint.to_channel_id() == chan_id_not_persisted {
10097 assert!(original_monitor.0.is_empty());
10098 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10103 // Now restart nodes[3].
10104 persister = test_utils::TestPersister::new();
10105 let keys_manager = &chanmon_cfgs[3].keys_manager;
10106 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);
10107 nodes[3].chain_monitor = &new_chain_monitor;
10108 let mut monitors = Vec::new();
10109 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10110 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10111 monitors.push(deserialized_monitor);
10114 let config = UserConfig::default();
10115 nodes_3_deserialized = {
10116 let mut channel_monitors = HashMap::new();
10117 for monitor in monitors.iter_mut() {
10118 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10120 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10121 default_config: config,
10123 fee_estimator: node_cfgs[3].fee_estimator,
10124 chain_monitor: nodes[3].chain_monitor,
10125 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10126 logger: nodes[3].logger,
10130 nodes[3].node = &nodes_3_deserialized;
10132 for monitor in monitors {
10133 // On startup the preimage should have been copied into the non-persisted monitor:
10134 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10135 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10137 check_added_monitors!(nodes[3], 2);
10139 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10140 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10142 // During deserialization, we should have closed one channel and broadcast its latest
10143 // commitment transaction. We should also still have the original PaymentReceived event we
10144 // never finished processing.
10145 let events = nodes[3].node.get_and_clear_pending_events();
10146 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10147 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10148 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10149 if persist_both_monitors {
10150 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10153 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10154 // ChannelManager prior to handling the original one.
10155 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10156 events[if persist_both_monitors { 3 } else { 2 }]
10158 assert_eq!(payment_hash, our_payment_hash);
10159 } else { panic!(); }
10161 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10162 if !persist_both_monitors {
10163 // If one of the two channels is still live, reveal the payment preimage over it.
10165 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10166 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10167 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10168 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10170 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10171 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10172 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10174 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10176 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10177 // claim should fly.
10178 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10179 check_added_monitors!(nodes[3], 1);
10180 assert_eq!(ds_msgs.len(), 2);
10181 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10183 let cs_updates = match ds_msgs[0] {
10184 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10185 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10186 check_added_monitors!(nodes[2], 1);
10187 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10188 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10189 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10195 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10196 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10197 expect_payment_sent!(nodes[0], payment_preimage);
10202 fn test_partial_claim_before_restart() {
10203 do_test_partial_claim_before_restart(false);
10204 do_test_partial_claim_before_restart(true);
10207 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10208 #[derive(Clone, Copy, PartialEq)]
10209 enum ExposureEvent {
10210 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10212 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10214 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10215 AtUpdateFeeOutbound,
10218 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10219 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10222 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10223 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10224 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10225 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10226 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10227 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10228 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10229 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10231 let chanmon_cfgs = create_chanmon_cfgs(2);
10232 let mut config = test_default_channel_config();
10233 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10234 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10235 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10236 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10238 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10239 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10240 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10241 open_channel.max_accepted_htlcs = 60;
10243 open_channel.dust_limit_satoshis = 546;
10245 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10246 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10247 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10249 let opt_anchors = false;
10251 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10254 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10255 chan.holder_dust_limit_satoshis = 546;
10259 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10260 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()));
10261 check_added_monitors!(nodes[1], 1);
10263 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()));
10264 check_added_monitors!(nodes[0], 1);
10266 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10267 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10268 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10270 let dust_buffer_feerate = {
10271 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10272 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10273 chan.get_dust_buffer_feerate(None) as u64
10275 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;
10276 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10278 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;
10279 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10281 let dust_htlc_on_counterparty_tx: u64 = 25;
10282 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10285 if dust_outbound_balance {
10286 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10287 // Outbound dust balance: 4372 sats
10288 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10289 for i in 0..dust_outbound_htlc_on_holder_tx {
10290 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10291 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10294 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10295 // Inbound dust balance: 4372 sats
10296 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10297 for _ in 0..dust_inbound_htlc_on_holder_tx {
10298 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10302 if dust_outbound_balance {
10303 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10304 // Outbound dust balance: 5000 sats
10305 for i in 0..dust_htlc_on_counterparty_tx {
10306 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10307 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10310 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10311 // Inbound dust balance: 5000 sats
10312 for _ in 0..dust_htlc_on_counterparty_tx {
10313 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10318 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10319 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10320 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 });
10321 let mut config = UserConfig::default();
10322 // With default dust exposure: 5000 sats
10324 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10325 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10326 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)));
10328 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)));
10330 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10331 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 });
10332 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10333 check_added_monitors!(nodes[1], 1);
10334 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10335 assert_eq!(events.len(), 1);
10336 let payment_event = SendEvent::from_event(events.remove(0));
10337 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10338 // With default dust exposure: 5000 sats
10340 // Outbound dust balance: 6399 sats
10341 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10342 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10343 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);
10345 // Outbound dust balance: 5200 sats
10346 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);
10348 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10349 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10350 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10352 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10353 *feerate_lock = *feerate_lock * 10;
10355 nodes[0].node.timer_tick_occurred();
10356 check_added_monitors!(nodes[0], 1);
10357 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);
10360 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10361 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10362 added_monitors.clear();
10366 fn test_max_dust_htlc_exposure() {
10367 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10368 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10369 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10370 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10371 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10372 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10373 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10374 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10375 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10376 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10377 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10378 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10382 fn test_non_final_funding_tx() {
10383 let chanmon_cfgs = create_chanmon_cfgs(2);
10384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10386 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10388 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10389 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10390 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10391 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10392 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10394 let best_height = nodes[0].node.best_block.read().unwrap().height();
10396 let chan_id = *nodes[0].network_chan_count.borrow();
10397 let events = nodes[0].node.get_and_clear_pending_events();
10398 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10399 assert_eq!(events.len(), 1);
10400 let mut tx = match events[0] {
10401 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10402 // Timelock the transaction _beyond_ the best client height + 2.
10403 Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10404 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10407 _ => panic!("Unexpected event"),
10409 // Transaction should fail as it's evaluated as non-final for propagation.
10410 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10411 Err(APIError::APIMisuseError { err }) => {
10412 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10417 // However, transaction should be accepted if it's in a +2 headroom from best block.
10419 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10420 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());