1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::gossip::NetworkGraph;
27 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, OptionalField, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
45 use bitcoin::secp256k1::Secp256k1;
46 use bitcoin::secp256k1::{PublicKey,SecretKey};
52 use alloc::collections::BTreeSet;
53 use core::default::Default;
54 use sync::{Arc, Mutex};
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
60 fn test_insane_channel_opens() {
61 // Stand up a network of 2 nodes
62 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
63 let mut cfg = UserConfig::default();
64 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
65 let chanmon_cfgs = create_chanmon_cfgs(2);
66 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
67 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
68 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
70 // Instantiate channel parameters where we push the maximum msats given our
72 let channel_value_sat = 31337; // same as funding satoshis
73 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
74 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
76 // Have node0 initiate a channel to node1 with aforementioned parameters
77 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
79 // Extract the channel open message from node0 to node1
80 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
82 // Test helper that asserts we get the correct error string given a mutator
83 // that supposedly makes the channel open message insane
84 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
85 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
86 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
87 assert_eq!(msg_events.len(), 1);
88 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
89 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
91 &ErrorAction::SendErrorMessage { .. } => {
92 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
94 _ => panic!("unexpected event!"),
96 } else { assert!(false); }
99 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
101 // Test all mutations that would make the channel open message insane
102 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 });
103 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 });
105 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
107 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 });
109 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
111 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 });
113 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 });
115 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
117 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 fn test_funding_exceeds_no_wumbo_limit() {
122 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
124 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
125 let chanmon_cfgs = create_chanmon_cfgs(2);
126 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
127 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
129 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
131 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
132 Err(APIError::APIMisuseError { err }) => {
133 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
139 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
140 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
141 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
142 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
143 // in normal testing, we test it explicitly here.
144 let chanmon_cfgs = create_chanmon_cfgs(2);
145 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
146 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
147 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
149 // Have node0 initiate a channel to node1 with aforementioned parameters
150 let mut push_amt = 100_000_000;
151 let feerate_per_kw = 253;
152 let opt_anchors = false;
153 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
154 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
156 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();
157 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
158 if !send_from_initiator {
159 open_channel_message.channel_reserve_satoshis = 0;
160 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
162 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
164 // Extract the channel accept message from node1 to node0
165 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
166 if send_from_initiator {
167 accept_channel_message.channel_reserve_satoshis = 0;
168 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
170 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
173 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
174 chan.holder_selected_channel_reserve_satoshis = 0;
175 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
178 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
179 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
180 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
182 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
183 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
184 if send_from_initiator {
185 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
186 // Note that for outbound channels we have to consider the commitment tx fee and the
187 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
188 // well as an additional HTLC.
189 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
191 send_payment(&nodes[1], &[&nodes[0]], push_amt);
196 fn test_counterparty_no_reserve() {
197 do_test_counterparty_no_reserve(true);
198 do_test_counterparty_no_reserve(false);
202 fn test_async_inbound_update_fee() {
203 let chanmon_cfgs = create_chanmon_cfgs(2);
204 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
205 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
206 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
207 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
210 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
214 // send (1) commitment_signed -.
215 // <- update_add_htlc/commitment_signed
216 // send (2) RAA (awaiting remote revoke) -.
217 // (1) commitment_signed is delivered ->
218 // .- send (3) RAA (awaiting remote revoke)
219 // (2) RAA is delivered ->
220 // .- send (4) commitment_signed
221 // <- (3) RAA is delivered
222 // send (5) commitment_signed -.
223 // <- (4) commitment_signed is delivered
225 // (5) commitment_signed is delivered ->
227 // (6) RAA is delivered ->
229 // First nodes[0] generates an update_fee
231 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
234 nodes[0].node.timer_tick_occurred();
235 check_added_monitors!(nodes[0], 1);
237 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
238 assert_eq!(events_0.len(), 1);
239 let (update_msg, commitment_signed) = match events_0[0] { // (1)
240 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
241 (update_fee.as_ref(), commitment_signed)
243 _ => panic!("Unexpected event"),
246 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
248 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
249 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
250 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
251 check_added_monitors!(nodes[1], 1);
253 let payment_event = {
254 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
255 assert_eq!(events_1.len(), 1);
256 SendEvent::from_event(events_1.remove(0))
258 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
259 assert_eq!(payment_event.msgs.len(), 1);
261 // ...now when the messages get delivered everyone should be happy
262 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
263 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
264 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
265 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
266 check_added_monitors!(nodes[0], 1);
268 // deliver(1), generate (3):
269 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
270 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
271 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[1], 1);
274 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
275 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
276 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
277 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
278 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
279 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
280 assert!(bs_update.update_fee.is_none()); // (4)
281 check_added_monitors!(nodes[1], 1);
283 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
284 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
285 assert!(as_update.update_add_htlcs.is_empty()); // (5)
286 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
287 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
288 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
289 assert!(as_update.update_fee.is_none()); // (5)
290 check_added_monitors!(nodes[0], 1);
292 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
293 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
294 // only (6) so get_event_msg's assert(len == 1) passes
295 check_added_monitors!(nodes[0], 1);
297 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
298 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
299 check_added_monitors!(nodes[1], 1);
301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
302 check_added_monitors!(nodes[0], 1);
304 let events_2 = nodes[0].node.get_and_clear_pending_events();
305 assert_eq!(events_2.len(), 1);
307 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
308 _ => panic!("Unexpected event"),
311 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
312 check_added_monitors!(nodes[1], 1);
316 fn test_update_fee_unordered_raa() {
317 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
318 // crash in an earlier version of the update_fee patch)
319 let chanmon_cfgs = create_chanmon_cfgs(2);
320 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
321 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
322 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
323 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
326 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
328 // First nodes[0] generates an update_fee
330 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
333 nodes[0].node.timer_tick_occurred();
334 check_added_monitors!(nodes[0], 1);
336 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
337 assert_eq!(events_0.len(), 1);
338 let update_msg = match events_0[0] { // (1)
339 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
342 _ => panic!("Unexpected event"),
345 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
347 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
348 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
349 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
350 check_added_monitors!(nodes[1], 1);
352 let payment_event = {
353 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
354 assert_eq!(events_1.len(), 1);
355 SendEvent::from_event(events_1.remove(0))
357 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
358 assert_eq!(payment_event.msgs.len(), 1);
360 // ...now when the messages get delivered everyone should be happy
361 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
362 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
363 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
364 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
365 check_added_monitors!(nodes[0], 1);
367 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
368 check_added_monitors!(nodes[1], 1);
370 // We can't continue, sadly, because our (1) now has a bogus signature
374 fn test_multi_flight_update_fee() {
375 let chanmon_cfgs = create_chanmon_cfgs(2);
376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
378 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
379 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
382 // update_fee/commitment_signed ->
383 // .- send (1) RAA and (2) commitment_signed
384 // update_fee (never committed) ->
386 // We have to manually generate the above update_fee, it is allowed by the protocol but we
387 // don't track which updates correspond to which revoke_and_ack responses so we're in
388 // AwaitingRAA mode and will not generate the update_fee yet.
389 // <- (1) RAA delivered
390 // (3) is generated and send (4) CS -.
391 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
392 // know the per_commitment_point to use for it.
393 // <- (2) commitment_signed delivered
395 // B should send no response here
396 // (4) commitment_signed delivered ->
397 // <- RAA/commitment_signed delivered
400 // First nodes[0] generates an update_fee
403 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
404 initial_feerate = *feerate_lock;
405 *feerate_lock = initial_feerate + 20;
407 nodes[0].node.timer_tick_occurred();
408 check_added_monitors!(nodes[0], 1);
410 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
411 assert_eq!(events_0.len(), 1);
412 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
413 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
414 (update_fee.as_ref().unwrap(), commitment_signed)
416 _ => panic!("Unexpected event"),
419 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
420 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
421 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
422 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
423 check_added_monitors!(nodes[1], 1);
425 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
428 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
429 *feerate_lock = initial_feerate + 40;
431 nodes[0].node.timer_tick_occurred();
432 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
433 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
435 // Create the (3) update_fee message that nodes[0] will generate before it does...
436 let mut update_msg_2 = msgs::UpdateFee {
437 channel_id: update_msg_1.channel_id.clone(),
438 feerate_per_kw: (initial_feerate + 30) as u32,
441 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
443 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
445 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
447 // Deliver (1), generating (3) and (4)
448 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
449 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
450 check_added_monitors!(nodes[0], 1);
451 assert!(as_second_update.update_add_htlcs.is_empty());
452 assert!(as_second_update.update_fulfill_htlcs.is_empty());
453 assert!(as_second_update.update_fail_htlcs.is_empty());
454 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
455 // Check that the update_fee newly generated matches what we delivered:
456 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
457 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
459 // Deliver (2) commitment_signed
460 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
461 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
462 check_added_monitors!(nodes[0], 1);
463 // No commitment_signed so get_event_msg's assert(len == 1) passes
465 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
466 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
467 check_added_monitors!(nodes[1], 1);
470 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
471 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
472 check_added_monitors!(nodes[1], 1);
474 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
475 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
476 check_added_monitors!(nodes[0], 1);
478 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
479 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
480 // No commitment_signed so get_event_msg's assert(len == 1) passes
481 check_added_monitors!(nodes[0], 1);
483 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
484 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
485 check_added_monitors!(nodes[1], 1);
488 fn do_test_sanity_on_in_flight_opens(steps: u8) {
489 // Previously, we had issues deserializing channels when we hadn't connected the first block
490 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
491 // serialization round-trips and simply do steps towards opening a channel and then drop the
494 let chanmon_cfgs = create_chanmon_cfgs(2);
495 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
496 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
497 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
499 if steps & 0b1000_0000 != 0{
501 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
504 connect_block(&nodes[0], &block);
505 connect_block(&nodes[1], &block);
508 if steps & 0x0f == 0 { return; }
509 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
510 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
512 if steps & 0x0f == 1 { return; }
513 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
514 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
516 if steps & 0x0f == 2 { return; }
517 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
519 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
521 if steps & 0x0f == 3 { return; }
522 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
523 check_added_monitors!(nodes[0], 0);
524 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
526 if steps & 0x0f == 4 { return; }
527 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
529 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
530 assert_eq!(added_monitors.len(), 1);
531 assert_eq!(added_monitors[0].0, funding_output);
532 added_monitors.clear();
534 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
536 if steps & 0x0f == 5 { return; }
537 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
539 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
540 assert_eq!(added_monitors.len(), 1);
541 assert_eq!(added_monitors[0].0, funding_output);
542 added_monitors.clear();
545 let events_4 = nodes[0].node.get_and_clear_pending_events();
546 assert_eq!(events_4.len(), 0);
548 if steps & 0x0f == 6 { return; }
549 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
551 if steps & 0x0f == 7 { return; }
552 confirm_transaction_at(&nodes[0], &tx, 2);
553 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
554 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
558 fn test_sanity_on_in_flight_opens() {
559 do_test_sanity_on_in_flight_opens(0);
560 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
561 do_test_sanity_on_in_flight_opens(1);
562 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
563 do_test_sanity_on_in_flight_opens(2);
564 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
565 do_test_sanity_on_in_flight_opens(3);
566 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
567 do_test_sanity_on_in_flight_opens(4);
568 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
569 do_test_sanity_on_in_flight_opens(5);
570 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(6);
572 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(7);
574 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(8);
576 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
580 fn test_update_fee_vanilla() {
581 let chanmon_cfgs = create_chanmon_cfgs(2);
582 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
583 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
584 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
585 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
588 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
591 nodes[0].node.timer_tick_occurred();
592 check_added_monitors!(nodes[0], 1);
594 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
595 assert_eq!(events_0.len(), 1);
596 let (update_msg, commitment_signed) = match events_0[0] {
597 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 } } => {
598 (update_fee.as_ref(), commitment_signed)
600 _ => panic!("Unexpected event"),
602 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
604 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
605 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
606 check_added_monitors!(nodes[1], 1);
608 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
609 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
610 check_added_monitors!(nodes[0], 1);
612 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
613 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
614 // No commitment_signed so get_event_msg's assert(len == 1) passes
615 check_added_monitors!(nodes[0], 1);
617 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
618 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
619 check_added_monitors!(nodes[1], 1);
623 fn test_update_fee_that_funder_cannot_afford() {
624 let chanmon_cfgs = create_chanmon_cfgs(2);
625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
627 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
628 let channel_value = 5000;
630 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
631 let channel_id = chan.2;
632 let secp_ctx = Secp256k1::new();
633 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
635 let opt_anchors = false;
637 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
638 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
639 // calculate two different feerates here - the expected local limit as well as the expected
641 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;
642 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
644 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
645 *feerate_lock = feerate;
647 nodes[0].node.timer_tick_occurred();
648 check_added_monitors!(nodes[0], 1);
649 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
651 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
653 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
655 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
657 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
659 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
660 assert_eq!(commitment_tx.output.len(), 2);
661 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
662 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
663 actual_fee = channel_value - actual_fee;
664 assert_eq!(total_fee, actual_fee);
668 // Increment the feerate by a small constant, accounting for rounding errors
669 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
672 nodes[0].node.timer_tick_occurred();
673 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
674 check_added_monitors!(nodes[0], 0);
676 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
678 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
679 // needed to sign the new commitment tx and (2) sign the new commitment tx.
680 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
681 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
682 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
683 let chan_signer = local_chan.get_signer();
684 let pubkeys = chan_signer.pubkeys();
685 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
686 pubkeys.funding_pubkey)
688 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
689 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
690 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
691 let chan_signer = remote_chan.get_signer();
692 let pubkeys = chan_signer.pubkeys();
693 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
694 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
695 pubkeys.funding_pubkey)
698 // Assemble the set of keys we can use for signatures for our commitment_signed message.
699 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
700 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
703 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
704 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
705 let local_chan_signer = local_chan.get_signer();
706 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
707 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
708 INITIAL_COMMITMENT_NUMBER - 1,
710 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
711 opt_anchors, local_funding, remote_funding,
712 commit_tx_keys.clone(),
713 non_buffer_feerate + 4,
715 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
717 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
720 let commit_signed_msg = msgs::CommitmentSigned {
723 htlc_signatures: res.1
726 let update_fee = msgs::UpdateFee {
728 feerate_per_kw: non_buffer_feerate + 4,
731 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
733 //While producing the commitment_signed response after handling a received update_fee request the
734 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
735 //Should produce and error.
736 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
737 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
738 check_added_monitors!(nodes[1], 1);
739 check_closed_broadcast!(nodes[1], true);
740 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
744 fn test_update_fee_with_fundee_update_add_htlc() {
745 let chanmon_cfgs = create_chanmon_cfgs(2);
746 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
747 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
748 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
749 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
752 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
755 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
758 nodes[0].node.timer_tick_occurred();
759 check_added_monitors!(nodes[0], 1);
761 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
762 assert_eq!(events_0.len(), 1);
763 let (update_msg, commitment_signed) = match events_0[0] {
764 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 } } => {
765 (update_fee.as_ref(), commitment_signed)
767 _ => panic!("Unexpected event"),
769 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
770 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
771 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
772 check_added_monitors!(nodes[1], 1);
774 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
776 // nothing happens since node[1] is in AwaitingRemoteRevoke
777 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
779 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
780 assert_eq!(added_monitors.len(), 0);
781 added_monitors.clear();
783 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
784 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
785 // node[1] has nothing to do
787 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
788 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
789 check_added_monitors!(nodes[0], 1);
791 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
792 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
793 // No commitment_signed so get_event_msg's assert(len == 1) passes
794 check_added_monitors!(nodes[0], 1);
795 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
796 check_added_monitors!(nodes[1], 1);
797 // AwaitingRemoteRevoke ends here
799 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
800 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
801 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
802 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
803 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
804 assert_eq!(commitment_update.update_fee.is_none(), true);
806 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
807 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
808 check_added_monitors!(nodes[0], 1);
809 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
811 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
812 check_added_monitors!(nodes[1], 1);
813 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
815 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
816 check_added_monitors!(nodes[1], 1);
817 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
818 // No commitment_signed so get_event_msg's assert(len == 1) passes
820 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
821 check_added_monitors!(nodes[0], 1);
822 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824 expect_pending_htlcs_forwardable!(nodes[0]);
826 let events = nodes[0].node.get_and_clear_pending_events();
827 assert_eq!(events.len(), 1);
829 Event::PaymentReceived { .. } => { },
830 _ => panic!("Unexpected event"),
833 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
835 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
836 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
837 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
838 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
839 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
843 fn test_update_fee() {
844 let chanmon_cfgs = create_chanmon_cfgs(2);
845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
847 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
848 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
849 let channel_id = chan.2;
852 // (1) update_fee/commitment_signed ->
853 // <- (2) revoke_and_ack
854 // .- send (3) commitment_signed
855 // (4) update_fee/commitment_signed ->
856 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
857 // <- (3) commitment_signed delivered
858 // send (6) revoke_and_ack -.
859 // <- (5) deliver revoke_and_ack
860 // (6) deliver revoke_and_ack ->
861 // .- send (7) commitment_signed in response to (4)
862 // <- (7) deliver commitment_signed
865 // Create and deliver (1)...
868 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
869 feerate = *feerate_lock;
870 *feerate_lock = feerate + 20;
872 nodes[0].node.timer_tick_occurred();
873 check_added_monitors!(nodes[0], 1);
875 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
876 assert_eq!(events_0.len(), 1);
877 let (update_msg, commitment_signed) = match events_0[0] {
878 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 } } => {
879 (update_fee.as_ref(), commitment_signed)
881 _ => panic!("Unexpected event"),
883 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
885 // Generate (2) and (3):
886 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
887 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
888 check_added_monitors!(nodes[1], 1);
891 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
892 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
893 check_added_monitors!(nodes[0], 1);
895 // Create and deliver (4)...
897 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
898 *feerate_lock = feerate + 30;
900 nodes[0].node.timer_tick_occurred();
901 check_added_monitors!(nodes[0], 1);
902 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
903 assert_eq!(events_0.len(), 1);
904 let (update_msg, commitment_signed) = match events_0[0] {
905 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 } } => {
906 (update_fee.as_ref(), commitment_signed)
908 _ => panic!("Unexpected event"),
911 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
912 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
913 check_added_monitors!(nodes[1], 1);
915 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
916 // No commitment_signed so get_event_msg's assert(len == 1) passes
918 // Handle (3), creating (6):
919 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
920 check_added_monitors!(nodes[0], 1);
921 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
922 // No commitment_signed so get_event_msg's assert(len == 1) passes
925 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
926 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
927 check_added_monitors!(nodes[0], 1);
929 // Deliver (6), creating (7):
930 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
931 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
932 assert!(commitment_update.update_add_htlcs.is_empty());
933 assert!(commitment_update.update_fulfill_htlcs.is_empty());
934 assert!(commitment_update.update_fail_htlcs.is_empty());
935 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
936 assert!(commitment_update.update_fee.is_none());
937 check_added_monitors!(nodes[1], 1);
940 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
941 check_added_monitors!(nodes[0], 1);
942 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
943 // No commitment_signed so get_event_msg's assert(len == 1) passes
945 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
946 check_added_monitors!(nodes[1], 1);
947 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
949 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
950 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
951 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
952 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
953 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
957 fn fake_network_test() {
958 // Simple test which builds a network of ChannelManagers, connects them to each other, and
959 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
960 let chanmon_cfgs = create_chanmon_cfgs(4);
961 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
962 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
963 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
965 // Create some initial channels
966 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
967 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
968 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
970 // Rebalance the network a bit by relaying one payment through all the channels...
971 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
974 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976 // Send some more payments
977 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
978 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
979 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
981 // Test failure packets
982 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
983 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
985 // Add a new channel that skips 3
986 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
988 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
989 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
990 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
994 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996 // Do some rebalance loop payments, simultaneously
997 let mut hops = Vec::with_capacity(3);
999 pubkey: nodes[2].node.get_our_node_id(),
1000 node_features: NodeFeatures::empty(),
1001 short_channel_id: chan_2.0.contents.short_channel_id,
1002 channel_features: ChannelFeatures::empty(),
1004 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1006 hops.push(RouteHop {
1007 pubkey: nodes[3].node.get_our_node_id(),
1008 node_features: NodeFeatures::empty(),
1009 short_channel_id: chan_3.0.contents.short_channel_id,
1010 channel_features: ChannelFeatures::empty(),
1012 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1014 hops.push(RouteHop {
1015 pubkey: nodes[1].node.get_our_node_id(),
1016 node_features: NodeFeatures::known(),
1017 short_channel_id: chan_4.0.contents.short_channel_id,
1018 channel_features: ChannelFeatures::known(),
1020 cltv_expiry_delta: TEST_FINAL_CLTV,
1022 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;
1023 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;
1024 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;
1026 let mut hops = Vec::with_capacity(3);
1027 hops.push(RouteHop {
1028 pubkey: nodes[3].node.get_our_node_id(),
1029 node_features: NodeFeatures::empty(),
1030 short_channel_id: chan_4.0.contents.short_channel_id,
1031 channel_features: ChannelFeatures::empty(),
1033 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1035 hops.push(RouteHop {
1036 pubkey: nodes[2].node.get_our_node_id(),
1037 node_features: NodeFeatures::empty(),
1038 short_channel_id: chan_3.0.contents.short_channel_id,
1039 channel_features: ChannelFeatures::empty(),
1041 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1043 hops.push(RouteHop {
1044 pubkey: nodes[1].node.get_our_node_id(),
1045 node_features: NodeFeatures::known(),
1046 short_channel_id: chan_2.0.contents.short_channel_id,
1047 channel_features: ChannelFeatures::known(),
1049 cltv_expiry_delta: TEST_FINAL_CLTV,
1051 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;
1052 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;
1053 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;
1055 // Claim the rebalances...
1056 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1057 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1059 // Add a duplicate new channel from 2 to 4
1060 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1062 // Send some payments across both channels
1063 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1065 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1068 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1069 let events = nodes[0].node.get_and_clear_pending_msg_events();
1070 assert_eq!(events.len(), 0);
1071 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);
1073 //TODO: Test that routes work again here as we've been notified that the channel is full
1075 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1076 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1077 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1079 // Close down the channels...
1080 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1081 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1082 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1083 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1084 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1086 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1087 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1089 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1090 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1091 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1093 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1094 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1098 fn holding_cell_htlc_counting() {
1099 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1100 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1101 // commitment dance rounds.
1102 let chanmon_cfgs = create_chanmon_cfgs(3);
1103 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1104 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1105 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1106 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1107 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1109 let mut payments = Vec::new();
1110 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1111 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1112 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1113 payments.push((payment_preimage, payment_hash));
1115 check_added_monitors!(nodes[1], 1);
1117 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1122 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1123 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1125 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1127 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1128 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1129 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1130 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1133 // This should also be true if we try to forward a payment.
1134 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1136 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141 assert_eq!(events.len(), 1);
1142 let payment_event = SendEvent::from_event(events.pop().unwrap());
1143 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148 // fails), the second will process the resulting failure and fail the HTLC backward.
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 expect_pending_htlcs_forwardable!(nodes[1]);
1151 check_added_monitors!(nodes[1], 1);
1153 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1157 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1159 // Now forward all the pending HTLCs and claim them back
1160 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 for ref update in as_updates.update_add_htlcs.iter() {
1174 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1176 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177 check_added_monitors!(nodes[2], 1);
1178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179 check_added_monitors!(nodes[2], 1);
1180 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183 check_added_monitors!(nodes[1], 1);
1184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185 check_added_monitors!(nodes[1], 1);
1186 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1188 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189 check_added_monitors!(nodes[2], 1);
1191 expect_pending_htlcs_forwardable!(nodes[2]);
1193 let events = nodes[2].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), payments.len());
1195 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1197 &Event::PaymentReceived { ref payment_hash, .. } => {
1198 assert_eq!(*payment_hash, *hash);
1200 _ => panic!("Unexpected event"),
1204 for (preimage, _) in payments.drain(..) {
1205 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 fn duplicate_htlc_test() {
1213 // Test that we accept duplicate payment_hash HTLCs across the network and that
1214 // claiming/failing them are all separate and don't affect each other
1215 let chanmon_cfgs = create_chanmon_cfgs(6);
1216 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1220 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1222 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1223 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1224 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1225 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1227 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1232 *nodes[0].network_payment_count.borrow_mut() -= 1;
1233 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1235 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242 // Test that ChannelMonitor doesn't generate 2 preimage txn
1243 // when we have 2 HTLCs with same preimage that go across a node
1244 // in opposite directions, even with the same payment secret.
1245 let chanmon_cfgs = create_chanmon_cfgs(2);
1246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1255 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1257 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1259 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1261 // Provide preimage to node 0 by claiming payment
1262 nodes[0].node.claim_funds(payment_preimage);
1263 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264 check_added_monitors!(nodes[0], 1);
1266 // Broadcast node 1 commitment txn
1267 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1269 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270 let mut has_both_htlcs = 0; // check htlcs match ones committed
1271 for outp in remote_txn[0].output.iter() {
1272 if outp.value == 800_000 / 1000 {
1273 has_both_htlcs += 1;
1274 } else if outp.value == 900_000 / 1000 {
1275 has_both_htlcs += 1;
1278 assert_eq!(has_both_htlcs, 2);
1280 mine_transaction(&nodes[0], &remote_txn[0]);
1281 check_added_monitors!(nodes[0], 1);
1282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 8);
1288 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1290 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1291 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1293 let bump_tx = if claim_txn[1] == claim_txn[4] {
1294 assert_eq!(claim_txn[1], claim_txn[4]);
1295 assert_eq!(claim_txn[2], claim_txn[5]);
1297 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1299 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1302 assert_eq!(claim_txn[1], claim_txn[3]);
1303 assert_eq!(claim_txn[2], claim_txn[4]);
1305 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1307 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1312 assert_eq!(claim_txn[0].input.len(), 1);
1313 assert_eq!(bump_tx.input.len(), 1);
1314 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1316 assert_eq!(claim_txn[0].input.len(), 1);
1317 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1318 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1320 assert_eq!(claim_txn[6].input.len(), 1);
1321 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1322 check_spends!(claim_txn[6], remote_txn[0]);
1323 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1325 let events = nodes[0].node.get_and_clear_pending_msg_events();
1326 assert_eq!(events.len(), 3);
1329 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1330 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1331 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1332 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1334 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, .. } } => {
1335 assert!(update_add_htlcs.is_empty());
1336 assert!(update_fail_htlcs.is_empty());
1337 assert_eq!(update_fulfill_htlcs.len(), 1);
1338 assert!(update_fail_malformed_htlcs.is_empty());
1339 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1341 _ => panic!("Unexpected event"),
1347 fn test_basic_channel_reserve() {
1348 let chanmon_cfgs = create_chanmon_cfgs(2);
1349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1352 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1354 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1355 let channel_reserve = chan_stat.channel_reserve_msat;
1357 // The 2* and +1 are for the fee spike reserve.
1358 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1359 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1360 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1361 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1363 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1365 &APIError::ChannelUnavailable{ref err} =>
1366 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1367 _ => panic!("Unexpected error variant"),
1370 _ => panic!("Unexpected error variant"),
1372 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1373 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);
1375 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1379 fn test_fee_spike_violation_fails_htlc() {
1380 let chanmon_cfgs = create_chanmon_cfgs(2);
1381 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1382 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1383 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1384 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1386 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1387 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1388 let secp_ctx = Secp256k1::new();
1389 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1391 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1393 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1394 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1395 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1396 let msg = msgs::UpdateAddHTLC {
1399 amount_msat: htlc_msat,
1400 payment_hash: payment_hash,
1401 cltv_expiry: htlc_cltv,
1402 onion_routing_packet: onion_packet,
1405 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1407 // Now manually create the commitment_signed message corresponding to the update_add
1408 // nodes[0] just sent. In the code for construction of this message, "local" refers
1409 // to the sender of the message, and "remote" refers to the receiver.
1411 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1413 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1415 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1416 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1417 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1418 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1419 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1420 let chan_signer = local_chan.get_signer();
1421 // Make the signer believe we validated another commitment, so we can release the secret
1422 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1424 let pubkeys = chan_signer.pubkeys();
1425 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1426 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1427 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1428 chan_signer.pubkeys().funding_pubkey)
1430 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1431 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1432 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1433 let chan_signer = remote_chan.get_signer();
1434 let pubkeys = chan_signer.pubkeys();
1435 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1436 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1437 chan_signer.pubkeys().funding_pubkey)
1440 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1441 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1442 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1444 // Build the remote commitment transaction so we can sign it, and then later use the
1445 // signature for the commitment_signed message.
1446 let local_chan_balance = 1313;
1448 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1450 amount_msat: 3460001,
1451 cltv_expiry: htlc_cltv,
1453 transaction_output_index: Some(1),
1456 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1459 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1460 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1461 let local_chan_signer = local_chan.get_signer();
1462 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1466 local_chan.opt_anchors(), local_funding, remote_funding,
1467 commit_tx_keys.clone(),
1469 &mut vec![(accepted_htlc_info, ())],
1470 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1472 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1475 let commit_signed_msg = msgs::CommitmentSigned {
1478 htlc_signatures: res.1
1481 // Send the commitment_signed message to the nodes[1].
1482 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1483 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1485 // Send the RAA to nodes[1].
1486 let raa_msg = msgs::RevokeAndACK {
1488 per_commitment_secret: local_secret,
1489 next_per_commitment_point: next_local_point
1491 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1493 let events = nodes[1].node.get_and_clear_pending_msg_events();
1494 assert_eq!(events.len(), 1);
1495 // Make sure the HTLC failed in the way we expect.
1497 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1498 assert_eq!(update_fail_htlcs.len(), 1);
1499 update_fail_htlcs[0].clone()
1501 _ => panic!("Unexpected event"),
1503 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1504 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1506 check_added_monitors!(nodes[1], 2);
1510 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1511 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1512 // Set the fee rate for the channel very high, to the point where the fundee
1513 // sending any above-dust amount would result in a channel reserve violation.
1514 // In this test we check that we would be prevented from sending an HTLC in
1516 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1519 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521 let opt_anchors = false;
1523 let mut push_amt = 100_000_000;
1524 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1525 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1527 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1529 // Sending exactly enough to hit the reserve amount should be accepted
1530 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1531 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1534 // However one more HTLC should be significantly over the reserve amount and fail.
1535 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1536 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1537 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1538 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1539 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);
1543 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1544 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1545 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1550 let opt_anchors = false;
1552 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1553 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1554 // transaction fee with 0 HTLCs (183 sats)).
1555 let mut push_amt = 100_000_000;
1556 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1557 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1558 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1560 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1561 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1562 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1565 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1566 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1567 let secp_ctx = Secp256k1::new();
1568 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1569 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1570 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1571 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1572 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1573 let msg = msgs::UpdateAddHTLC {
1575 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1576 amount_msat: htlc_msat,
1577 payment_hash: payment_hash,
1578 cltv_expiry: htlc_cltv,
1579 onion_routing_packet: onion_packet,
1582 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1583 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1584 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);
1585 assert_eq!(nodes[0].node.list_channels().len(), 0);
1586 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1587 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1588 check_added_monitors!(nodes[0], 1);
1589 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() });
1593 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1594 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1595 // calculating our commitment transaction fee (this was previously broken).
1596 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1597 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1603 let opt_anchors = false;
1605 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1606 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1607 // transaction fee with 0 HTLCs (183 sats)).
1608 let mut push_amt = 100_000_000;
1609 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1610 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1611 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1613 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1614 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1615 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1616 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1617 // commitment transaction fee.
1618 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1620 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1621 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1622 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1625 // One more than the dust amt should fail, however.
1626 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1627 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1628 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1632 fn test_chan_init_feerate_unaffordability() {
1633 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1634 // channel reserve and feerate requirements.
1635 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1636 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1641 let opt_anchors = false;
1643 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1645 let mut push_amt = 100_000_000;
1646 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1647 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1648 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1650 // During open, we don't have a "counterparty channel reserve" to check against, so that
1651 // requirement only comes into play on the open_channel handling side.
1652 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1653 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1654 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1655 open_channel_msg.push_msat += 1;
1656 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1658 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1659 assert_eq!(msg_events.len(), 1);
1660 match msg_events[0] {
1661 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1662 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1664 _ => panic!("Unexpected event"),
1669 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1670 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1671 // calculating our counterparty's commitment transaction fee (this was previously broken).
1672 let chanmon_cfgs = create_chanmon_cfgs(2);
1673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1676 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1678 let payment_amt = 46000; // Dust amount
1679 // In the previous code, these first four payments would succeed.
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1693 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1694 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1695 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1700 let chanmon_cfgs = create_chanmon_cfgs(3);
1701 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1702 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1703 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1704 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1705 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1708 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1709 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1710 let feerate = get_feerate!(nodes[0], chan.2);
1711 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1713 // Add a 2* and +1 for the fee spike reserve.
1714 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1715 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;
1716 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1718 // Add a pending HTLC.
1719 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1720 let payment_event_1 = {
1721 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1722 check_added_monitors!(nodes[0], 1);
1724 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1725 assert_eq!(events.len(), 1);
1726 SendEvent::from_event(events.remove(0))
1728 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1730 // Attempt to trigger a channel reserve violation --> payment failure.
1731 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1732 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;
1733 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1734 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1736 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1737 let secp_ctx = Secp256k1::new();
1738 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1739 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1740 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1741 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1742 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1743 let msg = msgs::UpdateAddHTLC {
1746 amount_msat: htlc_msat + 1,
1747 payment_hash: our_payment_hash_1,
1748 cltv_expiry: htlc_cltv,
1749 onion_routing_packet: onion_packet,
1752 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1753 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1754 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1755 assert_eq!(nodes[1].node.list_channels().len(), 1);
1756 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1757 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1758 check_added_monitors!(nodes[1], 1);
1759 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1763 fn test_inbound_outbound_capacity_is_not_zero() {
1764 let chanmon_cfgs = create_chanmon_cfgs(2);
1765 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1766 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1767 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1768 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1769 let channels0 = node_chanmgrs[0].list_channels();
1770 let channels1 = node_chanmgrs[1].list_channels();
1771 assert_eq!(channels0.len(), 1);
1772 assert_eq!(channels1.len(), 1);
1774 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1775 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1776 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1778 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1779 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1783 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1787 fn test_channel_reserve_holding_cell_htlcs() {
1788 let chanmon_cfgs = create_chanmon_cfgs(3);
1789 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1790 // When this test was written, the default base fee floated based on the HTLC count.
1791 // It is now fixed, so we simply set the fee to the expected value here.
1792 let mut config = test_default_channel_config();
1793 config.channel_config.forwarding_fee_base_msat = 239;
1794 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1795 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1796 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1797 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1799 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1800 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1802 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1803 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1805 macro_rules! expect_forward {
1807 let mut events = $node.node.get_and_clear_pending_msg_events();
1808 assert_eq!(events.len(), 1);
1809 check_added_monitors!($node, 1);
1810 let payment_event = SendEvent::from_event(events.remove(0));
1815 let feemsat = 239; // set above
1816 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1817 let feerate = get_feerate!(nodes[0], chan_1.2);
1818 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1820 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1822 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1824 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1825 route.paths[0].last_mut().unwrap().fee_msat += 1;
1826 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1827 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1828 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)));
1829 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1830 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);
1833 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1834 // nodes[0]'s wealth
1836 let amt_msat = recv_value_0 + total_fee_msat;
1837 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1838 // Also, ensure that each payment has enough to be over the dust limit to
1839 // ensure it'll be included in each commit tx fee calculation.
1840 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1841 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1842 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1845 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1847 let (stat01_, stat11_, stat12_, stat22_) = (
1848 get_channel_value_stat!(nodes[0], chan_1.2),
1849 get_channel_value_stat!(nodes[1], chan_1.2),
1850 get_channel_value_stat!(nodes[1], chan_2.2),
1851 get_channel_value_stat!(nodes[2], chan_2.2),
1854 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1855 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1856 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1857 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1858 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1861 // adding pending output.
1862 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1863 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1864 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1865 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1866 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1867 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1868 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1869 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1870 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1872 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1873 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1874 let amt_msat_1 = recv_value_1 + total_fee_msat;
1876 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);
1877 let payment_event_1 = {
1878 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1879 check_added_monitors!(nodes[0], 1);
1881 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1882 assert_eq!(events.len(), 1);
1883 SendEvent::from_event(events.remove(0))
1885 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1887 // channel reserve test with htlc pending output > 0
1888 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1890 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1891 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1892 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1893 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1896 // split the rest to test holding cell
1897 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1898 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1899 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1900 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1902 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1903 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);
1906 // now see if they go through on both sides
1907 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);
1908 // but this will stuck in the holding cell
1909 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1910 check_added_monitors!(nodes[0], 0);
1911 let events = nodes[0].node.get_and_clear_pending_events();
1912 assert_eq!(events.len(), 0);
1914 // test with outbound holding cell amount > 0
1916 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1917 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1918 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1919 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1920 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);
1923 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);
1924 // this will also stuck in the holding cell
1925 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1926 check_added_monitors!(nodes[0], 0);
1927 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1928 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1930 // flush the pending htlc
1931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1932 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1933 check_added_monitors!(nodes[1], 1);
1935 // the pending htlc should be promoted to committed
1936 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1937 check_added_monitors!(nodes[0], 1);
1938 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1940 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1941 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1942 // No commitment_signed so get_event_msg's assert(len == 1) passes
1943 check_added_monitors!(nodes[0], 1);
1945 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1946 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1947 check_added_monitors!(nodes[1], 1);
1949 expect_pending_htlcs_forwardable!(nodes[1]);
1951 let ref payment_event_11 = expect_forward!(nodes[1]);
1952 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1953 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1955 expect_pending_htlcs_forwardable!(nodes[2]);
1956 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1958 // flush the htlcs in the holding cell
1959 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1961 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1962 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1963 expect_pending_htlcs_forwardable!(nodes[1]);
1965 let ref payment_event_3 = expect_forward!(nodes[1]);
1966 assert_eq!(payment_event_3.msgs.len(), 2);
1967 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1968 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1970 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1971 expect_pending_htlcs_forwardable!(nodes[2]);
1973 let events = nodes[2].node.get_and_clear_pending_events();
1974 assert_eq!(events.len(), 2);
1976 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1977 assert_eq!(our_payment_hash_21, *payment_hash);
1978 assert_eq!(recv_value_21, amount_msat);
1980 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1981 assert!(payment_preimage.is_none());
1982 assert_eq!(our_payment_secret_21, *payment_secret);
1984 _ => panic!("expected PaymentPurpose::InvoicePayment")
1987 _ => panic!("Unexpected event"),
1990 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1991 assert_eq!(our_payment_hash_22, *payment_hash);
1992 assert_eq!(recv_value_22, amount_msat);
1994 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1995 assert!(payment_preimage.is_none());
1996 assert_eq!(our_payment_secret_22, *payment_secret);
1998 _ => panic!("expected PaymentPurpose::InvoicePayment")
2001 _ => panic!("Unexpected event"),
2004 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2005 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2006 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2008 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2009 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2010 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2012 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2013 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);
2014 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2015 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2016 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2018 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2019 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2023 fn channel_reserve_in_flight_removes() {
2024 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2025 // can send to its counterparty, but due to update ordering, the other side may not yet have
2026 // considered those HTLCs fully removed.
2027 // This tests that we don't count HTLCs which will not be included in the next remote
2028 // commitment transaction towards the reserve value (as it implies no commitment transaction
2029 // will be generated which violates the remote reserve value).
2030 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2032 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2033 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2034 // you only consider the value of the first HTLC, it may not),
2035 // * start routing a third HTLC from A to B,
2036 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2037 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2038 // * deliver the first fulfill from B
2039 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2041 // * deliver A's response CS and RAA.
2042 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2043 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2044 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2045 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2046 let chanmon_cfgs = create_chanmon_cfgs(2);
2047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2050 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2052 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2053 // Route the first two HTLCs.
2054 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2055 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2056 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2058 // Start routing the third HTLC (this is just used to get everyone in the right state).
2059 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2061 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2062 check_added_monitors!(nodes[0], 1);
2063 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2064 assert_eq!(events.len(), 1);
2065 SendEvent::from_event(events.remove(0))
2068 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2069 // initial fulfill/CS.
2070 nodes[1].node.claim_funds(payment_preimage_1);
2071 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2072 check_added_monitors!(nodes[1], 1);
2073 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2075 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2076 // remove the second HTLC when we send the HTLC back from B to A.
2077 nodes[1].node.claim_funds(payment_preimage_2);
2078 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2079 check_added_monitors!(nodes[1], 1);
2080 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2082 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2083 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2084 check_added_monitors!(nodes[0], 1);
2085 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2086 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2088 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2089 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2090 check_added_monitors!(nodes[1], 1);
2091 // B is already AwaitingRAA, so cant generate a CS here
2092 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2094 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2095 check_added_monitors!(nodes[1], 1);
2096 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2098 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2099 check_added_monitors!(nodes[0], 1);
2100 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2102 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2103 check_added_monitors!(nodes[1], 1);
2104 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2106 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2107 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2108 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2109 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2110 // on-chain as necessary).
2111 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2112 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2113 check_added_monitors!(nodes[0], 1);
2114 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2115 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2117 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2118 check_added_monitors!(nodes[1], 1);
2119 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2121 expect_pending_htlcs_forwardable!(nodes[1]);
2122 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2124 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2125 // resolve the second HTLC from A's point of view.
2126 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2127 check_added_monitors!(nodes[0], 1);
2128 expect_payment_path_successful!(nodes[0]);
2129 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2131 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2132 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2133 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2135 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2136 check_added_monitors!(nodes[1], 1);
2137 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2138 assert_eq!(events.len(), 1);
2139 SendEvent::from_event(events.remove(0))
2142 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2143 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2144 check_added_monitors!(nodes[0], 1);
2145 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2147 // Now just resolve all the outstanding messages/HTLCs for completeness...
2149 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2150 check_added_monitors!(nodes[1], 1);
2151 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2153 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2154 check_added_monitors!(nodes[1], 1);
2156 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2157 check_added_monitors!(nodes[0], 1);
2158 expect_payment_path_successful!(nodes[0]);
2159 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2161 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2162 check_added_monitors!(nodes[1], 1);
2163 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2165 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2166 check_added_monitors!(nodes[0], 1);
2168 expect_pending_htlcs_forwardable!(nodes[0]);
2169 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2171 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2172 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2176 fn channel_monitor_network_test() {
2177 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2178 // tests that ChannelMonitor is able to recover from various states.
2179 let chanmon_cfgs = create_chanmon_cfgs(5);
2180 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2181 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2182 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2184 // Create some initial channels
2185 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2186 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2187 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2188 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2190 // Make sure all nodes are at the same starting height
2191 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2192 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2193 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2194 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2195 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2197 // Rebalance the network a bit by relaying one payment through all the channels...
2198 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2199 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
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);
2203 // Simple case with no pending HTLCs:
2204 nodes[1].node.force_close_channel(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2205 check_added_monitors!(nodes[1], 1);
2206 check_closed_broadcast!(nodes[1], true);
2208 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2209 assert_eq!(node_txn.len(), 1);
2210 mine_transaction(&nodes[0], &node_txn[0]);
2211 check_added_monitors!(nodes[0], 1);
2212 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2214 check_closed_broadcast!(nodes[0], true);
2215 assert_eq!(nodes[0].node.list_channels().len(), 0);
2216 assert_eq!(nodes[1].node.list_channels().len(), 1);
2217 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2218 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2220 // One pending HTLC is discarded by the force-close:
2221 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2223 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2224 // broadcasted until we reach the timelock time).
2225 nodes[1].node.force_close_channel(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2226 check_closed_broadcast!(nodes[1], true);
2227 check_added_monitors!(nodes[1], 1);
2229 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2230 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2231 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2232 mine_transaction(&nodes[2], &node_txn[0]);
2233 check_added_monitors!(nodes[2], 1);
2234 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2236 check_closed_broadcast!(nodes[2], true);
2237 assert_eq!(nodes[1].node.list_channels().len(), 0);
2238 assert_eq!(nodes[2].node.list_channels().len(), 1);
2239 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2240 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2242 macro_rules! claim_funds {
2243 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2245 $node.node.claim_funds($preimage);
2246 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2247 check_added_monitors!($node, 1);
2249 let events = $node.node.get_and_clear_pending_msg_events();
2250 assert_eq!(events.len(), 1);
2252 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2253 assert!(update_add_htlcs.is_empty());
2254 assert!(update_fail_htlcs.is_empty());
2255 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2257 _ => panic!("Unexpected event"),
2263 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2264 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2265 nodes[2].node.force_close_channel(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2266 check_added_monitors!(nodes[2], 1);
2267 check_closed_broadcast!(nodes[2], true);
2268 let node2_commitment_txid;
2270 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2271 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2272 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2273 node2_commitment_txid = node_txn[0].txid();
2275 // Claim the payment on nodes[3], giving it knowledge of the preimage
2276 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2277 mine_transaction(&nodes[3], &node_txn[0]);
2278 check_added_monitors!(nodes[3], 1);
2279 check_preimage_claim(&nodes[3], &node_txn);
2281 check_closed_broadcast!(nodes[3], true);
2282 assert_eq!(nodes[2].node.list_channels().len(), 0);
2283 assert_eq!(nodes[3].node.list_channels().len(), 1);
2284 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2285 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2287 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2288 // confusing us in the following tests.
2289 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2291 // One pending HTLC to time out:
2292 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2293 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2296 let (close_chan_update_1, close_chan_update_2) = {
2297 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2298 let events = nodes[3].node.get_and_clear_pending_msg_events();
2299 assert_eq!(events.len(), 2);
2300 let close_chan_update_1 = match events[0] {
2301 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2304 _ => panic!("Unexpected event"),
2307 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2308 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2310 _ => panic!("Unexpected event"),
2312 check_added_monitors!(nodes[3], 1);
2314 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2316 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2317 node_txn.retain(|tx| {
2318 if tx.input[0].previous_output.txid == node2_commitment_txid {
2324 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2326 // Claim the payment on nodes[4], giving it knowledge of the preimage
2327 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2329 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2330 let events = nodes[4].node.get_and_clear_pending_msg_events();
2331 assert_eq!(events.len(), 2);
2332 let close_chan_update_2 = match events[0] {
2333 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2336 _ => panic!("Unexpected event"),
2339 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2340 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2342 _ => panic!("Unexpected event"),
2344 check_added_monitors!(nodes[4], 1);
2345 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2347 mine_transaction(&nodes[4], &node_txn[0]);
2348 check_preimage_claim(&nodes[4], &node_txn);
2349 (close_chan_update_1, close_chan_update_2)
2351 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2352 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2353 assert_eq!(nodes[3].node.list_channels().len(), 0);
2354 assert_eq!(nodes[4].node.list_channels().len(), 0);
2356 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2357 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2358 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2362 fn test_justice_tx() {
2363 // Test justice txn built on revoked HTLC-Success tx, against both sides
2364 let mut alice_config = UserConfig::default();
2365 alice_config.channel_handshake_config.announced_channel = true;
2366 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2367 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2368 let mut bob_config = UserConfig::default();
2369 bob_config.channel_handshake_config.announced_channel = true;
2370 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2371 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2372 let user_cfgs = [Some(alice_config), Some(bob_config)];
2373 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2374 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2375 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2378 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2379 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2380 // Create some new channels:
2381 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2383 // A pending HTLC which will be revoked:
2384 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2385 // Get the will-be-revoked local txn from nodes[0]
2386 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2387 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2388 assert_eq!(revoked_local_txn[0].input.len(), 1);
2389 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2390 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2391 assert_eq!(revoked_local_txn[1].input.len(), 1);
2392 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2393 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2394 // Revoke the old state
2395 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2398 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2400 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2401 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2402 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2404 check_spends!(node_txn[0], revoked_local_txn[0]);
2405 node_txn.swap_remove(0);
2406 node_txn.truncate(1);
2408 check_added_monitors!(nodes[1], 1);
2409 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2410 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2412 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2413 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2414 // Verify broadcast of revoked HTLC-timeout
2415 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2416 check_added_monitors!(nodes[0], 1);
2417 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2418 // Broadcast revoked HTLC-timeout on node 1
2419 mine_transaction(&nodes[1], &node_txn[1]);
2420 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2422 get_announce_close_broadcast_events(&nodes, 0, 1);
2424 assert_eq!(nodes[0].node.list_channels().len(), 0);
2425 assert_eq!(nodes[1].node.list_channels().len(), 0);
2427 // We test justice_tx build by A on B's revoked HTLC-Success tx
2428 // Create some new channels:
2429 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2431 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2435 // A pending HTLC which will be revoked:
2436 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2437 // Get the will-be-revoked local txn from B
2438 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2439 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2440 assert_eq!(revoked_local_txn[0].input.len(), 1);
2441 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2442 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2443 // Revoke the old state
2444 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2446 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2448 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2449 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2450 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2452 check_spends!(node_txn[0], revoked_local_txn[0]);
2453 node_txn.swap_remove(0);
2455 check_added_monitors!(nodes[0], 1);
2456 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2458 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2459 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2460 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2461 check_added_monitors!(nodes[1], 1);
2462 mine_transaction(&nodes[0], &node_txn[1]);
2463 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2464 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2466 get_announce_close_broadcast_events(&nodes, 0, 1);
2467 assert_eq!(nodes[0].node.list_channels().len(), 0);
2468 assert_eq!(nodes[1].node.list_channels().len(), 0);
2472 fn revoked_output_claim() {
2473 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2474 // transaction is broadcast by its counterparty
2475 let chanmon_cfgs = create_chanmon_cfgs(2);
2476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2478 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2479 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2480 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2481 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2482 assert_eq!(revoked_local_txn.len(), 1);
2483 // Only output is the full channel value back to nodes[0]:
2484 assert_eq!(revoked_local_txn[0].output.len(), 1);
2485 // Send a payment through, updating everyone's latest commitment txn
2486 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2488 // Inform nodes[1] that nodes[0] broadcast a stale tx
2489 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2490 check_added_monitors!(nodes[1], 1);
2491 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2492 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2493 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2495 check_spends!(node_txn[0], revoked_local_txn[0]);
2496 check_spends!(node_txn[1], chan_1.3);
2498 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2499 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2500 get_announce_close_broadcast_events(&nodes, 0, 1);
2501 check_added_monitors!(nodes[0], 1);
2502 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2506 fn claim_htlc_outputs_shared_tx() {
2507 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2508 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2509 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2510 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2511 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2512 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2514 // Create some new channel:
2515 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2517 // Rebalance the network to generate htlc in the two directions
2518 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2519 // 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
2520 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2521 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2523 // Get the will-be-revoked local txn from node[0]
2524 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2525 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2526 assert_eq!(revoked_local_txn[0].input.len(), 1);
2527 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2528 assert_eq!(revoked_local_txn[1].input.len(), 1);
2529 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2530 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2531 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2533 //Revoke the old state
2534 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2537 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538 check_added_monitors!(nodes[0], 1);
2539 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2540 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2541 check_added_monitors!(nodes[1], 1);
2542 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2543 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2544 expect_payment_failed!(nodes[1], payment_hash_2, true);
2546 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2547 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2549 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2550 check_spends!(node_txn[0], revoked_local_txn[0]);
2552 let mut witness_lens = BTreeSet::new();
2553 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2554 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2555 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2556 assert_eq!(witness_lens.len(), 3);
2557 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2558 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2559 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2561 // Next nodes[1] broadcasts its current local tx state:
2562 assert_eq!(node_txn[1].input.len(), 1);
2563 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2565 get_announce_close_broadcast_events(&nodes, 0, 1);
2566 assert_eq!(nodes[0].node.list_channels().len(), 0);
2567 assert_eq!(nodes[1].node.list_channels().len(), 0);
2571 fn claim_htlc_outputs_single_tx() {
2572 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2573 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2574 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2579 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2581 // Rebalance the network to generate htlc in the two directions
2582 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2583 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2584 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2585 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2586 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2588 // Get the will-be-revoked local txn from node[0]
2589 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2591 //Revoke the old state
2592 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2595 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2596 check_added_monitors!(nodes[0], 1);
2597 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2598 check_added_monitors!(nodes[1], 1);
2599 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2600 let mut events = nodes[0].node.get_and_clear_pending_events();
2601 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2603 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2604 _ => panic!("Unexpected event"),
2607 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2608 expect_payment_failed!(nodes[1], payment_hash_2, true);
2610 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2611 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2613 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2614 assert_eq!(node_txn[0].input.len(), 1);
2615 check_spends!(node_txn[0], chan_1.3);
2616 assert_eq!(node_txn[1].input.len(), 1);
2617 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2618 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2619 check_spends!(node_txn[1], node_txn[0]);
2621 // Justice transactions are indices 1-2-4
2622 assert_eq!(node_txn[2].input.len(), 1);
2623 assert_eq!(node_txn[3].input.len(), 1);
2624 assert_eq!(node_txn[4].input.len(), 1);
2626 check_spends!(node_txn[2], revoked_local_txn[0]);
2627 check_spends!(node_txn[3], revoked_local_txn[0]);
2628 check_spends!(node_txn[4], revoked_local_txn[0]);
2630 let mut witness_lens = BTreeSet::new();
2631 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2632 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2633 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2634 assert_eq!(witness_lens.len(), 3);
2635 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2636 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2637 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2639 get_announce_close_broadcast_events(&nodes, 0, 1);
2640 assert_eq!(nodes[0].node.list_channels().len(), 0);
2641 assert_eq!(nodes[1].node.list_channels().len(), 0);
2645 fn test_htlc_on_chain_success() {
2646 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2647 // the preimage backward accordingly. So here we test that ChannelManager is
2648 // broadcasting the right event to other nodes in payment path.
2649 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2650 // A --------------------> B ----------------------> C (preimage)
2651 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2652 // commitment transaction was broadcast.
2653 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2655 // B should be able to claim via preimage if A then broadcasts its local tx.
2656 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2657 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2658 // PaymentSent event).
2660 let chanmon_cfgs = create_chanmon_cfgs(3);
2661 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2662 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2663 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2665 // Create some initial channels
2666 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2667 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2669 // Ensure all nodes are at the same height
2670 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2671 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2672 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2673 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2675 // Rebalance the network a bit by relaying one payment through all the channels...
2676 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2677 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2679 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2680 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2682 // Broadcast legit commitment tx from C on B's chain
2683 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2684 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2685 assert_eq!(commitment_tx.len(), 1);
2686 check_spends!(commitment_tx[0], chan_2.3);
2687 nodes[2].node.claim_funds(our_payment_preimage);
2688 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2689 nodes[2].node.claim_funds(our_payment_preimage_2);
2690 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2691 check_added_monitors!(nodes[2], 2);
2692 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2693 assert!(updates.update_add_htlcs.is_empty());
2694 assert!(updates.update_fail_htlcs.is_empty());
2695 assert!(updates.update_fail_malformed_htlcs.is_empty());
2696 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2698 mine_transaction(&nodes[2], &commitment_tx[0]);
2699 check_closed_broadcast!(nodes[2], true);
2700 check_added_monitors!(nodes[2], 1);
2701 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2702 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)
2703 assert_eq!(node_txn.len(), 5);
2704 assert_eq!(node_txn[0], node_txn[3]);
2705 assert_eq!(node_txn[1], node_txn[4]);
2706 assert_eq!(node_txn[2], commitment_tx[0]);
2707 check_spends!(node_txn[0], commitment_tx[0]);
2708 check_spends!(node_txn[1], commitment_tx[0]);
2709 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2711 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2713 assert_eq!(node_txn[0].lock_time, 0);
2714 assert_eq!(node_txn[1].lock_time, 0);
2716 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2717 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2718 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2719 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2721 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2722 assert_eq!(added_monitors.len(), 1);
2723 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2724 added_monitors.clear();
2726 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2727 assert_eq!(forwarded_events.len(), 3);
2728 match forwarded_events[0] {
2729 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2730 _ => panic!("Unexpected event"),
2732 let chan_id = Some(chan_1.2);
2733 match forwarded_events[1] {
2734 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2735 assert_eq!(fee_earned_msat, Some(1000));
2736 assert_eq!(prev_channel_id, chan_id);
2737 assert_eq!(claim_from_onchain_tx, true);
2738 assert_eq!(next_channel_id, Some(chan_2.2));
2742 match forwarded_events[2] {
2743 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2744 assert_eq!(fee_earned_msat, Some(1000));
2745 assert_eq!(prev_channel_id, chan_id);
2746 assert_eq!(claim_from_onchain_tx, true);
2747 assert_eq!(next_channel_id, Some(chan_2.2));
2751 let events = nodes[1].node.get_and_clear_pending_msg_events();
2753 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2754 assert_eq!(added_monitors.len(), 2);
2755 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2756 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2757 added_monitors.clear();
2759 assert_eq!(events.len(), 3);
2761 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2762 _ => panic!("Unexpected event"),
2765 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2766 _ => panic!("Unexpected event"),
2770 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, .. } } => {
2771 assert!(update_add_htlcs.is_empty());
2772 assert!(update_fail_htlcs.is_empty());
2773 assert_eq!(update_fulfill_htlcs.len(), 1);
2774 assert!(update_fail_malformed_htlcs.is_empty());
2775 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2777 _ => panic!("Unexpected event"),
2779 macro_rules! check_tx_local_broadcast {
2780 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2781 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2782 assert_eq!(node_txn.len(), 3);
2783 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2784 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2785 check_spends!(node_txn[1], $commitment_tx);
2786 check_spends!(node_txn[2], $commitment_tx);
2787 assert_ne!(node_txn[1].lock_time, 0);
2788 assert_ne!(node_txn[2].lock_time, 0);
2790 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2791 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2792 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2793 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2795 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2796 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2797 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2798 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2800 check_spends!(node_txn[0], $chan_tx);
2801 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2805 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2806 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2807 // timeout-claim of the output that nodes[2] just claimed via success.
2808 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2810 // Broadcast legit commitment tx from A on B's chain
2811 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2812 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2813 check_spends!(node_a_commitment_tx[0], chan_1.3);
2814 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2815 check_closed_broadcast!(nodes[1], true);
2816 check_added_monitors!(nodes[1], 1);
2817 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2818 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2819 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2820 let commitment_spend =
2821 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2822 check_spends!(node_txn[1], commitment_tx[0]);
2823 check_spends!(node_txn[2], commitment_tx[0]);
2824 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2827 check_spends!(node_txn[0], commitment_tx[0]);
2828 check_spends!(node_txn[1], commitment_tx[0]);
2829 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2833 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2834 assert_eq!(commitment_spend.input.len(), 2);
2835 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2836 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2837 assert_eq!(commitment_spend.lock_time, 0);
2838 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2839 check_spends!(node_txn[3], chan_1.3);
2840 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2841 check_spends!(node_txn[4], node_txn[3]);
2842 check_spends!(node_txn[5], node_txn[3]);
2843 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2844 // we already checked the same situation with A.
2846 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2847 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2848 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2849 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2850 check_closed_broadcast!(nodes[0], true);
2851 check_added_monitors!(nodes[0], 1);
2852 let events = nodes[0].node.get_and_clear_pending_events();
2853 assert_eq!(events.len(), 5);
2854 let mut first_claimed = false;
2855 for event in events {
2857 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2858 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2859 assert!(!first_claimed);
2860 first_claimed = true;
2862 assert_eq!(payment_preimage, our_payment_preimage_2);
2863 assert_eq!(payment_hash, payment_hash_2);
2866 Event::PaymentPathSuccessful { .. } => {},
2867 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2868 _ => panic!("Unexpected event"),
2871 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2874 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2875 // Test that in case of a unilateral close onchain, we detect the state of output and
2876 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2877 // broadcasting the right event to other nodes in payment path.
2878 // A ------------------> B ----------------------> C (timeout)
2879 // B's commitment tx C's commitment tx
2881 // B's HTLC timeout tx B's timeout tx
2883 let chanmon_cfgs = create_chanmon_cfgs(3);
2884 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2885 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2886 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2887 *nodes[0].connect_style.borrow_mut() = connect_style;
2888 *nodes[1].connect_style.borrow_mut() = connect_style;
2889 *nodes[2].connect_style.borrow_mut() = connect_style;
2891 // Create some intial channels
2892 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2893 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2895 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2896 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2897 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2899 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2901 // Broadcast legit commitment tx from C on B's chain
2902 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2903 check_spends!(commitment_tx[0], chan_2.3);
2904 nodes[2].node.fail_htlc_backwards(&payment_hash);
2905 check_added_monitors!(nodes[2], 0);
2906 expect_pending_htlcs_forwardable!(nodes[2]);
2907 check_added_monitors!(nodes[2], 1);
2909 let events = nodes[2].node.get_and_clear_pending_msg_events();
2910 assert_eq!(events.len(), 1);
2912 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, .. } } => {
2913 assert!(update_add_htlcs.is_empty());
2914 assert!(!update_fail_htlcs.is_empty());
2915 assert!(update_fulfill_htlcs.is_empty());
2916 assert!(update_fail_malformed_htlcs.is_empty());
2917 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2919 _ => panic!("Unexpected event"),
2921 mine_transaction(&nodes[2], &commitment_tx[0]);
2922 check_closed_broadcast!(nodes[2], true);
2923 check_added_monitors!(nodes[2], 1);
2924 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2925 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2926 assert_eq!(node_txn.len(), 1);
2927 check_spends!(node_txn[0], chan_2.3);
2928 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2930 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2931 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2932 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2933 mine_transaction(&nodes[1], &commitment_tx[0]);
2934 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2937 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2938 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2939 assert_eq!(node_txn[0], node_txn[3]);
2940 assert_eq!(node_txn[1], node_txn[4]);
2942 check_spends!(node_txn[2], commitment_tx[0]);
2943 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2945 check_spends!(node_txn[0], chan_2.3);
2946 check_spends!(node_txn[1], node_txn[0]);
2947 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2948 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2950 timeout_tx = node_txn[2].clone();
2954 mine_transaction(&nodes[1], &timeout_tx);
2955 check_added_monitors!(nodes[1], 1);
2956 check_closed_broadcast!(nodes[1], true);
2958 // B will rebroadcast a fee-bumped timeout transaction here.
2959 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2960 assert_eq!(node_txn.len(), 1);
2961 check_spends!(node_txn[0], commitment_tx[0]);
2964 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2966 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2967 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2968 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2969 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2970 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2971 if node_txn.len() == 1 {
2972 check_spends!(node_txn[0], chan_2.3);
2974 assert_eq!(node_txn.len(), 0);
2978 expect_pending_htlcs_forwardable!(nodes[1]);
2979 check_added_monitors!(nodes[1], 1);
2980 let events = nodes[1].node.get_and_clear_pending_msg_events();
2981 assert_eq!(events.len(), 1);
2983 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, .. } } => {
2984 assert!(update_add_htlcs.is_empty());
2985 assert!(!update_fail_htlcs.is_empty());
2986 assert!(update_fulfill_htlcs.is_empty());
2987 assert!(update_fail_malformed_htlcs.is_empty());
2988 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2990 _ => panic!("Unexpected event"),
2993 // Broadcast legit commitment tx from B on A's chain
2994 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2995 check_spends!(commitment_tx[0], chan_1.3);
2997 mine_transaction(&nodes[0], &commitment_tx[0]);
2998 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3000 check_closed_broadcast!(nodes[0], true);
3001 check_added_monitors!(nodes[0], 1);
3002 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3003 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3004 assert_eq!(node_txn.len(), 2);
3005 check_spends!(node_txn[0], chan_1.3);
3006 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3007 check_spends!(node_txn[1], commitment_tx[0]);
3008 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3012 fn test_htlc_on_chain_timeout() {
3013 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3014 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3015 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3019 fn test_simple_commitment_revoked_fail_backward() {
3020 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3021 // and fail backward accordingly.
3023 let chanmon_cfgs = create_chanmon_cfgs(3);
3024 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3025 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3026 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3028 // Create some initial channels
3029 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3030 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3032 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3033 // Get the will-be-revoked local txn from nodes[2]
3034 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3035 // Revoke the old state
3036 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3038 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3040 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3041 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3042 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3043 check_added_monitors!(nodes[1], 1);
3044 check_closed_broadcast!(nodes[1], true);
3046 expect_pending_htlcs_forwardable!(nodes[1]);
3047 check_added_monitors!(nodes[1], 1);
3048 let events = nodes[1].node.get_and_clear_pending_msg_events();
3049 assert_eq!(events.len(), 1);
3051 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, .. } } => {
3052 assert!(update_add_htlcs.is_empty());
3053 assert_eq!(update_fail_htlcs.len(), 1);
3054 assert!(update_fulfill_htlcs.is_empty());
3055 assert!(update_fail_malformed_htlcs.is_empty());
3056 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3058 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3059 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3060 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3062 _ => panic!("Unexpected event"),
3066 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3067 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3068 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3069 // commitment transaction anymore.
3070 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3071 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3072 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3073 // technically disallowed and we should probably handle it reasonably.
3074 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3075 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3077 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3078 // commitment_signed (implying it will be in the latest remote commitment transaction).
3079 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3080 // and once they revoke the previous commitment transaction (allowing us to send a new
3081 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3082 let chanmon_cfgs = create_chanmon_cfgs(3);
3083 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3084 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3085 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3087 // Create some initial channels
3088 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3089 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3091 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 });
3092 // Get the will-be-revoked local txn from nodes[2]
3093 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3094 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3095 // Revoke the old state
3096 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3098 let value = if use_dust {
3099 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3100 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3101 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3104 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3105 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3106 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3108 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3109 expect_pending_htlcs_forwardable!(nodes[2]);
3110 check_added_monitors!(nodes[2], 1);
3111 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3112 assert!(updates.update_add_htlcs.is_empty());
3113 assert!(updates.update_fulfill_htlcs.is_empty());
3114 assert!(updates.update_fail_malformed_htlcs.is_empty());
3115 assert_eq!(updates.update_fail_htlcs.len(), 1);
3116 assert!(updates.update_fee.is_none());
3117 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3118 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3119 // Drop the last RAA from 3 -> 2
3121 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3122 expect_pending_htlcs_forwardable!(nodes[2]);
3123 check_added_monitors!(nodes[2], 1);
3124 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3125 assert!(updates.update_add_htlcs.is_empty());
3126 assert!(updates.update_fulfill_htlcs.is_empty());
3127 assert!(updates.update_fail_malformed_htlcs.is_empty());
3128 assert_eq!(updates.update_fail_htlcs.len(), 1);
3129 assert!(updates.update_fee.is_none());
3130 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3131 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3132 check_added_monitors!(nodes[1], 1);
3133 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3134 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3135 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3136 check_added_monitors!(nodes[2], 1);
3138 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3139 expect_pending_htlcs_forwardable!(nodes[2]);
3140 check_added_monitors!(nodes[2], 1);
3141 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3142 assert!(updates.update_add_htlcs.is_empty());
3143 assert!(updates.update_fulfill_htlcs.is_empty());
3144 assert!(updates.update_fail_malformed_htlcs.is_empty());
3145 assert_eq!(updates.update_fail_htlcs.len(), 1);
3146 assert!(updates.update_fee.is_none());
3147 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3148 // At this point first_payment_hash has dropped out of the latest two commitment
3149 // transactions that nodes[1] is tracking...
3150 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3151 check_added_monitors!(nodes[1], 1);
3152 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3153 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3154 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3155 check_added_monitors!(nodes[2], 1);
3157 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3158 // on nodes[2]'s RAA.
3159 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3160 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3161 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3162 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3163 check_added_monitors!(nodes[1], 0);
3166 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3167 // One monitor for the new revocation preimage, no second on as we won't generate a new
3168 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3169 check_added_monitors!(nodes[1], 1);
3170 let events = nodes[1].node.get_and_clear_pending_events();
3171 assert_eq!(events.len(), 1);
3173 Event::PendingHTLCsForwardable { .. } => { },
3174 _ => panic!("Unexpected event"),
3176 // Deliberately don't process the pending fail-back so they all fail back at once after
3177 // block connection just like the !deliver_bs_raa case
3180 let mut failed_htlcs = HashSet::new();
3181 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3183 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3184 check_added_monitors!(nodes[1], 1);
3185 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3186 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3188 let events = nodes[1].node.get_and_clear_pending_events();
3189 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3191 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3192 _ => panic!("Unexepected event"),
3195 Event::PaymentPathFailed { ref payment_hash, .. } => {
3196 assert_eq!(*payment_hash, fourth_payment_hash);
3198 _ => panic!("Unexpected event"),
3200 if !deliver_bs_raa {
3202 Event::PaymentFailed { ref payment_hash, .. } => {
3203 assert_eq!(*payment_hash, fourth_payment_hash);
3205 _ => panic!("Unexpected event"),
3208 Event::PendingHTLCsForwardable { .. } => { },
3209 _ => panic!("Unexpected event"),
3212 nodes[1].node.process_pending_htlc_forwards();
3213 check_added_monitors!(nodes[1], 1);
3215 let events = nodes[1].node.get_and_clear_pending_msg_events();
3216 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3217 match events[if deliver_bs_raa { 1 } else { 0 }] {
3218 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3219 _ => panic!("Unexpected event"),
3221 match events[if deliver_bs_raa { 2 } else { 1 }] {
3222 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3223 assert_eq!(channel_id, chan_2.2);
3224 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3226 _ => panic!("Unexpected event"),
3230 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, .. } } => {
3231 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3232 assert_eq!(update_add_htlcs.len(), 1);
3233 assert!(update_fulfill_htlcs.is_empty());
3234 assert!(update_fail_htlcs.is_empty());
3235 assert!(update_fail_malformed_htlcs.is_empty());
3237 _ => panic!("Unexpected event"),
3240 match events[if deliver_bs_raa { 3 } else { 2 }] {
3241 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, .. } } => {
3242 assert!(update_add_htlcs.is_empty());
3243 assert_eq!(update_fail_htlcs.len(), 3);
3244 assert!(update_fulfill_htlcs.is_empty());
3245 assert!(update_fail_malformed_htlcs.is_empty());
3246 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3248 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3249 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3250 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3252 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3254 let events = nodes[0].node.get_and_clear_pending_events();
3255 assert_eq!(events.len(), 3);
3257 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3258 assert!(failed_htlcs.insert(payment_hash.0));
3259 // If we delivered B's RAA we got an unknown preimage error, not something
3260 // that we should update our routing table for.
3261 if !deliver_bs_raa {
3262 assert!(network_update.is_some());
3265 _ => panic!("Unexpected event"),
3268 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3269 assert!(failed_htlcs.insert(payment_hash.0));
3270 assert!(network_update.is_some());
3272 _ => panic!("Unexpected event"),
3275 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3276 assert!(failed_htlcs.insert(payment_hash.0));
3277 assert!(network_update.is_some());
3279 _ => panic!("Unexpected event"),
3282 _ => panic!("Unexpected event"),
3285 assert!(failed_htlcs.contains(&first_payment_hash.0));
3286 assert!(failed_htlcs.contains(&second_payment_hash.0));
3287 assert!(failed_htlcs.contains(&third_payment_hash.0));
3291 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3292 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3293 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3294 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3295 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3299 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3300 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3301 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3302 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3303 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3307 fn fail_backward_pending_htlc_upon_channel_failure() {
3308 let chanmon_cfgs = create_chanmon_cfgs(2);
3309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3311 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3312 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3314 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3316 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3317 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3318 check_added_monitors!(nodes[0], 1);
3320 let payment_event = {
3321 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3322 assert_eq!(events.len(), 1);
3323 SendEvent::from_event(events.remove(0))
3325 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3326 assert_eq!(payment_event.msgs.len(), 1);
3329 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3330 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3332 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3333 check_added_monitors!(nodes[0], 0);
3335 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3338 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3340 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3342 let secp_ctx = Secp256k1::new();
3343 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3344 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3345 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3346 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3347 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3349 // Send a 0-msat update_add_htlc to fail the channel.
3350 let update_add_htlc = msgs::UpdateAddHTLC {
3356 onion_routing_packet,
3358 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3360 let events = nodes[0].node.get_and_clear_pending_events();
3361 assert_eq!(events.len(), 2);
3362 // Check that Alice fails backward the pending HTLC from the second payment.
3364 Event::PaymentPathFailed { payment_hash, .. } => {
3365 assert_eq!(payment_hash, failed_payment_hash);
3367 _ => panic!("Unexpected event"),
3370 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3371 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3373 _ => panic!("Unexpected event {:?}", events[1]),
3375 check_closed_broadcast!(nodes[0], true);
3376 check_added_monitors!(nodes[0], 1);
3380 fn test_htlc_ignore_latest_remote_commitment() {
3381 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3382 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3383 let chanmon_cfgs = create_chanmon_cfgs(2);
3384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3386 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3387 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3389 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3390 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3391 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3392 check_closed_broadcast!(nodes[0], true);
3393 check_added_monitors!(nodes[0], 1);
3394 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3396 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3397 assert_eq!(node_txn.len(), 3);
3398 assert_eq!(node_txn[0], node_txn[1]);
3400 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3401 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3402 check_closed_broadcast!(nodes[1], true);
3403 check_added_monitors!(nodes[1], 1);
3404 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3406 // Duplicate the connect_block call since this may happen due to other listeners
3407 // registering new transactions
3408 header.prev_blockhash = header.block_hash();
3409 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3413 fn test_force_close_fail_back() {
3414 // Check which HTLCs are failed-backwards on channel force-closure
3415 let chanmon_cfgs = create_chanmon_cfgs(3);
3416 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3417 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3418 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3419 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3420 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3422 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3424 let mut payment_event = {
3425 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3426 check_added_monitors!(nodes[0], 1);
3428 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3429 assert_eq!(events.len(), 1);
3430 SendEvent::from_event(events.remove(0))
3433 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3434 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3436 expect_pending_htlcs_forwardable!(nodes[1]);
3438 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3439 assert_eq!(events_2.len(), 1);
3440 payment_event = SendEvent::from_event(events_2.remove(0));
3441 assert_eq!(payment_event.msgs.len(), 1);
3443 check_added_monitors!(nodes[1], 1);
3444 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3445 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3446 check_added_monitors!(nodes[2], 1);
3447 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3449 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3450 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3451 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3453 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3454 check_closed_broadcast!(nodes[2], true);
3455 check_added_monitors!(nodes[2], 1);
3456 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3458 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3459 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3460 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3461 // back to nodes[1] upon timeout otherwise.
3462 assert_eq!(node_txn.len(), 1);
3466 mine_transaction(&nodes[1], &tx);
3468 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3469 check_closed_broadcast!(nodes[1], true);
3470 check_added_monitors!(nodes[1], 1);
3471 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3473 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3475 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3476 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3478 mine_transaction(&nodes[2], &tx);
3479 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3480 assert_eq!(node_txn.len(), 1);
3481 assert_eq!(node_txn[0].input.len(), 1);
3482 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3483 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3484 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3486 check_spends!(node_txn[0], tx);
3490 fn test_dup_events_on_peer_disconnect() {
3491 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3492 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3493 // as we used to generate the event immediately upon receipt of the payment preimage in the
3494 // update_fulfill_htlc message.
3496 let chanmon_cfgs = create_chanmon_cfgs(2);
3497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3500 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3502 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3504 nodes[1].node.claim_funds(payment_preimage);
3505 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3506 check_added_monitors!(nodes[1], 1);
3507 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3508 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3509 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3511 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3512 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3514 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3515 expect_payment_path_successful!(nodes[0]);
3519 fn test_peer_disconnected_before_funding_broadcasted() {
3520 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3521 // before the funding transaction has been broadcasted.
3522 let chanmon_cfgs = create_chanmon_cfgs(2);
3523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3527 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3528 // broadcasted, even though it's created by `nodes[0]`.
3529 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();
3530 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3531 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3532 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3533 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3535 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3536 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3538 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3540 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3541 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3543 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3544 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3547 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3550 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3551 // disconnected before the funding transaction was broadcasted.
3552 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3553 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3555 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3556 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3560 fn test_simple_peer_disconnect() {
3561 // Test that we can reconnect when there are no lost messages
3562 let chanmon_cfgs = create_chanmon_cfgs(3);
3563 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3564 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3565 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3566 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3567 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3569 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3570 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3571 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3574 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3575 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3576 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3578 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3579 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3580 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3582 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3583 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3584 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3585 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3588 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3590 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3591 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3593 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3595 let events = nodes[0].node.get_and_clear_pending_events();
3596 assert_eq!(events.len(), 3);
3598 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3599 assert_eq!(payment_preimage, payment_preimage_3);
3600 assert_eq!(payment_hash, payment_hash_3);
3602 _ => panic!("Unexpected event"),
3605 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3606 assert_eq!(payment_hash, payment_hash_5);
3607 assert!(rejected_by_dest);
3609 _ => panic!("Unexpected event"),
3612 Event::PaymentPathSuccessful { .. } => {},
3613 _ => panic!("Unexpected event"),
3617 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3618 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3621 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3622 // Test that we can reconnect when in-flight HTLC updates get dropped
3623 let chanmon_cfgs = create_chanmon_cfgs(2);
3624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3626 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3628 let mut as_channel_ready = None;
3629 if messages_delivered == 0 {
3630 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3631 as_channel_ready = Some(channel_ready);
3632 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3633 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3634 // it before the channel_reestablish message.
3636 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3639 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3641 let payment_event = {
3642 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3643 check_added_monitors!(nodes[0], 1);
3645 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3646 assert_eq!(events.len(), 1);
3647 SendEvent::from_event(events.remove(0))
3649 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3651 if messages_delivered < 2 {
3652 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3654 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3655 if messages_delivered >= 3 {
3656 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3657 check_added_monitors!(nodes[1], 1);
3658 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3660 if messages_delivered >= 4 {
3661 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3662 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3663 check_added_monitors!(nodes[0], 1);
3665 if messages_delivered >= 5 {
3666 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3667 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3668 // No commitment_signed so get_event_msg's assert(len == 1) passes
3669 check_added_monitors!(nodes[0], 1);
3671 if messages_delivered >= 6 {
3672 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3673 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3674 check_added_monitors!(nodes[1], 1);
3681 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3682 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3683 if messages_delivered < 3 {
3684 if simulate_broken_lnd {
3685 // lnd has a long-standing bug where they send a channel_ready prior to a
3686 // channel_reestablish if you reconnect prior to channel_ready time.
3688 // Here we simulate that behavior, delivering a channel_ready immediately on
3689 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3690 // in `reconnect_nodes` but we currently don't fail based on that.
3692 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3693 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3695 // Even if the channel_ready messages get exchanged, as long as nothing further was
3696 // received on either side, both sides will need to resend them.
3697 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3698 } else if messages_delivered == 3 {
3699 // nodes[0] still wants its RAA + commitment_signed
3700 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3701 } else if messages_delivered == 4 {
3702 // nodes[0] still wants its commitment_signed
3703 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3704 } else if messages_delivered == 5 {
3705 // nodes[1] still wants its final RAA
3706 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3707 } else if messages_delivered == 6 {
3708 // Everything was delivered...
3709 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712 let events_1 = nodes[1].node.get_and_clear_pending_events();
3713 assert_eq!(events_1.len(), 1);
3715 Event::PendingHTLCsForwardable { .. } => { },
3716 _ => panic!("Unexpected event"),
3719 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3720 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3721 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3723 nodes[1].node.process_pending_htlc_forwards();
3725 let events_2 = nodes[1].node.get_and_clear_pending_events();
3726 assert_eq!(events_2.len(), 1);
3728 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3729 assert_eq!(payment_hash_1, *payment_hash);
3730 assert_eq!(amount_msat, 1_000_000);
3732 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3733 assert!(payment_preimage.is_none());
3734 assert_eq!(payment_secret_1, *payment_secret);
3736 _ => panic!("expected PaymentPurpose::InvoicePayment")
3739 _ => panic!("Unexpected event"),
3742 nodes[1].node.claim_funds(payment_preimage_1);
3743 check_added_monitors!(nodes[1], 1);
3744 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3746 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3747 assert_eq!(events_3.len(), 1);
3748 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3749 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3750 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3751 assert!(updates.update_add_htlcs.is_empty());
3752 assert!(updates.update_fail_htlcs.is_empty());
3753 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3754 assert!(updates.update_fail_malformed_htlcs.is_empty());
3755 assert!(updates.update_fee.is_none());
3756 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3758 _ => panic!("Unexpected event"),
3761 if messages_delivered >= 1 {
3762 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3764 let events_4 = nodes[0].node.get_and_clear_pending_events();
3765 assert_eq!(events_4.len(), 1);
3767 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3768 assert_eq!(payment_preimage_1, *payment_preimage);
3769 assert_eq!(payment_hash_1, *payment_hash);
3771 _ => panic!("Unexpected event"),
3774 if messages_delivered >= 2 {
3775 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3776 check_added_monitors!(nodes[0], 1);
3777 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3779 if messages_delivered >= 3 {
3780 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3781 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3782 check_added_monitors!(nodes[1], 1);
3784 if messages_delivered >= 4 {
3785 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3786 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3787 // No commitment_signed so get_event_msg's assert(len == 1) passes
3788 check_added_monitors!(nodes[1], 1);
3790 if messages_delivered >= 5 {
3791 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3792 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3793 check_added_monitors!(nodes[0], 1);
3800 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3801 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3802 if messages_delivered < 2 {
3803 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3804 if messages_delivered < 1 {
3805 expect_payment_sent!(nodes[0], payment_preimage_1);
3807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3809 } else if messages_delivered == 2 {
3810 // nodes[0] still wants its RAA + commitment_signed
3811 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3812 } else if messages_delivered == 3 {
3813 // nodes[0] still wants its commitment_signed
3814 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815 } else if messages_delivered == 4 {
3816 // nodes[1] still wants its final RAA
3817 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3818 } else if messages_delivered == 5 {
3819 // Everything was delivered...
3820 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3823 if messages_delivered == 1 || messages_delivered == 2 {
3824 expect_payment_path_successful!(nodes[0]);
3827 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3828 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3829 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3831 if messages_delivered > 2 {
3832 expect_payment_path_successful!(nodes[0]);
3835 // Channel should still work fine...
3836 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3837 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3838 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3842 fn test_drop_messages_peer_disconnect_a() {
3843 do_test_drop_messages_peer_disconnect(0, true);
3844 do_test_drop_messages_peer_disconnect(0, false);
3845 do_test_drop_messages_peer_disconnect(1, false);
3846 do_test_drop_messages_peer_disconnect(2, false);
3850 fn test_drop_messages_peer_disconnect_b() {
3851 do_test_drop_messages_peer_disconnect(3, false);
3852 do_test_drop_messages_peer_disconnect(4, false);
3853 do_test_drop_messages_peer_disconnect(5, false);
3854 do_test_drop_messages_peer_disconnect(6, false);
3858 fn test_funding_peer_disconnect() {
3859 // Test that we can lock in our funding tx while disconnected
3860 let chanmon_cfgs = create_chanmon_cfgs(2);
3861 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3862 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3863 let persister: test_utils::TestPersister;
3864 let new_chain_monitor: test_utils::TestChainMonitor;
3865 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3866 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3867 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3869 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3870 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3872 confirm_transaction(&nodes[0], &tx);
3873 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3874 assert!(events_1.is_empty());
3876 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3878 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3879 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3881 confirm_transaction(&nodes[1], &tx);
3882 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3883 assert!(events_2.is_empty());
3885 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3886 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3887 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3888 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3890 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3891 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3892 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3893 assert_eq!(events_3.len(), 1);
3894 let as_channel_ready = match events_3[0] {
3895 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3896 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3899 _ => panic!("Unexpected event {:?}", events_3[0]),
3902 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3903 // announcement_signatures as well as channel_update.
3904 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3905 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3906 assert_eq!(events_4.len(), 3);
3908 let bs_channel_ready = match events_4[0] {
3909 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3910 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3911 chan_id = msg.channel_id;
3914 _ => panic!("Unexpected event {:?}", events_4[0]),
3916 let bs_announcement_sigs = match events_4[1] {
3917 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3918 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3921 _ => panic!("Unexpected event {:?}", events_4[1]),
3924 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3925 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3927 _ => panic!("Unexpected event {:?}", events_4[2]),
3930 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3931 // generates a duplicative private channel_update
3932 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3933 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3934 assert_eq!(events_5.len(), 1);
3936 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3937 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3939 _ => panic!("Unexpected event {:?}", events_5[0]),
3942 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3943 // announcement_signatures.
3944 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3945 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3946 assert_eq!(events_6.len(), 1);
3947 let as_announcement_sigs = match events_6[0] {
3948 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3949 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3952 _ => panic!("Unexpected event {:?}", events_6[0]),
3955 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3956 // broadcast the channel announcement globally, as well as re-send its (now-public)
3958 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3959 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3960 assert_eq!(events_7.len(), 1);
3961 let (chan_announcement, as_update) = match events_7[0] {
3962 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3963 (msg.clone(), update_msg.clone())
3965 _ => panic!("Unexpected event {:?}", events_7[0]),
3968 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3969 // same channel_announcement.
3970 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3971 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3972 assert_eq!(events_8.len(), 1);
3973 let bs_update = match events_8[0] {
3974 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3975 assert_eq!(*msg, chan_announcement);
3978 _ => panic!("Unexpected event {:?}", events_8[0]),
3981 // Provide the channel announcement and public updates to the network graph
3982 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3983 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3984 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3986 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3987 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3988 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3990 // Check that after deserialization and reconnection we can still generate an identical
3991 // channel_announcement from the cached signatures.
3992 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3994 let nodes_0_serialized = nodes[0].node.encode();
3995 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3996 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3998 persister = test_utils::TestPersister::new();
3999 let keys_manager = &chanmon_cfgs[0].keys_manager;
4000 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);
4001 nodes[0].chain_monitor = &new_chain_monitor;
4002 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4003 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4004 &mut chan_0_monitor_read, keys_manager).unwrap();
4005 assert!(chan_0_monitor_read.is_empty());
4007 let mut nodes_0_read = &nodes_0_serialized[..];
4008 let (_, nodes_0_deserialized_tmp) = {
4009 let mut channel_monitors = HashMap::new();
4010 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4011 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4012 default_config: UserConfig::default(),
4014 fee_estimator: node_cfgs[0].fee_estimator,
4015 chain_monitor: nodes[0].chain_monitor,
4016 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4017 logger: nodes[0].logger,
4021 nodes_0_deserialized = nodes_0_deserialized_tmp;
4022 assert!(nodes_0_read.is_empty());
4024 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4025 nodes[0].node = &nodes_0_deserialized;
4026 check_added_monitors!(nodes[0], 1);
4028 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4030 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4031 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4032 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4033 let mut found_announcement = false;
4034 for event in msgs.iter() {
4036 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4037 if *msg == chan_announcement { found_announcement = true; }
4039 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4040 _ => panic!("Unexpected event"),
4043 assert!(found_announcement);
4047 fn test_channel_ready_without_best_block_updated() {
4048 // Previously, if we were offline when a funding transaction was locked in, and then we came
4049 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4050 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4051 // channel_ready immediately instead.
4052 let chanmon_cfgs = create_chanmon_cfgs(2);
4053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4055 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4056 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4058 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4060 let conf_height = nodes[0].best_block_info().1 + 1;
4061 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4062 let block_txn = [funding_tx];
4063 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4064 let conf_block_header = nodes[0].get_block_header(conf_height);
4065 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4067 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4068 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4069 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4073 fn test_drop_messages_peer_disconnect_dual_htlc() {
4074 // Test that we can handle reconnecting when both sides of a channel have pending
4075 // commitment_updates when we disconnect.
4076 let chanmon_cfgs = create_chanmon_cfgs(2);
4077 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4078 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4079 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4080 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4082 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4084 // Now try to send a second payment which will fail to send
4085 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4086 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4087 check_added_monitors!(nodes[0], 1);
4089 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4090 assert_eq!(events_1.len(), 1);
4092 MessageSendEvent::UpdateHTLCs { .. } => {},
4093 _ => panic!("Unexpected event"),
4096 nodes[1].node.claim_funds(payment_preimage_1);
4097 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4098 check_added_monitors!(nodes[1], 1);
4100 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4101 assert_eq!(events_2.len(), 1);
4103 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 } } => {
4104 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4105 assert!(update_add_htlcs.is_empty());
4106 assert_eq!(update_fulfill_htlcs.len(), 1);
4107 assert!(update_fail_htlcs.is_empty());
4108 assert!(update_fail_malformed_htlcs.is_empty());
4109 assert!(update_fee.is_none());
4111 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4112 let events_3 = nodes[0].node.get_and_clear_pending_events();
4113 assert_eq!(events_3.len(), 1);
4115 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4116 assert_eq!(*payment_preimage, payment_preimage_1);
4117 assert_eq!(*payment_hash, payment_hash_1);
4119 _ => panic!("Unexpected event"),
4122 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4123 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4124 // No commitment_signed so get_event_msg's assert(len == 1) passes
4125 check_added_monitors!(nodes[0], 1);
4127 _ => panic!("Unexpected event"),
4130 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4131 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4133 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4134 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4135 assert_eq!(reestablish_1.len(), 1);
4136 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4137 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4138 assert_eq!(reestablish_2.len(), 1);
4140 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4141 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4142 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4143 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4145 assert!(as_resp.0.is_none());
4146 assert!(bs_resp.0.is_none());
4148 assert!(bs_resp.1.is_none());
4149 assert!(bs_resp.2.is_none());
4151 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4153 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4154 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4155 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4156 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4157 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4158 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4159 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4160 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4161 // No commitment_signed so get_event_msg's assert(len == 1) passes
4162 check_added_monitors!(nodes[1], 1);
4164 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4165 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4166 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4167 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4168 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4169 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4170 assert!(bs_second_commitment_signed.update_fee.is_none());
4171 check_added_monitors!(nodes[1], 1);
4173 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4174 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4175 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4176 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4177 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4178 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4179 assert!(as_commitment_signed.update_fee.is_none());
4180 check_added_monitors!(nodes[0], 1);
4182 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4183 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4184 // No commitment_signed so get_event_msg's assert(len == 1) passes
4185 check_added_monitors!(nodes[0], 1);
4187 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4188 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4189 // No commitment_signed so get_event_msg's assert(len == 1) passes
4190 check_added_monitors!(nodes[1], 1);
4192 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4193 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4194 check_added_monitors!(nodes[1], 1);
4196 expect_pending_htlcs_forwardable!(nodes[1]);
4198 let events_5 = nodes[1].node.get_and_clear_pending_events();
4199 assert_eq!(events_5.len(), 1);
4201 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4202 assert_eq!(payment_hash_2, *payment_hash);
4204 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4205 assert!(payment_preimage.is_none());
4206 assert_eq!(payment_secret_2, *payment_secret);
4208 _ => panic!("expected PaymentPurpose::InvoicePayment")
4211 _ => panic!("Unexpected event"),
4214 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4215 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4216 check_added_monitors!(nodes[0], 1);
4218 expect_payment_path_successful!(nodes[0]);
4219 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4222 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4223 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4224 // to avoid our counterparty failing the channel.
4225 let chanmon_cfgs = create_chanmon_cfgs(2);
4226 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4227 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4228 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4230 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4232 let our_payment_hash = if send_partial_mpp {
4233 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4234 // Use the utility function send_payment_along_path to send the payment with MPP data which
4235 // indicates there are more HTLCs coming.
4236 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.
4237 let payment_id = PaymentId([42; 32]);
4238 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();
4239 check_added_monitors!(nodes[0], 1);
4240 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4241 assert_eq!(events.len(), 1);
4242 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4243 // hop should *not* yet generate any PaymentReceived event(s).
4244 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4247 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4250 let mut block = Block {
4251 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4254 connect_block(&nodes[0], &block);
4255 connect_block(&nodes[1], &block);
4256 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4257 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4258 block.header.prev_blockhash = block.block_hash();
4259 connect_block(&nodes[0], &block);
4260 connect_block(&nodes[1], &block);
4263 expect_pending_htlcs_forwardable!(nodes[1]);
4265 check_added_monitors!(nodes[1], 1);
4266 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4267 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4268 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4269 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4270 assert!(htlc_timeout_updates.update_fee.is_none());
4272 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4273 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4274 // 100_000 msat as u64, followed by the height at which we failed back above
4275 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4276 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4277 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4281 fn test_htlc_timeout() {
4282 do_test_htlc_timeout(true);
4283 do_test_htlc_timeout(false);
4286 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4287 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4288 let chanmon_cfgs = create_chanmon_cfgs(3);
4289 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4290 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4291 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4292 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4293 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4295 // Make sure all nodes are at the same starting height
4296 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4297 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4298 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4300 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4301 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4303 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4305 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4306 check_added_monitors!(nodes[1], 1);
4308 // Now attempt to route a second payment, which should be placed in the holding cell
4309 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4310 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4311 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4313 check_added_monitors!(nodes[0], 1);
4314 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4315 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4316 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4317 expect_pending_htlcs_forwardable!(nodes[1]);
4319 check_added_monitors!(nodes[1], 0);
4321 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4322 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4323 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4324 connect_blocks(&nodes[1], 1);
4327 expect_pending_htlcs_forwardable!(nodes[1]);
4328 check_added_monitors!(nodes[1], 1);
4329 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4330 assert_eq!(fail_commit.len(), 1);
4331 match fail_commit[0] {
4332 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4333 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4334 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4336 _ => unreachable!(),
4338 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4340 let events = nodes[1].node.get_and_clear_pending_events();
4341 assert_eq!(events.len(), 2);
4342 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4343 assert_eq!(*payment_hash, second_payment_hash);
4344 } else { panic!("Unexpected event"); }
4345 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4346 assert_eq!(*payment_hash, second_payment_hash);
4347 } else { panic!("Unexpected event"); }
4352 fn test_holding_cell_htlc_add_timeouts() {
4353 do_test_holding_cell_htlc_add_timeouts(false);
4354 do_test_holding_cell_htlc_add_timeouts(true);
4358 fn test_no_txn_manager_serialize_deserialize() {
4359 let chanmon_cfgs = create_chanmon_cfgs(2);
4360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4362 let logger: test_utils::TestLogger;
4363 let fee_estimator: test_utils::TestFeeEstimator;
4364 let persister: test_utils::TestPersister;
4365 let new_chain_monitor: test_utils::TestChainMonitor;
4366 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4367 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4369 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4371 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4373 let nodes_0_serialized = nodes[0].node.encode();
4374 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4375 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4376 .write(&mut chan_0_monitor_serialized).unwrap();
4378 logger = test_utils::TestLogger::new();
4379 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4380 persister = test_utils::TestPersister::new();
4381 let keys_manager = &chanmon_cfgs[0].keys_manager;
4382 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4383 nodes[0].chain_monitor = &new_chain_monitor;
4384 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4385 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4386 &mut chan_0_monitor_read, keys_manager).unwrap();
4387 assert!(chan_0_monitor_read.is_empty());
4389 let mut nodes_0_read = &nodes_0_serialized[..];
4390 let config = UserConfig::default();
4391 let (_, nodes_0_deserialized_tmp) = {
4392 let mut channel_monitors = HashMap::new();
4393 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4394 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4395 default_config: config,
4397 fee_estimator: &fee_estimator,
4398 chain_monitor: nodes[0].chain_monitor,
4399 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4404 nodes_0_deserialized = nodes_0_deserialized_tmp;
4405 assert!(nodes_0_read.is_empty());
4407 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4408 nodes[0].node = &nodes_0_deserialized;
4409 assert_eq!(nodes[0].node.list_channels().len(), 1);
4410 check_added_monitors!(nodes[0], 1);
4412 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4413 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4414 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4415 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4417 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4418 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4419 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4420 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4422 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4423 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4424 for node in nodes.iter() {
4425 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4426 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4427 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4430 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4434 fn test_manager_serialize_deserialize_events() {
4435 // This test makes sure the events field in ChannelManager survives de/serialization
4436 let chanmon_cfgs = create_chanmon_cfgs(2);
4437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4439 let fee_estimator: test_utils::TestFeeEstimator;
4440 let persister: test_utils::TestPersister;
4441 let logger: test_utils::TestLogger;
4442 let new_chain_monitor: test_utils::TestChainMonitor;
4443 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4444 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4446 // Start creating a channel, but stop right before broadcasting the funding transaction
4447 let channel_value = 100000;
4448 let push_msat = 10001;
4449 let a_flags = InitFeatures::known();
4450 let b_flags = InitFeatures::known();
4451 let node_a = nodes.remove(0);
4452 let node_b = nodes.remove(0);
4453 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4454 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()));
4455 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()));
4457 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4459 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4460 check_added_monitors!(node_a, 0);
4462 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()));
4464 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4465 assert_eq!(added_monitors.len(), 1);
4466 assert_eq!(added_monitors[0].0, funding_output);
4467 added_monitors.clear();
4470 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4471 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4473 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4474 assert_eq!(added_monitors.len(), 1);
4475 assert_eq!(added_monitors[0].0, funding_output);
4476 added_monitors.clear();
4478 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4483 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4484 let nodes_0_serialized = nodes[0].node.encode();
4485 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4486 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4488 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4489 logger = test_utils::TestLogger::new();
4490 persister = test_utils::TestPersister::new();
4491 let keys_manager = &chanmon_cfgs[0].keys_manager;
4492 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4493 nodes[0].chain_monitor = &new_chain_monitor;
4494 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4495 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4496 &mut chan_0_monitor_read, keys_manager).unwrap();
4497 assert!(chan_0_monitor_read.is_empty());
4499 let mut nodes_0_read = &nodes_0_serialized[..];
4500 let config = UserConfig::default();
4501 let (_, nodes_0_deserialized_tmp) = {
4502 let mut channel_monitors = HashMap::new();
4503 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4504 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4505 default_config: config,
4507 fee_estimator: &fee_estimator,
4508 chain_monitor: nodes[0].chain_monitor,
4509 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4514 nodes_0_deserialized = nodes_0_deserialized_tmp;
4515 assert!(nodes_0_read.is_empty());
4517 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4519 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4520 nodes[0].node = &nodes_0_deserialized;
4522 // After deserializing, make sure the funding_transaction is still held by the channel manager
4523 let events_4 = nodes[0].node.get_and_clear_pending_events();
4524 assert_eq!(events_4.len(), 0);
4525 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4526 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4528 // Make sure the channel is functioning as though the de/serialization never happened
4529 assert_eq!(nodes[0].node.list_channels().len(), 1);
4530 check_added_monitors!(nodes[0], 1);
4532 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4533 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4534 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4535 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4537 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4538 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4539 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4540 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4542 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4543 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4544 for node in nodes.iter() {
4545 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4546 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4547 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4550 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4554 fn test_simple_manager_serialize_deserialize() {
4555 let chanmon_cfgs = create_chanmon_cfgs(2);
4556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4558 let logger: test_utils::TestLogger;
4559 let fee_estimator: test_utils::TestFeeEstimator;
4560 let persister: test_utils::TestPersister;
4561 let new_chain_monitor: test_utils::TestChainMonitor;
4562 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4563 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4564 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4566 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4567 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4569 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4571 let nodes_0_serialized = nodes[0].node.encode();
4572 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4573 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4575 logger = test_utils::TestLogger::new();
4576 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4577 persister = test_utils::TestPersister::new();
4578 let keys_manager = &chanmon_cfgs[0].keys_manager;
4579 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4580 nodes[0].chain_monitor = &new_chain_monitor;
4581 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4582 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4583 &mut chan_0_monitor_read, keys_manager).unwrap();
4584 assert!(chan_0_monitor_read.is_empty());
4586 let mut nodes_0_read = &nodes_0_serialized[..];
4587 let (_, nodes_0_deserialized_tmp) = {
4588 let mut channel_monitors = HashMap::new();
4589 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4590 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4591 default_config: UserConfig::default(),
4593 fee_estimator: &fee_estimator,
4594 chain_monitor: nodes[0].chain_monitor,
4595 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4600 nodes_0_deserialized = nodes_0_deserialized_tmp;
4601 assert!(nodes_0_read.is_empty());
4603 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4604 nodes[0].node = &nodes_0_deserialized;
4605 check_added_monitors!(nodes[0], 1);
4607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4609 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4610 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4614 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4615 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4616 let chanmon_cfgs = create_chanmon_cfgs(4);
4617 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4618 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4619 let logger: test_utils::TestLogger;
4620 let fee_estimator: test_utils::TestFeeEstimator;
4621 let persister: test_utils::TestPersister;
4622 let new_chain_monitor: test_utils::TestChainMonitor;
4623 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4624 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4625 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4626 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4627 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4629 let mut node_0_stale_monitors_serialized = Vec::new();
4630 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4631 let mut writer = test_utils::TestVecWriter(Vec::new());
4632 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4633 node_0_stale_monitors_serialized.push(writer.0);
4636 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4638 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4639 let nodes_0_serialized = nodes[0].node.encode();
4641 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4642 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4643 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4644 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4646 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4648 let mut node_0_monitors_serialized = Vec::new();
4649 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4650 let mut writer = test_utils::TestVecWriter(Vec::new());
4651 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4652 node_0_monitors_serialized.push(writer.0);
4655 logger = test_utils::TestLogger::new();
4656 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4657 persister = test_utils::TestPersister::new();
4658 let keys_manager = &chanmon_cfgs[0].keys_manager;
4659 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4660 nodes[0].chain_monitor = &new_chain_monitor;
4663 let mut node_0_stale_monitors = Vec::new();
4664 for serialized in node_0_stale_monitors_serialized.iter() {
4665 let mut read = &serialized[..];
4666 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4667 assert!(read.is_empty());
4668 node_0_stale_monitors.push(monitor);
4671 let mut node_0_monitors = Vec::new();
4672 for serialized in node_0_monitors_serialized.iter() {
4673 let mut read = &serialized[..];
4674 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4675 assert!(read.is_empty());
4676 node_0_monitors.push(monitor);
4679 let mut nodes_0_read = &nodes_0_serialized[..];
4680 if let Err(msgs::DecodeError::InvalidValue) =
4681 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4682 default_config: UserConfig::default(),
4684 fee_estimator: &fee_estimator,
4685 chain_monitor: nodes[0].chain_monitor,
4686 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4688 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4690 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4693 let mut nodes_0_read = &nodes_0_serialized[..];
4694 let (_, nodes_0_deserialized_tmp) =
4695 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4696 default_config: UserConfig::default(),
4698 fee_estimator: &fee_estimator,
4699 chain_monitor: nodes[0].chain_monitor,
4700 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4702 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4704 nodes_0_deserialized = nodes_0_deserialized_tmp;
4705 assert!(nodes_0_read.is_empty());
4707 { // Channel close should result in a commitment tx
4708 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4709 assert_eq!(txn.len(), 1);
4710 check_spends!(txn[0], funding_tx);
4711 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4714 for monitor in node_0_monitors.drain(..) {
4715 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4716 check_added_monitors!(nodes[0], 1);
4718 nodes[0].node = &nodes_0_deserialized;
4719 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4721 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4722 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4723 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4724 //... and we can even still claim the payment!
4725 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4727 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4728 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4729 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4730 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4731 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4732 assert_eq!(msg_events.len(), 1);
4733 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4735 &ErrorAction::SendErrorMessage { ref msg } => {
4736 assert_eq!(msg.channel_id, channel_id);
4738 _ => panic!("Unexpected event!"),
4743 macro_rules! check_spendable_outputs {
4744 ($node: expr, $keysinterface: expr) => {
4746 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4747 let mut txn = Vec::new();
4748 let mut all_outputs = Vec::new();
4749 let secp_ctx = Secp256k1::new();
4750 for event in events.drain(..) {
4752 Event::SpendableOutputs { mut outputs } => {
4753 for outp in outputs.drain(..) {
4754 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4755 all_outputs.push(outp);
4758 _ => panic!("Unexpected event"),
4761 if all_outputs.len() > 1 {
4762 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) {
4772 fn test_claim_sizeable_push_msat() {
4773 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4774 let chanmon_cfgs = create_chanmon_cfgs(2);
4775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4777 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4780 nodes[1].node.force_close_channel(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4781 check_closed_broadcast!(nodes[1], true);
4782 check_added_monitors!(nodes[1], 1);
4783 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4784 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4785 assert_eq!(node_txn.len(), 1);
4786 check_spends!(node_txn[0], chan.3);
4787 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
4789 mine_transaction(&nodes[1], &node_txn[0]);
4790 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4792 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4793 assert_eq!(spend_txn.len(), 1);
4794 assert_eq!(spend_txn[0].input.len(), 1);
4795 check_spends!(spend_txn[0], node_txn[0]);
4796 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4800 fn test_claim_on_remote_sizeable_push_msat() {
4801 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4802 // to_remote output is encumbered by a P2WPKH
4803 let chanmon_cfgs = create_chanmon_cfgs(2);
4804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4806 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4808 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4809 nodes[0].node.force_close_channel(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4810 check_closed_broadcast!(nodes[0], true);
4811 check_added_monitors!(nodes[0], 1);
4812 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4814 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4815 assert_eq!(node_txn.len(), 1);
4816 check_spends!(node_txn[0], chan.3);
4817 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
4819 mine_transaction(&nodes[1], &node_txn[0]);
4820 check_closed_broadcast!(nodes[1], true);
4821 check_added_monitors!(nodes[1], 1);
4822 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4823 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4825 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4826 assert_eq!(spend_txn.len(), 1);
4827 check_spends!(spend_txn[0], node_txn[0]);
4831 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4832 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4833 // to_remote output is encumbered by a P2WPKH
4835 let chanmon_cfgs = create_chanmon_cfgs(2);
4836 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4837 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4838 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4840 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4841 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4842 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4843 assert_eq!(revoked_local_txn[0].input.len(), 1);
4844 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4846 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4847 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4848 check_closed_broadcast!(nodes[1], true);
4849 check_added_monitors!(nodes[1], 1);
4850 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4852 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4853 mine_transaction(&nodes[1], &node_txn[0]);
4854 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4856 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4857 assert_eq!(spend_txn.len(), 3);
4858 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4859 check_spends!(spend_txn[1], node_txn[0]);
4860 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4864 fn test_static_spendable_outputs_preimage_tx() {
4865 let chanmon_cfgs = create_chanmon_cfgs(2);
4866 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4867 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4868 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4870 // Create some initial channels
4871 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4873 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4875 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4876 assert_eq!(commitment_tx[0].input.len(), 1);
4877 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4879 // Settle A's commitment tx on B's chain
4880 nodes[1].node.claim_funds(payment_preimage);
4881 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4882 check_added_monitors!(nodes[1], 1);
4883 mine_transaction(&nodes[1], &commitment_tx[0]);
4884 check_added_monitors!(nodes[1], 1);
4885 let events = nodes[1].node.get_and_clear_pending_msg_events();
4887 MessageSendEvent::UpdateHTLCs { .. } => {},
4888 _ => panic!("Unexpected event"),
4891 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4892 _ => panic!("Unexepected event"),
4895 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4896 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4897 assert_eq!(node_txn.len(), 3);
4898 check_spends!(node_txn[0], commitment_tx[0]);
4899 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4900 check_spends!(node_txn[1], chan_1.3);
4901 check_spends!(node_txn[2], node_txn[1]);
4903 mine_transaction(&nodes[1], &node_txn[0]);
4904 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4905 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4907 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4908 assert_eq!(spend_txn.len(), 1);
4909 check_spends!(spend_txn[0], node_txn[0]);
4913 fn test_static_spendable_outputs_timeout_tx() {
4914 let chanmon_cfgs = create_chanmon_cfgs(2);
4915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4917 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4919 // Create some initial channels
4920 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4922 // Rebalance the network a bit by relaying one payment through all the channels ...
4923 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4925 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4927 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4928 assert_eq!(commitment_tx[0].input.len(), 1);
4929 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4931 // Settle A's commitment tx on B' chain
4932 mine_transaction(&nodes[1], &commitment_tx[0]);
4933 check_added_monitors!(nodes[1], 1);
4934 let events = nodes[1].node.get_and_clear_pending_msg_events();
4936 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4937 _ => panic!("Unexpected event"),
4939 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4941 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4942 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4943 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4944 check_spends!(node_txn[0], chan_1.3.clone());
4945 check_spends!(node_txn[1], commitment_tx[0].clone());
4946 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4948 mine_transaction(&nodes[1], &node_txn[1]);
4949 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4950 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4951 expect_payment_failed!(nodes[1], our_payment_hash, true);
4953 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4954 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4955 check_spends!(spend_txn[0], commitment_tx[0]);
4956 check_spends!(spend_txn[1], node_txn[1]);
4957 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4961 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4962 let chanmon_cfgs = create_chanmon_cfgs(2);
4963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4965 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4967 // Create some initial channels
4968 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4970 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4971 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4972 assert_eq!(revoked_local_txn[0].input.len(), 1);
4973 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4975 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4977 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4978 check_closed_broadcast!(nodes[1], true);
4979 check_added_monitors!(nodes[1], 1);
4980 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4982 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4983 assert_eq!(node_txn.len(), 2);
4984 assert_eq!(node_txn[0].input.len(), 2);
4985 check_spends!(node_txn[0], revoked_local_txn[0]);
4987 mine_transaction(&nodes[1], &node_txn[0]);
4988 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4990 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4991 assert_eq!(spend_txn.len(), 1);
4992 check_spends!(spend_txn[0], node_txn[0]);
4996 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4997 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4998 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4999 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5000 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5001 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5003 // Create some initial channels
5004 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5006 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5007 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5008 assert_eq!(revoked_local_txn[0].input.len(), 1);
5009 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5011 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5013 // A will generate HTLC-Timeout from revoked commitment tx
5014 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5015 check_closed_broadcast!(nodes[0], true);
5016 check_added_monitors!(nodes[0], 1);
5017 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5018 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5020 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5021 assert_eq!(revoked_htlc_txn.len(), 2);
5022 check_spends!(revoked_htlc_txn[0], chan_1.3);
5023 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5024 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5025 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5026 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5028 // B will generate justice tx from A's revoked commitment/HTLC tx
5029 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5030 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5031 check_closed_broadcast!(nodes[1], true);
5032 check_added_monitors!(nodes[1], 1);
5033 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5035 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5036 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5037 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5038 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5039 // transactions next...
5040 assert_eq!(node_txn[0].input.len(), 3);
5041 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5043 assert_eq!(node_txn[1].input.len(), 2);
5044 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5045 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5046 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5048 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5049 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5052 assert_eq!(node_txn[2].input.len(), 1);
5053 check_spends!(node_txn[2], chan_1.3);
5055 mine_transaction(&nodes[1], &node_txn[1]);
5056 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5058 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5059 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5060 assert_eq!(spend_txn.len(), 1);
5061 assert_eq!(spend_txn[0].input.len(), 1);
5062 check_spends!(spend_txn[0], node_txn[1]);
5066 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5067 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5068 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5069 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5070 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5071 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5073 // Create some initial channels
5074 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5076 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5077 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5078 assert_eq!(revoked_local_txn[0].input.len(), 1);
5079 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5081 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5082 assert_eq!(revoked_local_txn[0].output.len(), 2);
5084 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5086 // B will generate HTLC-Success from revoked commitment tx
5087 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5088 check_closed_broadcast!(nodes[1], true);
5089 check_added_monitors!(nodes[1], 1);
5090 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5091 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5093 assert_eq!(revoked_htlc_txn.len(), 2);
5094 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5095 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5096 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5098 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5099 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5100 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5102 // A will generate justice tx from B's revoked commitment/HTLC tx
5103 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5104 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5105 check_closed_broadcast!(nodes[0], true);
5106 check_added_monitors!(nodes[0], 1);
5107 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5109 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5110 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5112 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5113 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5114 // transactions next...
5115 assert_eq!(node_txn[0].input.len(), 2);
5116 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5117 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5118 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5120 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5121 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5124 assert_eq!(node_txn[1].input.len(), 1);
5125 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5127 check_spends!(node_txn[2], chan_1.3);
5129 mine_transaction(&nodes[0], &node_txn[1]);
5130 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5132 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5133 // didn't try to generate any new transactions.
5135 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5136 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5137 assert_eq!(spend_txn.len(), 3);
5138 assert_eq!(spend_txn[0].input.len(), 1);
5139 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5140 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5141 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5142 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5146 fn test_onchain_to_onchain_claim() {
5147 // Test that in case of channel closure, we detect the state of output and claim HTLC
5148 // on downstream peer's remote commitment tx.
5149 // First, have C claim an HTLC against its own latest commitment transaction.
5150 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5152 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5155 let chanmon_cfgs = create_chanmon_cfgs(3);
5156 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5157 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5158 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5160 // Create some initial channels
5161 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5162 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5164 // Ensure all nodes are at the same height
5165 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5166 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5167 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5168 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5170 // Rebalance the network a bit by relaying one payment through all the channels ...
5171 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5172 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5174 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5175 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5176 check_spends!(commitment_tx[0], chan_2.3);
5177 nodes[2].node.claim_funds(payment_preimage);
5178 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5179 check_added_monitors!(nodes[2], 1);
5180 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5181 assert!(updates.update_add_htlcs.is_empty());
5182 assert!(updates.update_fail_htlcs.is_empty());
5183 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5184 assert!(updates.update_fail_malformed_htlcs.is_empty());
5186 mine_transaction(&nodes[2], &commitment_tx[0]);
5187 check_closed_broadcast!(nodes[2], true);
5188 check_added_monitors!(nodes[2], 1);
5189 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5191 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5192 assert_eq!(c_txn.len(), 3);
5193 assert_eq!(c_txn[0], c_txn[2]);
5194 assert_eq!(commitment_tx[0], c_txn[1]);
5195 check_spends!(c_txn[1], chan_2.3);
5196 check_spends!(c_txn[2], c_txn[1]);
5197 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5198 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5199 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5200 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5202 // 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
5203 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5204 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5205 check_added_monitors!(nodes[1], 1);
5206 let events = nodes[1].node.get_and_clear_pending_events();
5207 assert_eq!(events.len(), 2);
5209 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5210 _ => panic!("Unexpected event"),
5213 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5214 assert_eq!(fee_earned_msat, Some(1000));
5215 assert_eq!(prev_channel_id, Some(chan_1.2));
5216 assert_eq!(claim_from_onchain_tx, true);
5217 assert_eq!(next_channel_id, Some(chan_2.2));
5219 _ => panic!("Unexpected event"),
5222 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5223 // ChannelMonitor: claim tx
5224 assert_eq!(b_txn.len(), 1);
5225 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5228 check_added_monitors!(nodes[1], 1);
5229 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5230 assert_eq!(msg_events.len(), 3);
5231 match msg_events[0] {
5232 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5233 _ => panic!("Unexpected event"),
5235 match msg_events[1] {
5236 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5237 _ => panic!("Unexpected event"),
5239 match msg_events[2] {
5240 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, .. } } => {
5241 assert!(update_add_htlcs.is_empty());
5242 assert!(update_fail_htlcs.is_empty());
5243 assert_eq!(update_fulfill_htlcs.len(), 1);
5244 assert!(update_fail_malformed_htlcs.is_empty());
5245 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5247 _ => panic!("Unexpected event"),
5249 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5250 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5251 mine_transaction(&nodes[1], &commitment_tx[0]);
5252 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5253 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5254 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5255 assert_eq!(b_txn.len(), 3);
5256 check_spends!(b_txn[1], chan_1.3);
5257 check_spends!(b_txn[2], b_txn[1]);
5258 check_spends!(b_txn[0], commitment_tx[0]);
5259 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5260 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5261 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5263 check_closed_broadcast!(nodes[1], true);
5264 check_added_monitors!(nodes[1], 1);
5268 fn test_duplicate_payment_hash_one_failure_one_success() {
5269 // Topology : A --> B --> C --> D
5270 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5271 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5272 // we forward one of the payments onwards to D.
5273 let chanmon_cfgs = create_chanmon_cfgs(4);
5274 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5275 // When this test was written, the default base fee floated based on the HTLC count.
5276 // It is now fixed, so we simply set the fee to the expected value here.
5277 let mut config = test_default_channel_config();
5278 config.channel_config.forwarding_fee_base_msat = 196;
5279 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5280 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5281 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5283 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5284 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5285 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5287 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5288 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5289 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5290 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5291 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5293 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5295 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5296 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5297 // script push size limit so that the below script length checks match
5298 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5299 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5300 .with_features(InvoiceFeatures::known());
5301 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5302 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5304 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5305 assert_eq!(commitment_txn[0].input.len(), 1);
5306 check_spends!(commitment_txn[0], chan_2.3);
5308 mine_transaction(&nodes[1], &commitment_txn[0]);
5309 check_closed_broadcast!(nodes[1], true);
5310 check_added_monitors!(nodes[1], 1);
5311 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5312 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5314 let htlc_timeout_tx;
5315 { // Extract one of the two HTLC-Timeout transaction
5316 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5317 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5318 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5319 check_spends!(node_txn[0], chan_2.3);
5321 check_spends!(node_txn[1], commitment_txn[0]);
5322 assert_eq!(node_txn[1].input.len(), 1);
5324 if node_txn.len() > 3 {
5325 check_spends!(node_txn[2], commitment_txn[0]);
5326 assert_eq!(node_txn[2].input.len(), 1);
5327 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5329 check_spends!(node_txn[3], commitment_txn[0]);
5330 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5332 check_spends!(node_txn[2], commitment_txn[0]);
5333 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5336 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5337 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5338 if node_txn.len() > 3 {
5339 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5341 htlc_timeout_tx = node_txn[1].clone();
5344 nodes[2].node.claim_funds(our_payment_preimage);
5345 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5347 mine_transaction(&nodes[2], &commitment_txn[0]);
5348 check_added_monitors!(nodes[2], 2);
5349 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5350 let events = nodes[2].node.get_and_clear_pending_msg_events();
5352 MessageSendEvent::UpdateHTLCs { .. } => {},
5353 _ => panic!("Unexpected event"),
5356 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5357 _ => panic!("Unexepected event"),
5359 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5360 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)
5361 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5362 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5363 assert_eq!(htlc_success_txn[0].input.len(), 1);
5364 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5365 assert_eq!(htlc_success_txn[1].input.len(), 1);
5366 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5367 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5368 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5369 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5370 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5371 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5373 mine_transaction(&nodes[1], &htlc_timeout_tx);
5374 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5375 expect_pending_htlcs_forwardable!(nodes[1]);
5376 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5377 assert!(htlc_updates.update_add_htlcs.is_empty());
5378 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5379 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5380 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5381 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5382 check_added_monitors!(nodes[1], 1);
5384 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5385 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5387 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5389 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5391 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5392 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5393 // and nodes[2] fee) is rounded down and then claimed in full.
5394 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5395 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5396 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5397 assert!(updates.update_add_htlcs.is_empty());
5398 assert!(updates.update_fail_htlcs.is_empty());
5399 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5400 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5401 assert!(updates.update_fail_malformed_htlcs.is_empty());
5402 check_added_monitors!(nodes[1], 1);
5404 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5405 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5407 let events = nodes[0].node.get_and_clear_pending_events();
5409 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5410 assert_eq!(*payment_preimage, our_payment_preimage);
5411 assert_eq!(*payment_hash, duplicate_payment_hash);
5413 _ => panic!("Unexpected event"),
5418 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5419 let chanmon_cfgs = create_chanmon_cfgs(2);
5420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5422 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5424 // Create some initial channels
5425 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5427 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5428 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5429 assert_eq!(local_txn.len(), 1);
5430 assert_eq!(local_txn[0].input.len(), 1);
5431 check_spends!(local_txn[0], chan_1.3);
5433 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5434 nodes[1].node.claim_funds(payment_preimage);
5435 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5436 check_added_monitors!(nodes[1], 1);
5438 mine_transaction(&nodes[1], &local_txn[0]);
5439 check_added_monitors!(nodes[1], 1);
5440 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5441 let events = nodes[1].node.get_and_clear_pending_msg_events();
5443 MessageSendEvent::UpdateHTLCs { .. } => {},
5444 _ => panic!("Unexpected event"),
5447 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5448 _ => panic!("Unexepected event"),
5451 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5452 assert_eq!(node_txn.len(), 3);
5453 assert_eq!(node_txn[0], node_txn[2]);
5454 assert_eq!(node_txn[1], local_txn[0]);
5455 assert_eq!(node_txn[0].input.len(), 1);
5456 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5457 check_spends!(node_txn[0], local_txn[0]);
5461 mine_transaction(&nodes[1], &node_tx);
5462 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5464 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5465 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5466 assert_eq!(spend_txn.len(), 1);
5467 assert_eq!(spend_txn[0].input.len(), 1);
5468 check_spends!(spend_txn[0], node_tx);
5469 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5472 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5473 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5474 // unrevoked commitment transaction.
5475 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5476 // a remote RAA before they could be failed backwards (and combinations thereof).
5477 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5478 // use the same payment hashes.
5479 // Thus, we use a six-node network:
5484 // And test where C fails back to A/B when D announces its latest commitment transaction
5485 let chanmon_cfgs = create_chanmon_cfgs(6);
5486 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5487 // When this test was written, the default base fee floated based on the HTLC count.
5488 // It is now fixed, so we simply set the fee to the expected value here.
5489 let mut config = test_default_channel_config();
5490 config.channel_config.forwarding_fee_base_msat = 196;
5491 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5492 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5493 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5495 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5496 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5497 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5498 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5499 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5501 // Rebalance and check output sanity...
5502 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5503 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5504 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5506 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5508 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
5510 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
5511 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5513 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
5515 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
5517 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5519 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5520 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5522 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());
5524 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());
5527 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5529 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5530 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
5533 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
5535 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5536 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());
5538 // Double-check that six of the new HTLC were added
5539 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5540 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5541 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5542 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5544 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5545 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5546 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5547 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5548 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5549 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5550 check_added_monitors!(nodes[4], 0);
5551 expect_pending_htlcs_forwardable!(nodes[4]);
5552 check_added_monitors!(nodes[4], 1);
5554 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5555 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5556 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5557 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5558 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5559 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5561 // Fail 3rd below-dust and 7th above-dust HTLCs
5562 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5563 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5564 check_added_monitors!(nodes[5], 0);
5565 expect_pending_htlcs_forwardable!(nodes[5]);
5566 check_added_monitors!(nodes[5], 1);
5568 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5569 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5570 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5571 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5573 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5575 expect_pending_htlcs_forwardable!(nodes[3]);
5576 check_added_monitors!(nodes[3], 1);
5577 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5578 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5579 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5580 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5581 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5582 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5583 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5584 if deliver_last_raa {
5585 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5587 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5590 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5591 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5592 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5593 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5595 // We now broadcast the latest commitment transaction, which *should* result in failures for
5596 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5597 // the non-broadcast above-dust HTLCs.
5599 // Alternatively, we may broadcast the previous commitment transaction, which should only
5600 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5601 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5603 if announce_latest {
5604 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5606 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5608 let events = nodes[2].node.get_and_clear_pending_events();
5609 let close_event = if deliver_last_raa {
5610 assert_eq!(events.len(), 2);
5613 assert_eq!(events.len(), 1);
5617 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5618 _ => panic!("Unexpected event"),
5621 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5622 check_closed_broadcast!(nodes[2], true);
5623 if deliver_last_raa {
5624 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5626 expect_pending_htlcs_forwardable!(nodes[2]);
5628 check_added_monitors!(nodes[2], 3);
5630 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5631 assert_eq!(cs_msgs.len(), 2);
5632 let mut a_done = false;
5633 for msg in cs_msgs {
5635 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5636 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5637 // should be failed-backwards here.
5638 let target = if *node_id == nodes[0].node.get_our_node_id() {
5639 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5640 for htlc in &updates.update_fail_htlcs {
5641 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 });
5643 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5648 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5649 for htlc in &updates.update_fail_htlcs {
5650 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5652 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5653 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5656 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5657 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5658 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5659 if announce_latest {
5660 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5661 if *node_id == nodes[0].node.get_our_node_id() {
5662 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5665 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5667 _ => panic!("Unexpected event"),
5671 let as_events = nodes[0].node.get_and_clear_pending_events();
5672 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5673 let mut as_failds = HashSet::new();
5674 let mut as_updates = 0;
5675 for event in as_events.iter() {
5676 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5677 assert!(as_failds.insert(*payment_hash));
5678 if *payment_hash != payment_hash_2 {
5679 assert_eq!(*rejected_by_dest, deliver_last_raa);
5681 assert!(!rejected_by_dest);
5683 if network_update.is_some() {
5686 } else { panic!("Unexpected event"); }
5688 assert!(as_failds.contains(&payment_hash_1));
5689 assert!(as_failds.contains(&payment_hash_2));
5690 if announce_latest {
5691 assert!(as_failds.contains(&payment_hash_3));
5692 assert!(as_failds.contains(&payment_hash_5));
5694 assert!(as_failds.contains(&payment_hash_6));
5696 let bs_events = nodes[1].node.get_and_clear_pending_events();
5697 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5698 let mut bs_failds = HashSet::new();
5699 let mut bs_updates = 0;
5700 for event in bs_events.iter() {
5701 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5702 assert!(bs_failds.insert(*payment_hash));
5703 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5704 assert_eq!(*rejected_by_dest, deliver_last_raa);
5706 assert!(!rejected_by_dest);
5708 if network_update.is_some() {
5711 } else { panic!("Unexpected event"); }
5713 assert!(bs_failds.contains(&payment_hash_1));
5714 assert!(bs_failds.contains(&payment_hash_2));
5715 if announce_latest {
5716 assert!(bs_failds.contains(&payment_hash_4));
5718 assert!(bs_failds.contains(&payment_hash_5));
5720 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5721 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5722 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5723 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5724 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5725 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5729 fn test_fail_backwards_latest_remote_announce_a() {
5730 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5734 fn test_fail_backwards_latest_remote_announce_b() {
5735 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5739 fn test_fail_backwards_previous_remote_announce() {
5740 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5741 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5742 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5746 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5747 let chanmon_cfgs = create_chanmon_cfgs(2);
5748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5750 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5752 // Create some initial channels
5753 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5755 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5756 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5757 assert_eq!(local_txn[0].input.len(), 1);
5758 check_spends!(local_txn[0], chan_1.3);
5760 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5761 mine_transaction(&nodes[0], &local_txn[0]);
5762 check_closed_broadcast!(nodes[0], true);
5763 check_added_monitors!(nodes[0], 1);
5764 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5765 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5767 let htlc_timeout = {
5768 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5769 assert_eq!(node_txn.len(), 2);
5770 check_spends!(node_txn[0], chan_1.3);
5771 assert_eq!(node_txn[1].input.len(), 1);
5772 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5773 check_spends!(node_txn[1], local_txn[0]);
5777 mine_transaction(&nodes[0], &htlc_timeout);
5778 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5779 expect_payment_failed!(nodes[0], our_payment_hash, true);
5781 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5782 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5783 assert_eq!(spend_txn.len(), 3);
5784 check_spends!(spend_txn[0], local_txn[0]);
5785 assert_eq!(spend_txn[1].input.len(), 1);
5786 check_spends!(spend_txn[1], htlc_timeout);
5787 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5788 assert_eq!(spend_txn[2].input.len(), 2);
5789 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5790 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5791 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5795 fn test_key_derivation_params() {
5796 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5797 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5798 // let us re-derive the channel key set to then derive a delayed_payment_key.
5800 let chanmon_cfgs = create_chanmon_cfgs(3);
5802 // We manually create the node configuration to backup the seed.
5803 let seed = [42; 32];
5804 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5805 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);
5806 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5807 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() };
5808 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5809 node_cfgs.remove(0);
5810 node_cfgs.insert(0, node);
5812 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5813 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5815 // Create some initial channels
5816 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5818 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5819 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5820 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5822 // Ensure all nodes are at the same height
5823 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5824 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5825 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5826 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5828 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5829 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5830 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5831 assert_eq!(local_txn_1[0].input.len(), 1);
5832 check_spends!(local_txn_1[0], chan_1.3);
5834 // We check funding pubkey are unique
5835 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]));
5836 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]));
5837 if from_0_funding_key_0 == from_1_funding_key_0
5838 || from_0_funding_key_0 == from_1_funding_key_1
5839 || from_0_funding_key_1 == from_1_funding_key_0
5840 || from_0_funding_key_1 == from_1_funding_key_1 {
5841 panic!("Funding pubkeys aren't unique");
5844 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5845 mine_transaction(&nodes[0], &local_txn_1[0]);
5846 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5847 check_closed_broadcast!(nodes[0], true);
5848 check_added_monitors!(nodes[0], 1);
5849 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5851 let htlc_timeout = {
5852 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5853 assert_eq!(node_txn[1].input.len(), 1);
5854 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5855 check_spends!(node_txn[1], local_txn_1[0]);
5859 mine_transaction(&nodes[0], &htlc_timeout);
5860 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5861 expect_payment_failed!(nodes[0], our_payment_hash, true);
5863 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5864 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5865 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5866 assert_eq!(spend_txn.len(), 3);
5867 check_spends!(spend_txn[0], local_txn_1[0]);
5868 assert_eq!(spend_txn[1].input.len(), 1);
5869 check_spends!(spend_txn[1], htlc_timeout);
5870 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5871 assert_eq!(spend_txn[2].input.len(), 2);
5872 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5873 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5874 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5878 fn test_static_output_closing_tx() {
5879 let chanmon_cfgs = create_chanmon_cfgs(2);
5880 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5881 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5882 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5884 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5886 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5887 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5889 mine_transaction(&nodes[0], &closing_tx);
5890 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5891 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5893 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5894 assert_eq!(spend_txn.len(), 1);
5895 check_spends!(spend_txn[0], closing_tx);
5897 mine_transaction(&nodes[1], &closing_tx);
5898 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5899 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5901 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5902 assert_eq!(spend_txn.len(), 1);
5903 check_spends!(spend_txn[0], closing_tx);
5906 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5907 let chanmon_cfgs = create_chanmon_cfgs(2);
5908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5911 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5913 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5915 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5916 // present in B's local commitment transaction, but none of A's commitment transactions.
5917 nodes[1].node.claim_funds(payment_preimage);
5918 check_added_monitors!(nodes[1], 1);
5919 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5921 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5922 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5923 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5925 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5926 check_added_monitors!(nodes[0], 1);
5927 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5928 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5929 check_added_monitors!(nodes[1], 1);
5931 let starting_block = nodes[1].best_block_info();
5932 let mut block = Block {
5933 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5936 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5937 connect_block(&nodes[1], &block);
5938 block.header.prev_blockhash = block.block_hash();
5940 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5941 check_closed_broadcast!(nodes[1], true);
5942 check_added_monitors!(nodes[1], 1);
5943 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5946 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5947 let chanmon_cfgs = create_chanmon_cfgs(2);
5948 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5949 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5950 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5951 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5953 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5954 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5955 check_added_monitors!(nodes[0], 1);
5957 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5959 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5960 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5961 // to "time out" the HTLC.
5963 let starting_block = nodes[1].best_block_info();
5964 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5966 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5967 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5968 header.prev_blockhash = header.block_hash();
5970 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5971 check_closed_broadcast!(nodes[0], true);
5972 check_added_monitors!(nodes[0], 1);
5973 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5976 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5977 let chanmon_cfgs = create_chanmon_cfgs(3);
5978 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5979 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5980 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5981 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5983 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5984 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5985 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5986 // actually revoked.
5987 let htlc_value = if use_dust { 50000 } else { 3000000 };
5988 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5989 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5990 expect_pending_htlcs_forwardable!(nodes[1]);
5991 check_added_monitors!(nodes[1], 1);
5993 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5994 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5995 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5996 check_added_monitors!(nodes[0], 1);
5997 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5998 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5999 check_added_monitors!(nodes[1], 1);
6000 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6001 check_added_monitors!(nodes[1], 1);
6002 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6004 if check_revoke_no_close {
6005 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6006 check_added_monitors!(nodes[0], 1);
6009 let starting_block = nodes[1].best_block_info();
6010 let mut block = Block {
6011 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6014 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6015 connect_block(&nodes[0], &block);
6016 block.header.prev_blockhash = block.block_hash();
6018 if !check_revoke_no_close {
6019 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6020 check_closed_broadcast!(nodes[0], true);
6021 check_added_monitors!(nodes[0], 1);
6022 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6024 let events = nodes[0].node.get_and_clear_pending_events();
6025 assert_eq!(events.len(), 2);
6026 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6027 assert_eq!(*payment_hash, our_payment_hash);
6028 } else { panic!("Unexpected event"); }
6029 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6030 assert_eq!(*payment_hash, our_payment_hash);
6031 } else { panic!("Unexpected event"); }
6035 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6036 // There are only a few cases to test here:
6037 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6038 // broadcastable commitment transactions result in channel closure,
6039 // * its included in an unrevoked-but-previous remote commitment transaction,
6040 // * its included in the latest remote or local commitment transactions.
6041 // We test each of the three possible commitment transactions individually and use both dust and
6043 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6044 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6045 // tested for at least one of the cases in other tests.
6047 fn htlc_claim_single_commitment_only_a() {
6048 do_htlc_claim_local_commitment_only(true);
6049 do_htlc_claim_local_commitment_only(false);
6051 do_htlc_claim_current_remote_commitment_only(true);
6052 do_htlc_claim_current_remote_commitment_only(false);
6056 fn htlc_claim_single_commitment_only_b() {
6057 do_htlc_claim_previous_remote_commitment_only(true, false);
6058 do_htlc_claim_previous_remote_commitment_only(false, false);
6059 do_htlc_claim_previous_remote_commitment_only(true, true);
6060 do_htlc_claim_previous_remote_commitment_only(false, true);
6065 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6066 let chanmon_cfgs = create_chanmon_cfgs(2);
6067 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6068 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6069 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6070 // Force duplicate randomness for every get-random call
6071 for node in nodes.iter() {
6072 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6075 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6076 let channel_value_satoshis=10000;
6077 let push_msat=10001;
6078 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6079 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6080 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6081 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6083 // Create a second channel with the same random values. This used to panic due to a colliding
6084 // channel_id, but now panics due to a colliding outbound SCID alias.
6085 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6089 fn bolt2_open_channel_sending_node_checks_part2() {
6090 let chanmon_cfgs = create_chanmon_cfgs(2);
6091 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6092 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6093 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6095 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6096 let channel_value_satoshis=2^24;
6097 let push_msat=10001;
6098 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6100 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6101 let channel_value_satoshis=10000;
6102 // Test when push_msat is equal to 1000 * funding_satoshis.
6103 let push_msat=1000*channel_value_satoshis+1;
6104 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6106 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6107 let channel_value_satoshis=10000;
6108 let push_msat=10001;
6109 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
6110 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6111 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6113 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6114 // 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
6115 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6117 // 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.
6118 assert!(BREAKDOWN_TIMEOUT>0);
6119 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6121 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6122 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6123 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6125 // 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.
6126 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6127 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6128 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6129 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6130 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6134 fn bolt2_open_channel_sane_dust_limit() {
6135 let chanmon_cfgs = create_chanmon_cfgs(2);
6136 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6137 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6138 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6140 let channel_value_satoshis=1000000;
6141 let push_msat=10001;
6142 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6143 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6144 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6145 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6147 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6148 let events = nodes[1].node.get_and_clear_pending_msg_events();
6149 let err_msg = match events[0] {
6150 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6153 _ => panic!("Unexpected event"),
6155 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6158 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6159 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6160 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6161 // is no longer affordable once it's freed.
6163 fn test_fail_holding_cell_htlc_upon_free() {
6164 let chanmon_cfgs = create_chanmon_cfgs(2);
6165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6167 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6168 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6170 // First nodes[0] generates an update_fee, setting the channel's
6171 // pending_update_fee.
6173 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6174 *feerate_lock += 20;
6176 nodes[0].node.timer_tick_occurred();
6177 check_added_monitors!(nodes[0], 1);
6179 let events = nodes[0].node.get_and_clear_pending_msg_events();
6180 assert_eq!(events.len(), 1);
6181 let (update_msg, commitment_signed) = match events[0] {
6182 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6183 (update_fee.as_ref(), commitment_signed)
6185 _ => panic!("Unexpected event"),
6188 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6190 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6191 let channel_reserve = chan_stat.channel_reserve_msat;
6192 let feerate = get_feerate!(nodes[0], chan.2);
6193 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6195 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6196 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6197 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6199 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6200 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6201 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6202 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6204 // Flush the pending fee update.
6205 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6206 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6207 check_added_monitors!(nodes[1], 1);
6208 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6209 check_added_monitors!(nodes[0], 1);
6211 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6212 // HTLC, but now that the fee has been raised the payment will now fail, causing
6213 // us to surface its failure to the user.
6214 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6215 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6216 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);
6217 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 {}",
6218 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6219 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6221 // Check that the payment failed to be sent out.
6222 let events = nodes[0].node.get_and_clear_pending_events();
6223 assert_eq!(events.len(), 1);
6225 &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, .. } => {
6226 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6227 assert_eq!(our_payment_hash.clone(), *payment_hash);
6228 assert_eq!(*rejected_by_dest, false);
6229 assert_eq!(*all_paths_failed, true);
6230 assert_eq!(*network_update, None);
6231 assert_eq!(*short_channel_id, None);
6232 assert_eq!(*error_code, None);
6233 assert_eq!(*error_data, None);
6235 _ => panic!("Unexpected event"),
6239 // Test that if multiple HTLCs are released from the holding cell and one is
6240 // valid but the other is no longer valid upon release, the valid HTLC can be
6241 // successfully completed while the other one fails as expected.
6243 fn test_free_and_fail_holding_cell_htlcs() {
6244 let chanmon_cfgs = create_chanmon_cfgs(2);
6245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6247 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6248 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6250 // First nodes[0] generates an update_fee, setting the channel's
6251 // pending_update_fee.
6253 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6254 *feerate_lock += 200;
6256 nodes[0].node.timer_tick_occurred();
6257 check_added_monitors!(nodes[0], 1);
6259 let events = nodes[0].node.get_and_clear_pending_msg_events();
6260 assert_eq!(events.len(), 1);
6261 let (update_msg, commitment_signed) = match events[0] {
6262 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6263 (update_fee.as_ref(), commitment_signed)
6265 _ => panic!("Unexpected event"),
6268 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6270 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6271 let channel_reserve = chan_stat.channel_reserve_msat;
6272 let feerate = get_feerate!(nodes[0], chan.2);
6273 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6275 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6277 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6278 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6279 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6281 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6282 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6283 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6284 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6285 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6286 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6287 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6289 // Flush the pending fee update.
6290 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6291 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6292 check_added_monitors!(nodes[1], 1);
6293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6294 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6295 check_added_monitors!(nodes[0], 2);
6297 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6298 // but now that the fee has been raised the second payment will now fail, causing us
6299 // to surface its failure to the user. The first payment should succeed.
6300 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6301 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6302 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);
6303 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 {}",
6304 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6305 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6307 // Check that the second payment failed to be sent out.
6308 let events = nodes[0].node.get_and_clear_pending_events();
6309 assert_eq!(events.len(), 1);
6311 &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, .. } => {
6312 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6313 assert_eq!(payment_hash_2.clone(), *payment_hash);
6314 assert_eq!(*rejected_by_dest, false);
6315 assert_eq!(*all_paths_failed, true);
6316 assert_eq!(*network_update, None);
6317 assert_eq!(*short_channel_id, None);
6318 assert_eq!(*error_code, None);
6319 assert_eq!(*error_data, None);
6321 _ => panic!("Unexpected event"),
6324 // Complete the first payment and the RAA from the fee update.
6325 let (payment_event, send_raa_event) = {
6326 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6327 assert_eq!(msgs.len(), 2);
6328 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6330 let raa = match send_raa_event {
6331 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6332 _ => panic!("Unexpected event"),
6334 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6335 check_added_monitors!(nodes[1], 1);
6336 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6337 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6338 let events = nodes[1].node.get_and_clear_pending_events();
6339 assert_eq!(events.len(), 1);
6341 Event::PendingHTLCsForwardable { .. } => {},
6342 _ => panic!("Unexpected event"),
6344 nodes[1].node.process_pending_htlc_forwards();
6345 let events = nodes[1].node.get_and_clear_pending_events();
6346 assert_eq!(events.len(), 1);
6348 Event::PaymentReceived { .. } => {},
6349 _ => panic!("Unexpected event"),
6351 nodes[1].node.claim_funds(payment_preimage_1);
6352 check_added_monitors!(nodes[1], 1);
6353 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6355 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6356 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6357 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6358 expect_payment_sent!(nodes[0], payment_preimage_1);
6361 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6362 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6363 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6366 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6367 let chanmon_cfgs = create_chanmon_cfgs(3);
6368 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6369 // When this test was written, the default base fee floated based on the HTLC count.
6370 // It is now fixed, so we simply set the fee to the expected value here.
6371 let mut config = test_default_channel_config();
6372 config.channel_config.forwarding_fee_base_msat = 196;
6373 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6374 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6375 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6376 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6378 // First nodes[1] generates an update_fee, setting the channel's
6379 // pending_update_fee.
6381 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6382 *feerate_lock += 20;
6384 nodes[1].node.timer_tick_occurred();
6385 check_added_monitors!(nodes[1], 1);
6387 let events = nodes[1].node.get_and_clear_pending_msg_events();
6388 assert_eq!(events.len(), 1);
6389 let (update_msg, commitment_signed) = match events[0] {
6390 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6391 (update_fee.as_ref(), commitment_signed)
6393 _ => panic!("Unexpected event"),
6396 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6398 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6399 let channel_reserve = chan_stat.channel_reserve_msat;
6400 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6401 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6403 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6405 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6406 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6407 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6408 let payment_event = {
6409 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6410 check_added_monitors!(nodes[0], 1);
6412 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6413 assert_eq!(events.len(), 1);
6415 SendEvent::from_event(events.remove(0))
6417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6418 check_added_monitors!(nodes[1], 0);
6419 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6420 expect_pending_htlcs_forwardable!(nodes[1]);
6422 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6423 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6425 // Flush the pending fee update.
6426 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6427 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6428 check_added_monitors!(nodes[2], 1);
6429 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6430 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6431 check_added_monitors!(nodes[1], 2);
6433 // A final RAA message is generated to finalize the fee update.
6434 let events = nodes[1].node.get_and_clear_pending_msg_events();
6435 assert_eq!(events.len(), 1);
6437 let raa_msg = match &events[0] {
6438 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6441 _ => panic!("Unexpected event"),
6444 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6445 check_added_monitors!(nodes[2], 1);
6446 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6448 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6449 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6450 assert_eq!(process_htlc_forwards_event.len(), 1);
6451 match &process_htlc_forwards_event[0] {
6452 &Event::PendingHTLCsForwardable { .. } => {},
6453 _ => panic!("Unexpected event"),
6456 // In response, we call ChannelManager's process_pending_htlc_forwards
6457 nodes[1].node.process_pending_htlc_forwards();
6458 check_added_monitors!(nodes[1], 1);
6460 // This causes the HTLC to be failed backwards.
6461 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6462 assert_eq!(fail_event.len(), 1);
6463 let (fail_msg, commitment_signed) = match &fail_event[0] {
6464 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6465 assert_eq!(updates.update_add_htlcs.len(), 0);
6466 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6467 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6468 assert_eq!(updates.update_fail_htlcs.len(), 1);
6469 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6471 _ => panic!("Unexpected event"),
6474 // Pass the failure messages back to nodes[0].
6475 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6476 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6478 // Complete the HTLC failure+removal process.
6479 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6480 check_added_monitors!(nodes[0], 1);
6481 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6482 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6483 check_added_monitors!(nodes[1], 2);
6484 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6485 assert_eq!(final_raa_event.len(), 1);
6486 let raa = match &final_raa_event[0] {
6487 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6488 _ => panic!("Unexpected event"),
6490 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6491 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6492 check_added_monitors!(nodes[0], 1);
6495 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6496 // 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.
6497 //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.
6500 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6501 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6502 let chanmon_cfgs = create_chanmon_cfgs(2);
6503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6506 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6508 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6509 route.paths[0][0].fee_msat = 100;
6511 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6512 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6513 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6514 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6518 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6519 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6520 let chanmon_cfgs = create_chanmon_cfgs(2);
6521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6526 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6527 route.paths[0][0].fee_msat = 0;
6528 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6529 assert_eq!(err, "Cannot send 0-msat HTLC"));
6531 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6532 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6536 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6537 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6538 let chanmon_cfgs = create_chanmon_cfgs(2);
6539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6541 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6542 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6544 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6545 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6546 check_added_monitors!(nodes[0], 1);
6547 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6548 updates.update_add_htlcs[0].amount_msat = 0;
6550 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6551 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6552 check_closed_broadcast!(nodes[1], true).unwrap();
6553 check_added_monitors!(nodes[1], 1);
6554 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6558 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6559 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6560 //It is enforced when constructing a route.
6561 let chanmon_cfgs = create_chanmon_cfgs(2);
6562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6567 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6568 .with_features(InvoiceFeatures::known());
6569 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6570 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6571 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6572 assert_eq!(err, &"Channel CLTV overflowed?"));
6576 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6577 //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.
6578 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6579 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6580 let chanmon_cfgs = create_chanmon_cfgs(2);
6581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6583 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6584 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6585 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6587 for i in 0..max_accepted_htlcs {
6588 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6589 let payment_event = {
6590 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6591 check_added_monitors!(nodes[0], 1);
6593 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6594 assert_eq!(events.len(), 1);
6595 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6596 assert_eq!(htlcs[0].htlc_id, i);
6600 SendEvent::from_event(events.remove(0))
6602 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6603 check_added_monitors!(nodes[1], 0);
6604 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6606 expect_pending_htlcs_forwardable!(nodes[1]);
6607 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6609 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6610 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6611 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6613 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6614 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6618 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6619 //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.
6620 let chanmon_cfgs = create_chanmon_cfgs(2);
6621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6624 let channel_value = 100000;
6625 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6626 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6628 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6630 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6631 // Manually create a route over our max in flight (which our router normally automatically
6633 route.paths[0][0].fee_msat = max_in_flight + 1;
6634 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6635 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)));
6637 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6638 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);
6640 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6643 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6645 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6646 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6647 let chanmon_cfgs = create_chanmon_cfgs(2);
6648 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6649 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6650 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6651 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6652 let htlc_minimum_msat: u64;
6654 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6655 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6656 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6659 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6660 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6661 check_added_monitors!(nodes[0], 1);
6662 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6663 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6664 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6665 assert!(nodes[1].node.list_channels().is_empty());
6666 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6667 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()));
6668 check_added_monitors!(nodes[1], 1);
6669 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6673 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6674 //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
6675 let chanmon_cfgs = create_chanmon_cfgs(2);
6676 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6677 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6678 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6679 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6681 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6682 let channel_reserve = chan_stat.channel_reserve_msat;
6683 let feerate = get_feerate!(nodes[0], chan.2);
6684 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6685 // The 2* and +1 are for the fee spike reserve.
6686 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6688 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6689 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6690 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6691 check_added_monitors!(nodes[0], 1);
6692 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6694 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6695 // at this time channel-initiatee receivers are not required to enforce that senders
6696 // respect the fee_spike_reserve.
6697 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6698 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6700 assert!(nodes[1].node.list_channels().is_empty());
6701 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6702 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6703 check_added_monitors!(nodes[1], 1);
6704 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6708 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6709 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6710 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6711 let chanmon_cfgs = create_chanmon_cfgs(2);
6712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6715 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6717 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6718 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6719 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6720 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6721 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6722 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6724 let mut msg = msgs::UpdateAddHTLC {
6728 payment_hash: our_payment_hash,
6729 cltv_expiry: htlc_cltv,
6730 onion_routing_packet: onion_packet.clone(),
6733 for i in 0..super::channel::OUR_MAX_HTLCS {
6734 msg.htlc_id = i as u64;
6735 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6737 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6740 assert!(nodes[1].node.list_channels().is_empty());
6741 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6742 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6743 check_added_monitors!(nodes[1], 1);
6744 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6748 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6749 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6750 let chanmon_cfgs = create_chanmon_cfgs(2);
6751 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6752 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6753 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6754 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6756 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6757 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6758 check_added_monitors!(nodes[0], 1);
6759 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6760 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6761 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6763 assert!(nodes[1].node.list_channels().is_empty());
6764 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6765 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6766 check_added_monitors!(nodes[1], 1);
6767 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6771 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6772 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6773 let chanmon_cfgs = create_chanmon_cfgs(2);
6774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6776 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6778 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6779 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6780 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6781 check_added_monitors!(nodes[0], 1);
6782 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6783 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6786 assert!(nodes[1].node.list_channels().is_empty());
6787 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6788 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6789 check_added_monitors!(nodes[1], 1);
6790 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6794 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6795 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6796 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6797 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6798 let chanmon_cfgs = create_chanmon_cfgs(2);
6799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6801 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6803 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6804 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6805 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6806 check_added_monitors!(nodes[0], 1);
6807 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6808 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6810 //Disconnect and Reconnect
6811 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6812 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6813 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6814 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6815 assert_eq!(reestablish_1.len(), 1);
6816 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6817 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6818 assert_eq!(reestablish_2.len(), 1);
6819 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6820 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6821 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6822 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6825 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6826 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6827 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6828 check_added_monitors!(nodes[1], 1);
6829 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6831 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6833 assert!(nodes[1].node.list_channels().is_empty());
6834 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6835 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6836 check_added_monitors!(nodes[1], 1);
6837 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6841 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6842 //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.
6844 let chanmon_cfgs = create_chanmon_cfgs(2);
6845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6847 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6848 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6849 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6850 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6852 check_added_monitors!(nodes[0], 1);
6853 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6856 let update_msg = msgs::UpdateFulfillHTLC{
6859 payment_preimage: our_payment_preimage,
6862 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6864 assert!(nodes[0].node.list_channels().is_empty());
6865 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6866 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()));
6867 check_added_monitors!(nodes[0], 1);
6868 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6872 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6873 //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.
6875 let chanmon_cfgs = create_chanmon_cfgs(2);
6876 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6877 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6878 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6879 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6881 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6882 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6883 check_added_monitors!(nodes[0], 1);
6884 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6885 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6887 let update_msg = msgs::UpdateFailHTLC{
6890 reason: msgs::OnionErrorPacket { data: Vec::new()},
6893 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6895 assert!(nodes[0].node.list_channels().is_empty());
6896 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6897 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()));
6898 check_added_monitors!(nodes[0], 1);
6899 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6903 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6904 //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.
6906 let chanmon_cfgs = create_chanmon_cfgs(2);
6907 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6908 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6909 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6910 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6912 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6913 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6914 check_added_monitors!(nodes[0], 1);
6915 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6916 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6917 let update_msg = msgs::UpdateFailMalformedHTLC{
6920 sha256_of_onion: [1; 32],
6921 failure_code: 0x8000,
6924 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6926 assert!(nodes[0].node.list_channels().is_empty());
6927 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6928 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()));
6929 check_added_monitors!(nodes[0], 1);
6930 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6934 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6935 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6937 let chanmon_cfgs = create_chanmon_cfgs(2);
6938 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6939 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6940 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6941 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6943 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6945 nodes[1].node.claim_funds(our_payment_preimage);
6946 check_added_monitors!(nodes[1], 1);
6947 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6949 let events = nodes[1].node.get_and_clear_pending_msg_events();
6950 assert_eq!(events.len(), 1);
6951 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6953 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, .. } } => {
6954 assert!(update_add_htlcs.is_empty());
6955 assert_eq!(update_fulfill_htlcs.len(), 1);
6956 assert!(update_fail_htlcs.is_empty());
6957 assert!(update_fail_malformed_htlcs.is_empty());
6958 assert!(update_fee.is_none());
6959 update_fulfill_htlcs[0].clone()
6961 _ => panic!("Unexpected event"),
6965 update_fulfill_msg.htlc_id = 1;
6967 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6969 assert!(nodes[0].node.list_channels().is_empty());
6970 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6971 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6972 check_added_monitors!(nodes[0], 1);
6973 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6977 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6978 //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.
6980 let chanmon_cfgs = create_chanmon_cfgs(2);
6981 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6982 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6983 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6984 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6986 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6988 nodes[1].node.claim_funds(our_payment_preimage);
6989 check_added_monitors!(nodes[1], 1);
6990 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6992 let events = nodes[1].node.get_and_clear_pending_msg_events();
6993 assert_eq!(events.len(), 1);
6994 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6996 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, .. } } => {
6997 assert!(update_add_htlcs.is_empty());
6998 assert_eq!(update_fulfill_htlcs.len(), 1);
6999 assert!(update_fail_htlcs.is_empty());
7000 assert!(update_fail_malformed_htlcs.is_empty());
7001 assert!(update_fee.is_none());
7002 update_fulfill_htlcs[0].clone()
7004 _ => panic!("Unexpected event"),
7008 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7010 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7012 assert!(nodes[0].node.list_channels().is_empty());
7013 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7014 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7015 check_added_monitors!(nodes[0], 1);
7016 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7020 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7021 //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.
7023 let chanmon_cfgs = create_chanmon_cfgs(2);
7024 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7025 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7026 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7027 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7029 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7030 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7031 check_added_monitors!(nodes[0], 1);
7033 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7034 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7036 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7037 check_added_monitors!(nodes[1], 0);
7038 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7040 let events = nodes[1].node.get_and_clear_pending_msg_events();
7042 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7044 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, .. } } => {
7045 assert!(update_add_htlcs.is_empty());
7046 assert!(update_fulfill_htlcs.is_empty());
7047 assert!(update_fail_htlcs.is_empty());
7048 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7049 assert!(update_fee.is_none());
7050 update_fail_malformed_htlcs[0].clone()
7052 _ => panic!("Unexpected event"),
7055 update_msg.failure_code &= !0x8000;
7056 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7058 assert!(nodes[0].node.list_channels().is_empty());
7059 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7060 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7061 check_added_monitors!(nodes[0], 1);
7062 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7066 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7067 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7068 // * 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.
7070 let chanmon_cfgs = create_chanmon_cfgs(3);
7071 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7072 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7073 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7074 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7075 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7077 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7080 let mut payment_event = {
7081 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7082 check_added_monitors!(nodes[0], 1);
7083 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7084 assert_eq!(events.len(), 1);
7085 SendEvent::from_event(events.remove(0))
7087 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7088 check_added_monitors!(nodes[1], 0);
7089 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7090 expect_pending_htlcs_forwardable!(nodes[1]);
7091 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7092 assert_eq!(events_2.len(), 1);
7093 check_added_monitors!(nodes[1], 1);
7094 payment_event = SendEvent::from_event(events_2.remove(0));
7095 assert_eq!(payment_event.msgs.len(), 1);
7098 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7099 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7100 check_added_monitors!(nodes[2], 0);
7101 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7103 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7104 assert_eq!(events_3.len(), 1);
7105 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7107 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 } } => {
7108 assert!(update_add_htlcs.is_empty());
7109 assert!(update_fulfill_htlcs.is_empty());
7110 assert!(update_fail_htlcs.is_empty());
7111 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7112 assert!(update_fee.is_none());
7113 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7115 _ => panic!("Unexpected event"),
7119 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7121 check_added_monitors!(nodes[1], 0);
7122 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7123 expect_pending_htlcs_forwardable!(nodes[1]);
7124 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7125 assert_eq!(events_4.len(), 1);
7127 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7129 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, .. } } => {
7130 assert!(update_add_htlcs.is_empty());
7131 assert!(update_fulfill_htlcs.is_empty());
7132 assert_eq!(update_fail_htlcs.len(), 1);
7133 assert!(update_fail_malformed_htlcs.is_empty());
7134 assert!(update_fee.is_none());
7136 _ => panic!("Unexpected event"),
7139 check_added_monitors!(nodes[1], 1);
7142 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7143 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7144 // 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
7145 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7147 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7148 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7149 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7150 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7151 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7152 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7154 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7156 // We route 2 dust-HTLCs between A and B
7157 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7158 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7159 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7161 // Cache one local commitment tx as previous
7162 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7164 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7165 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7166 check_added_monitors!(nodes[1], 0);
7167 expect_pending_htlcs_forwardable!(nodes[1]);
7168 check_added_monitors!(nodes[1], 1);
7170 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7171 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7172 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7173 check_added_monitors!(nodes[0], 1);
7175 // Cache one local commitment tx as lastest
7176 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7178 let events = nodes[0].node.get_and_clear_pending_msg_events();
7180 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7181 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7183 _ => panic!("Unexpected event"),
7186 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7187 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7189 _ => panic!("Unexpected event"),
7192 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7193 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7194 if announce_latest {
7195 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7197 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7200 check_closed_broadcast!(nodes[0], true);
7201 check_added_monitors!(nodes[0], 1);
7202 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7204 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7205 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7206 let events = nodes[0].node.get_and_clear_pending_events();
7207 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7208 assert_eq!(events.len(), 2);
7209 let mut first_failed = false;
7210 for event in events {
7212 Event::PaymentPathFailed { payment_hash, .. } => {
7213 if payment_hash == payment_hash_1 {
7214 assert!(!first_failed);
7215 first_failed = true;
7217 assert_eq!(payment_hash, payment_hash_2);
7220 _ => panic!("Unexpected event"),
7226 fn test_failure_delay_dust_htlc_local_commitment() {
7227 do_test_failure_delay_dust_htlc_local_commitment(true);
7228 do_test_failure_delay_dust_htlc_local_commitment(false);
7231 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7232 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7233 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7234 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7235 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7236 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7237 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7239 let chanmon_cfgs = create_chanmon_cfgs(3);
7240 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7241 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7242 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7243 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7245 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7247 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7248 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7250 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7251 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7253 // We revoked bs_commitment_tx
7255 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7256 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7259 let mut timeout_tx = Vec::new();
7261 // We fail dust-HTLC 1 by broadcast of local commitment tx
7262 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7263 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7264 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7265 expect_payment_failed!(nodes[0], dust_hash, true);
7267 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7268 check_closed_broadcast!(nodes[0], true);
7269 check_added_monitors!(nodes[0], 1);
7270 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7271 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7272 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7273 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7274 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7275 mine_transaction(&nodes[0], &timeout_tx[0]);
7276 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7277 expect_payment_failed!(nodes[0], non_dust_hash, true);
7279 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7280 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7281 check_closed_broadcast!(nodes[0], true);
7282 check_added_monitors!(nodes[0], 1);
7283 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7284 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7285 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7286 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7288 expect_payment_failed!(nodes[0], dust_hash, true);
7289 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7290 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7291 mine_transaction(&nodes[0], &timeout_tx[0]);
7292 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7293 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7294 expect_payment_failed!(nodes[0], non_dust_hash, true);
7296 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7298 let events = nodes[0].node.get_and_clear_pending_events();
7299 assert_eq!(events.len(), 2);
7302 Event::PaymentPathFailed { payment_hash, .. } => {
7303 if payment_hash == dust_hash { first = true; }
7304 else { first = false; }
7306 _ => panic!("Unexpected event"),
7309 Event::PaymentPathFailed { payment_hash, .. } => {
7310 if first { assert_eq!(payment_hash, non_dust_hash); }
7311 else { assert_eq!(payment_hash, dust_hash); }
7313 _ => panic!("Unexpected event"),
7320 fn test_sweep_outbound_htlc_failure_update() {
7321 do_test_sweep_outbound_htlc_failure_update(false, true);
7322 do_test_sweep_outbound_htlc_failure_update(false, false);
7323 do_test_sweep_outbound_htlc_failure_update(true, false);
7327 fn test_user_configurable_csv_delay() {
7328 // We test our channel constructors yield errors when we pass them absurd csv delay
7330 let mut low_our_to_self_config = UserConfig::default();
7331 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7332 let mut high_their_to_self_config = UserConfig::default();
7333 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7334 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7335 let chanmon_cfgs = create_chanmon_cfgs(2);
7336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7338 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7340 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7341 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7342 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7343 &low_our_to_self_config, 0, 42)
7346 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())); },
7347 _ => panic!("Unexpected event"),
7349 } else { assert!(false) }
7351 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7352 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7353 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7354 open_channel.to_self_delay = 200;
7355 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7356 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7357 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7360 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())); },
7361 _ => panic!("Unexpected event"),
7363 } else { assert!(false); }
7365 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7366 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7367 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()));
7368 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7369 accept_channel.to_self_delay = 200;
7370 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7372 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7374 &ErrorAction::SendErrorMessage { ref msg } => {
7375 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()));
7376 reason_msg = msg.data.clone();
7380 } else { panic!(); }
7381 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7383 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7384 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7385 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7386 open_channel.to_self_delay = 200;
7387 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7388 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7389 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7392 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())); },
7393 _ => panic!("Unexpected event"),
7395 } else { assert!(false); }
7399 fn test_data_loss_protect() {
7400 // We want to be sure that :
7401 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7402 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7403 // * we close channel in case of detecting other being fallen behind
7404 // * we are able to claim our own outputs thanks to to_remote being static
7405 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7411 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7412 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7413 // during signing due to revoked tx
7414 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7415 let keys_manager = &chanmon_cfgs[0].keys_manager;
7418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7420 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7422 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7424 // Cache node A state before any channel update
7425 let previous_node_state = nodes[0].node.encode();
7426 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7427 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7429 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7430 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7432 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7433 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7435 // Restore node A from previous state
7436 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7437 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7438 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7439 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7440 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7441 persister = test_utils::TestPersister::new();
7442 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7444 let mut channel_monitors = HashMap::new();
7445 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7446 <(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 {
7447 keys_manager: keys_manager,
7448 fee_estimator: &fee_estimator,
7449 chain_monitor: &monitor,
7451 tx_broadcaster: &tx_broadcaster,
7452 default_config: UserConfig::default(),
7456 nodes[0].node = &node_state_0;
7457 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7458 nodes[0].chain_monitor = &monitor;
7459 nodes[0].chain_source = &chain_source;
7461 check_added_monitors!(nodes[0], 1);
7463 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7464 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7466 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7468 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7469 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7470 check_added_monitors!(nodes[0], 1);
7473 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7474 assert_eq!(node_txn.len(), 0);
7477 let mut reestablish_1 = Vec::with_capacity(1);
7478 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7479 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7480 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7481 reestablish_1.push(msg.clone());
7482 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7483 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7485 &ErrorAction::SendErrorMessage { ref msg } => {
7486 assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7488 _ => panic!("Unexpected event!"),
7491 panic!("Unexpected event")
7495 // Check we close channel detecting A is fallen-behind
7496 // Check that we sent the warning message when we detected that A has fallen behind,
7497 // and give the possibility for A to recover from the warning.
7498 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7499 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7500 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7502 // Check A is able to claim to_remote output
7503 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7504 // The node B should not broadcast the transaction to force close the channel!
7505 assert!(node_txn.is_empty());
7506 // B should now detect that there is something wrong and should force close the channel.
7507 let exp_err = "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting";
7508 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: exp_err.to_string() });
7510 // after the warning message sent by B, we should not able to
7511 // use the channel, or reconnect with success to the channel.
7512 assert!(nodes[0].node.list_usable_channels().is_empty());
7513 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7514 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7515 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7517 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7518 let mut err_msgs_0 = Vec::with_capacity(1);
7519 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7520 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7522 &ErrorAction::SendErrorMessage { ref msg } => {
7523 assert_eq!(msg.data, "Failed to find corresponding channel");
7524 err_msgs_0.push(msg.clone());
7526 _ => panic!("Unexpected event!"),
7529 panic!("Unexpected event!");
7532 assert_eq!(err_msgs_0.len(), 1);
7533 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7534 assert!(nodes[1].node.list_usable_channels().is_empty());
7535 check_added_monitors!(nodes[1], 1);
7536 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7537 check_closed_broadcast!(nodes[1], false);
7541 fn test_check_htlc_underpaying() {
7542 // Send payment through A -> B but A is maliciously
7543 // sending a probe payment (i.e less than expected value0
7544 // to B, B should refuse payment.
7546 let chanmon_cfgs = create_chanmon_cfgs(2);
7547 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7548 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7549 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7551 // Create some initial channels
7552 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7554 let scorer = test_utils::TestScorer::with_penalty(0);
7555 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7556 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7557 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();
7558 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7559 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7560 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7561 check_added_monitors!(nodes[0], 1);
7563 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7564 assert_eq!(events.len(), 1);
7565 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7567 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7569 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7570 // and then will wait a second random delay before failing the HTLC back:
7571 expect_pending_htlcs_forwardable!(nodes[1]);
7572 expect_pending_htlcs_forwardable!(nodes[1]);
7574 // Node 3 is expecting payment of 100_000 but received 10_000,
7575 // it should fail htlc like we didn't know the preimage.
7576 nodes[1].node.process_pending_htlc_forwards();
7578 let events = nodes[1].node.get_and_clear_pending_msg_events();
7579 assert_eq!(events.len(), 1);
7580 let (update_fail_htlc, commitment_signed) = match events[0] {
7581 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 } } => {
7582 assert!(update_add_htlcs.is_empty());
7583 assert!(update_fulfill_htlcs.is_empty());
7584 assert_eq!(update_fail_htlcs.len(), 1);
7585 assert!(update_fail_malformed_htlcs.is_empty());
7586 assert!(update_fee.is_none());
7587 (update_fail_htlcs[0].clone(), commitment_signed)
7589 _ => panic!("Unexpected event"),
7591 check_added_monitors!(nodes[1], 1);
7593 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7594 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7596 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7597 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7598 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7599 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7603 fn test_announce_disable_channels() {
7604 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7605 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7607 let chanmon_cfgs = create_chanmon_cfgs(2);
7608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7610 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7612 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7613 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7614 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7617 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7618 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7620 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7621 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7622 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7623 assert_eq!(msg_events.len(), 3);
7624 let mut chans_disabled = HashMap::new();
7625 for e in msg_events {
7627 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7628 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7629 // Check that each channel gets updated exactly once
7630 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7631 panic!("Generated ChannelUpdate for wrong chan!");
7634 _ => panic!("Unexpected event"),
7638 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7639 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7640 assert_eq!(reestablish_1.len(), 3);
7641 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7642 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7643 assert_eq!(reestablish_2.len(), 3);
7645 // Reestablish chan_1
7646 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7647 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7648 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7649 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7650 // Reestablish chan_2
7651 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7652 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7653 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7654 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7655 // Reestablish chan_3
7656 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7657 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7658 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7659 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7661 nodes[0].node.timer_tick_occurred();
7662 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7663 nodes[0].node.timer_tick_occurred();
7664 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7665 assert_eq!(msg_events.len(), 3);
7666 for e in msg_events {
7668 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7669 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7670 match chans_disabled.remove(&msg.contents.short_channel_id) {
7671 // Each update should have a higher timestamp than the previous one, replacing
7673 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7674 None => panic!("Generated ChannelUpdate for wrong chan!"),
7677 _ => panic!("Unexpected event"),
7680 // Check that each channel gets updated exactly once
7681 assert!(chans_disabled.is_empty());
7685 fn test_bump_penalty_txn_on_revoked_commitment() {
7686 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7687 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7689 let chanmon_cfgs = create_chanmon_cfgs(2);
7690 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7691 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7692 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7694 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7696 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7697 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7698 .with_features(InvoiceFeatures::known());
7699 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7700 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7702 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7703 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7704 assert_eq!(revoked_txn[0].output.len(), 4);
7705 assert_eq!(revoked_txn[0].input.len(), 1);
7706 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7707 let revoked_txid = revoked_txn[0].txid();
7709 let mut penalty_sum = 0;
7710 for outp in revoked_txn[0].output.iter() {
7711 if outp.script_pubkey.is_v0_p2wsh() {
7712 penalty_sum += outp.value;
7716 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7717 let header_114 = connect_blocks(&nodes[1], 14);
7719 // Actually revoke tx by claiming a HTLC
7720 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7721 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7722 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7723 check_added_monitors!(nodes[1], 1);
7725 // One or more justice tx should have been broadcast, check it
7729 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7730 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7731 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7732 assert_eq!(node_txn[0].output.len(), 1);
7733 check_spends!(node_txn[0], revoked_txn[0]);
7734 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7735 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7736 penalty_1 = node_txn[0].txid();
7740 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7741 connect_blocks(&nodes[1], 15);
7742 let mut penalty_2 = penalty_1;
7743 let mut feerate_2 = 0;
7745 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7746 assert_eq!(node_txn.len(), 1);
7747 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7748 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7749 assert_eq!(node_txn[0].output.len(), 1);
7750 check_spends!(node_txn[0], revoked_txn[0]);
7751 penalty_2 = node_txn[0].txid();
7752 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7753 assert_ne!(penalty_2, penalty_1);
7754 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7755 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7756 // Verify 25% bump heuristic
7757 assert!(feerate_2 * 100 >= feerate_1 * 125);
7761 assert_ne!(feerate_2, 0);
7763 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7764 connect_blocks(&nodes[1], 1);
7766 let mut feerate_3 = 0;
7768 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7769 assert_eq!(node_txn.len(), 1);
7770 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7771 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7772 assert_eq!(node_txn[0].output.len(), 1);
7773 check_spends!(node_txn[0], revoked_txn[0]);
7774 penalty_3 = node_txn[0].txid();
7775 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7776 assert_ne!(penalty_3, penalty_2);
7777 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7778 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7779 // Verify 25% bump heuristic
7780 assert!(feerate_3 * 100 >= feerate_2 * 125);
7784 assert_ne!(feerate_3, 0);
7786 nodes[1].node.get_and_clear_pending_events();
7787 nodes[1].node.get_and_clear_pending_msg_events();
7791 fn test_bump_penalty_txn_on_revoked_htlcs() {
7792 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7793 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7795 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7796 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7799 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7801 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7802 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7803 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7804 let scorer = test_utils::TestScorer::with_penalty(0);
7805 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7806 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7807 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7808 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7809 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7810 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7811 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7812 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7814 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7815 assert_eq!(revoked_local_txn[0].input.len(), 1);
7816 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7818 // Revoke local commitment tx
7819 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7821 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7822 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7823 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7824 check_closed_broadcast!(nodes[1], true);
7825 check_added_monitors!(nodes[1], 1);
7826 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7827 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7829 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7830 assert_eq!(revoked_htlc_txn.len(), 3);
7831 check_spends!(revoked_htlc_txn[1], chan.3);
7833 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7834 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7835 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7837 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7838 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7839 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7840 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7842 // Broadcast set of revoked txn on A
7843 let hash_128 = connect_blocks(&nodes[0], 40);
7844 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7845 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7846 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7847 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7848 let events = nodes[0].node.get_and_clear_pending_events();
7849 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7851 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7852 _ => panic!("Unexpected event"),
7858 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7859 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7860 // Verify claim tx are spending revoked HTLC txn
7862 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7863 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7864 // which are included in the same block (they are broadcasted because we scan the
7865 // transactions linearly and generate claims as we go, they likely should be removed in the
7867 assert_eq!(node_txn[0].input.len(), 1);
7868 check_spends!(node_txn[0], revoked_local_txn[0]);
7869 assert_eq!(node_txn[1].input.len(), 1);
7870 check_spends!(node_txn[1], revoked_local_txn[0]);
7871 assert_eq!(node_txn[2].input.len(), 1);
7872 check_spends!(node_txn[2], revoked_local_txn[0]);
7874 // Each of the three justice transactions claim a separate (single) output of the three
7875 // available, which we check here:
7876 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7877 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7878 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7880 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7881 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7883 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7884 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7885 // a remote commitment tx has already been confirmed).
7886 check_spends!(node_txn[3], chan.3);
7888 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7889 // output, checked above).
7890 assert_eq!(node_txn[4].input.len(), 2);
7891 assert_eq!(node_txn[4].output.len(), 1);
7892 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7894 first = node_txn[4].txid();
7895 // Store both feerates for later comparison
7896 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7897 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7898 penalty_txn = vec![node_txn[2].clone()];
7902 // Connect one more block to see if bumped penalty are issued for HTLC txn
7903 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7904 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7905 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7906 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7908 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7909 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7911 check_spends!(node_txn[0], revoked_local_txn[0]);
7912 check_spends!(node_txn[1], revoked_local_txn[0]);
7913 // Note that these are both bogus - they spend outputs already claimed in block 129:
7914 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7915 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7917 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7918 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7924 // Few more blocks to confirm penalty txn
7925 connect_blocks(&nodes[0], 4);
7926 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7927 let header_144 = connect_blocks(&nodes[0], 9);
7929 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7930 assert_eq!(node_txn.len(), 1);
7932 assert_eq!(node_txn[0].input.len(), 2);
7933 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7934 // Verify bumped tx is different and 25% bump heuristic
7935 assert_ne!(first, node_txn[0].txid());
7936 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7937 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7938 assert!(feerate_2 * 100 > feerate_1 * 125);
7939 let txn = vec![node_txn[0].clone()];
7943 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7944 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7945 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7946 connect_blocks(&nodes[0], 20);
7948 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7949 // We verify than no new transaction has been broadcast because previously
7950 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7951 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7952 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7953 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7954 // up bumped justice generation.
7955 assert_eq!(node_txn.len(), 0);
7958 check_closed_broadcast!(nodes[0], true);
7959 check_added_monitors!(nodes[0], 1);
7963 fn test_bump_penalty_txn_on_remote_commitment() {
7964 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7965 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7968 // Provide preimage for one
7969 // Check aggregation
7971 let chanmon_cfgs = create_chanmon_cfgs(2);
7972 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7973 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7974 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7976 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7977 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7978 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7980 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7981 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7982 assert_eq!(remote_txn[0].output.len(), 4);
7983 assert_eq!(remote_txn[0].input.len(), 1);
7984 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7986 // Claim a HTLC without revocation (provide B monitor with preimage)
7987 nodes[1].node.claim_funds(payment_preimage);
7988 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7989 mine_transaction(&nodes[1], &remote_txn[0]);
7990 check_added_monitors!(nodes[1], 2);
7991 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7993 // One or more claim tx should have been broadcast, check it
7997 let feerate_timeout;
7998 let feerate_preimage;
8000 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8001 // 9 transactions including:
8002 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8003 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8004 // 2 * HTLC-Success (one RBF bump we'll check later)
8006 assert_eq!(node_txn.len(), 8);
8007 assert_eq!(node_txn[0].input.len(), 1);
8008 assert_eq!(node_txn[6].input.len(), 1);
8009 check_spends!(node_txn[0], remote_txn[0]);
8010 check_spends!(node_txn[6], remote_txn[0]);
8012 check_spends!(node_txn[1], chan.3);
8013 check_spends!(node_txn[2], node_txn[1]);
8015 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8016 preimage_bump = node_txn[3].clone();
8017 check_spends!(node_txn[3], remote_txn[0]);
8019 assert_eq!(node_txn[1], node_txn[4]);
8020 assert_eq!(node_txn[2], node_txn[5]);
8022 preimage_bump = node_txn[7].clone();
8023 check_spends!(node_txn[7], remote_txn[0]);
8024 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8026 assert_eq!(node_txn[1], node_txn[3]);
8027 assert_eq!(node_txn[2], node_txn[4]);
8030 timeout = node_txn[6].txid();
8031 let index = node_txn[6].input[0].previous_output.vout;
8032 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8033 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8035 preimage = node_txn[0].txid();
8036 let index = node_txn[0].input[0].previous_output.vout;
8037 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8038 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8042 assert_ne!(feerate_timeout, 0);
8043 assert_ne!(feerate_preimage, 0);
8045 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8046 connect_blocks(&nodes[1], 15);
8048 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8049 assert_eq!(node_txn.len(), 1);
8050 assert_eq!(node_txn[0].input.len(), 1);
8051 assert_eq!(preimage_bump.input.len(), 1);
8052 check_spends!(node_txn[0], remote_txn[0]);
8053 check_spends!(preimage_bump, remote_txn[0]);
8055 let index = preimage_bump.input[0].previous_output.vout;
8056 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8057 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8058 assert!(new_feerate * 100 > feerate_timeout * 125);
8059 assert_ne!(timeout, preimage_bump.txid());
8061 let index = node_txn[0].input[0].previous_output.vout;
8062 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8063 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8064 assert!(new_feerate * 100 > feerate_preimage * 125);
8065 assert_ne!(preimage, node_txn[0].txid());
8070 nodes[1].node.get_and_clear_pending_events();
8071 nodes[1].node.get_and_clear_pending_msg_events();
8075 fn test_counterparty_raa_skip_no_crash() {
8076 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8077 // commitment transaction, we would have happily carried on and provided them the next
8078 // commitment transaction based on one RAA forward. This would probably eventually have led to
8079 // channel closure, but it would not have resulted in funds loss. Still, our
8080 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8081 // check simply that the channel is closed in response to such an RAA, but don't check whether
8082 // we decide to punish our counterparty for revoking their funds (as we don't currently
8084 let chanmon_cfgs = create_chanmon_cfgs(2);
8085 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8086 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8087 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8088 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8090 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8091 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8093 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8095 // Make signer believe we got a counterparty signature, so that it allows the revocation
8096 keys.get_enforcement_state().last_holder_commitment -= 1;
8097 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8099 // Must revoke without gaps
8100 keys.get_enforcement_state().last_holder_commitment -= 1;
8101 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8103 keys.get_enforcement_state().last_holder_commitment -= 1;
8104 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8105 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8107 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8108 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8109 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8110 check_added_monitors!(nodes[1], 1);
8111 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8115 fn test_bump_txn_sanitize_tracking_maps() {
8116 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8117 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8119 let chanmon_cfgs = create_chanmon_cfgs(2);
8120 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8121 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8122 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8124 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8125 // Lock HTLC in both directions
8126 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8127 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8129 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8130 assert_eq!(revoked_local_txn[0].input.len(), 1);
8131 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8133 // Revoke local commitment tx
8134 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8136 // Broadcast set of revoked txn on A
8137 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8138 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8139 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8141 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8142 check_closed_broadcast!(nodes[0], true);
8143 check_added_monitors!(nodes[0], 1);
8144 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8146 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8147 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8148 check_spends!(node_txn[0], revoked_local_txn[0]);
8149 check_spends!(node_txn[1], revoked_local_txn[0]);
8150 check_spends!(node_txn[2], revoked_local_txn[0]);
8151 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8155 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8156 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8157 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8159 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8160 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8161 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8166 fn test_pending_claimed_htlc_no_balance_underflow() {
8167 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8168 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8169 let chanmon_cfgs = create_chanmon_cfgs(2);
8170 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8171 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8172 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8173 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8175 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8176 nodes[1].node.claim_funds(payment_preimage);
8177 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8178 check_added_monitors!(nodes[1], 1);
8179 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8181 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8182 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8183 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8184 check_added_monitors!(nodes[0], 1);
8185 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8187 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8188 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8189 // can get our balance.
8191 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8192 // the public key of the only hop. This works around ChannelDetails not showing the
8193 // almost-claimed HTLC as available balance.
8194 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8195 route.payment_params = None; // This is all wrong, but unnecessary
8196 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8197 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8198 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8200 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8204 fn test_channel_conf_timeout() {
8205 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8206 // confirm within 2016 blocks, as recommended by BOLT 2.
8207 let chanmon_cfgs = create_chanmon_cfgs(2);
8208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8210 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8212 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8214 // The outbound node should wait forever for confirmation:
8215 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8216 // copied here instead of directly referencing the constant.
8217 connect_blocks(&nodes[0], 2016);
8218 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8220 // The inbound node should fail the channel after exactly 2016 blocks
8221 connect_blocks(&nodes[1], 2015);
8222 check_added_monitors!(nodes[1], 0);
8223 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8225 connect_blocks(&nodes[1], 1);
8226 check_added_monitors!(nodes[1], 1);
8227 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8228 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8229 assert_eq!(close_ev.len(), 1);
8231 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8232 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8233 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8235 _ => panic!("Unexpected event"),
8240 fn test_override_channel_config() {
8241 let chanmon_cfgs = create_chanmon_cfgs(2);
8242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8244 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8246 // Node0 initiates a channel to node1 using the override config.
8247 let mut override_config = UserConfig::default();
8248 override_config.channel_handshake_config.our_to_self_delay = 200;
8250 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8252 // Assert the channel created by node0 is using the override config.
8253 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8254 assert_eq!(res.channel_flags, 0);
8255 assert_eq!(res.to_self_delay, 200);
8259 fn test_override_0msat_htlc_minimum() {
8260 let mut zero_config = UserConfig::default();
8261 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8262 let chanmon_cfgs = create_chanmon_cfgs(2);
8263 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8264 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8265 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8267 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8268 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8269 assert_eq!(res.htlc_minimum_msat, 1);
8271 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8272 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8273 assert_eq!(res.htlc_minimum_msat, 1);
8277 fn test_channel_update_has_correct_htlc_maximum_msat() {
8278 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8279 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8280 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8281 // 90% of the `channel_value`.
8282 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8284 let mut config_30_percent = UserConfig::default();
8285 config_30_percent.channel_handshake_config.announced_channel = true;
8286 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8287 let mut config_50_percent = UserConfig::default();
8288 config_50_percent.channel_handshake_config.announced_channel = true;
8289 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8290 let mut config_95_percent = UserConfig::default();
8291 config_95_percent.channel_handshake_config.announced_channel = true;
8292 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8293 let mut config_100_percent = UserConfig::default();
8294 config_100_percent.channel_handshake_config.announced_channel = true;
8295 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8297 let chanmon_cfgs = create_chanmon_cfgs(4);
8298 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8299 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)]);
8300 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8302 let channel_value_satoshis = 100000;
8303 let channel_value_msat = channel_value_satoshis * 1000;
8304 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8305 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8306 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8308 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());
8309 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());
8311 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8312 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8313 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8314 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8315 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8316 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8318 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8319 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8321 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8322 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8323 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8325 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8329 fn test_manually_accept_inbound_channel_request() {
8330 let mut manually_accept_conf = UserConfig::default();
8331 manually_accept_conf.manually_accept_inbound_channels = true;
8332 let chanmon_cfgs = create_chanmon_cfgs(2);
8333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8335 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8337 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8338 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8340 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8342 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8343 // accepting the inbound channel request.
8344 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8346 let events = nodes[1].node.get_and_clear_pending_events();
8348 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8349 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8351 _ => panic!("Unexpected event"),
8354 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8355 assert_eq!(accept_msg_ev.len(), 1);
8357 match accept_msg_ev[0] {
8358 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8359 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8361 _ => panic!("Unexpected event"),
8364 nodes[1].node.force_close_channel(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8366 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8367 assert_eq!(close_msg_ev.len(), 1);
8369 let events = nodes[1].node.get_and_clear_pending_events();
8371 Event::ChannelClosed { user_channel_id, .. } => {
8372 assert_eq!(user_channel_id, 23);
8374 _ => panic!("Unexpected event"),
8379 fn test_manually_reject_inbound_channel_request() {
8380 let mut manually_accept_conf = UserConfig::default();
8381 manually_accept_conf.manually_accept_inbound_channels = true;
8382 let chanmon_cfgs = create_chanmon_cfgs(2);
8383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8385 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8387 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8388 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8390 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8392 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8393 // rejecting the inbound channel request.
8394 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8396 let events = nodes[1].node.get_and_clear_pending_events();
8398 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8399 nodes[1].node.force_close_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8401 _ => panic!("Unexpected event"),
8404 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8405 assert_eq!(close_msg_ev.len(), 1);
8407 match close_msg_ev[0] {
8408 MessageSendEvent::HandleError { ref node_id, .. } => {
8409 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8411 _ => panic!("Unexpected event"),
8413 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8417 fn test_reject_funding_before_inbound_channel_accepted() {
8418 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8419 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8420 // the node operator before the counterparty sends a `FundingCreated` message. If a
8421 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8422 // and the channel should be closed.
8423 let mut manually_accept_conf = UserConfig::default();
8424 manually_accept_conf.manually_accept_inbound_channels = true;
8425 let chanmon_cfgs = create_chanmon_cfgs(2);
8426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8428 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8430 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8431 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8432 let temp_channel_id = res.temporary_channel_id;
8434 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8436 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8437 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8439 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8440 nodes[1].node.get_and_clear_pending_events();
8442 // Get the `AcceptChannel` message of `nodes[1]` without calling
8443 // `ChannelManager::accept_inbound_channel`, which generates a
8444 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8445 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8446 // succeed when `nodes[0]` is passed to it.
8449 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8450 let accept_chan_msg = channel.get_accept_channel_message();
8451 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8454 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8456 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8457 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8459 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8460 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8462 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8463 assert_eq!(close_msg_ev.len(), 1);
8465 let expected_err = "FundingCreated message received before the channel was accepted";
8466 match close_msg_ev[0] {
8467 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8468 assert_eq!(msg.channel_id, temp_channel_id);
8469 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8470 assert_eq!(msg.data, expected_err);
8472 _ => panic!("Unexpected event"),
8475 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8479 fn test_can_not_accept_inbound_channel_twice() {
8480 let mut manually_accept_conf = UserConfig::default();
8481 manually_accept_conf.manually_accept_inbound_channels = true;
8482 let chanmon_cfgs = create_chanmon_cfgs(2);
8483 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8484 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8485 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8487 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8488 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8490 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8492 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8493 // accepting the inbound channel request.
8494 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8496 let events = nodes[1].node.get_and_clear_pending_events();
8498 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8499 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8500 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8502 Err(APIError::APIMisuseError { err }) => {
8503 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8505 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8506 Err(_) => panic!("Unexpected Error"),
8509 _ => panic!("Unexpected event"),
8512 // Ensure that the channel wasn't closed after attempting to accept it twice.
8513 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8514 assert_eq!(accept_msg_ev.len(), 1);
8516 match accept_msg_ev[0] {
8517 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8518 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8520 _ => panic!("Unexpected event"),
8525 fn test_can_not_accept_unknown_inbound_channel() {
8526 let chanmon_cfg = create_chanmon_cfgs(2);
8527 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8528 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8529 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8531 let unknown_channel_id = [0; 32];
8532 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8534 Err(APIError::ChannelUnavailable { err }) => {
8535 assert_eq!(err, "Can't accept a channel that doesn't exist");
8537 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8538 Err(_) => panic!("Unexpected Error"),
8543 fn test_simple_mpp() {
8544 // Simple test of sending a multi-path payment.
8545 let chanmon_cfgs = create_chanmon_cfgs(4);
8546 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8547 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8548 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8550 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8551 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8552 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8553 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8555 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8556 let path = route.paths[0].clone();
8557 route.paths.push(path);
8558 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8559 route.paths[0][0].short_channel_id = chan_1_id;
8560 route.paths[0][1].short_channel_id = chan_3_id;
8561 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8562 route.paths[1][0].short_channel_id = chan_2_id;
8563 route.paths[1][1].short_channel_id = chan_4_id;
8564 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8565 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8569 fn test_preimage_storage() {
8570 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8571 let chanmon_cfgs = create_chanmon_cfgs(2);
8572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8576 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8579 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8580 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8581 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8582 check_added_monitors!(nodes[0], 1);
8583 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8584 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8585 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8586 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8588 // Note that after leaving the above scope we have no knowledge of any arguments or return
8589 // values from previous calls.
8590 expect_pending_htlcs_forwardable!(nodes[1]);
8591 let events = nodes[1].node.get_and_clear_pending_events();
8592 assert_eq!(events.len(), 1);
8594 Event::PaymentReceived { ref purpose, .. } => {
8596 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8597 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8599 _ => panic!("expected PaymentPurpose::InvoicePayment")
8602 _ => panic!("Unexpected event"),
8607 #[allow(deprecated)]
8608 fn test_secret_timeout() {
8609 // Simple test of payment secret storage time outs. After
8610 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8611 let chanmon_cfgs = create_chanmon_cfgs(2);
8612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8614 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8616 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8618 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8620 // We should fail to register the same payment hash twice, at least until we've connected a
8621 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8622 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8623 assert_eq!(err, "Duplicate payment hash");
8624 } else { panic!(); }
8626 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8628 header: BlockHeader {
8630 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8631 merkle_root: Default::default(),
8632 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8636 connect_block(&nodes[1], &block);
8637 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8638 assert_eq!(err, "Duplicate payment hash");
8639 } else { panic!(); }
8641 // If we then connect the second block, we should be able to register the same payment hash
8642 // again (this time getting a new payment secret).
8643 block.header.prev_blockhash = block.header.block_hash();
8644 block.header.time += 1;
8645 connect_block(&nodes[1], &block);
8646 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8647 assert_ne!(payment_secret_1, our_payment_secret);
8650 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8651 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8652 check_added_monitors!(nodes[0], 1);
8653 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8654 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8655 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8656 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8658 // Note that after leaving the above scope we have no knowledge of any arguments or return
8659 // values from previous calls.
8660 expect_pending_htlcs_forwardable!(nodes[1]);
8661 let events = nodes[1].node.get_and_clear_pending_events();
8662 assert_eq!(events.len(), 1);
8664 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8665 assert!(payment_preimage.is_none());
8666 assert_eq!(payment_secret, our_payment_secret);
8667 // We don't actually have the payment preimage with which to claim this payment!
8669 _ => panic!("Unexpected event"),
8674 fn test_bad_secret_hash() {
8675 // Simple test of unregistered payment hash/invalid payment secret handling
8676 let chanmon_cfgs = create_chanmon_cfgs(2);
8677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8681 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8683 let random_payment_hash = PaymentHash([42; 32]);
8684 let random_payment_secret = PaymentSecret([43; 32]);
8685 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8686 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8688 // All the below cases should end up being handled exactly identically, so we macro the
8689 // resulting events.
8690 macro_rules! handle_unknown_invalid_payment_data {
8692 check_added_monitors!(nodes[0], 1);
8693 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8694 let payment_event = SendEvent::from_event(events.pop().unwrap());
8695 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8696 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8698 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8699 // again to process the pending backwards-failure of the HTLC
8700 expect_pending_htlcs_forwardable!(nodes[1]);
8701 expect_pending_htlcs_forwardable!(nodes[1]);
8702 check_added_monitors!(nodes[1], 1);
8704 // We should fail the payment back
8705 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8706 match events.pop().unwrap() {
8707 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8708 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8709 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8711 _ => panic!("Unexpected event"),
8716 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8717 // Error data is the HTLC value (100,000) and current block height
8718 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8720 // Send a payment with the right payment hash but the wrong payment secret
8721 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8722 handle_unknown_invalid_payment_data!();
8723 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8725 // Send a payment with a random payment hash, but the right payment secret
8726 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8727 handle_unknown_invalid_payment_data!();
8728 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8730 // Send a payment with a random payment hash and random payment secret
8731 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8732 handle_unknown_invalid_payment_data!();
8733 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8737 fn test_update_err_monitor_lockdown() {
8738 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8739 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8740 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8742 // This scenario may happen in a watchtower setup, where watchtower process a block height
8743 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8744 // commitment at same time.
8746 let chanmon_cfgs = create_chanmon_cfgs(2);
8747 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8748 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8749 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8751 // Create some initial channel
8752 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8753 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8755 // Rebalance the network to generate htlc in the two directions
8756 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8758 // Route a HTLC from node 0 to node 1 (but don't settle)
8759 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8761 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8762 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8763 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8764 let persister = test_utils::TestPersister::new();
8766 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8767 let mut w = test_utils::TestVecWriter(Vec::new());
8768 monitor.write(&mut w).unwrap();
8769 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8770 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8771 assert!(new_monitor == *monitor);
8772 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);
8773 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8776 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8777 let block = Block { header, txdata: vec![] };
8778 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8779 // transaction lock time requirements here.
8780 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8781 watchtower.chain_monitor.block_connected(&block, 200);
8783 // Try to update ChannelMonitor
8784 nodes[1].node.claim_funds(preimage);
8785 check_added_monitors!(nodes[1], 1);
8786 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8788 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8789 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8790 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8791 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8792 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8793 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8794 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8795 } else { assert!(false); }
8796 } else { assert!(false); };
8797 // Our local monitor is in-sync and hasn't processed yet timeout
8798 check_added_monitors!(nodes[0], 1);
8799 let events = nodes[0].node.get_and_clear_pending_events();
8800 assert_eq!(events.len(), 1);
8804 fn test_concurrent_monitor_claim() {
8805 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8806 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8807 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8808 // state N+1 confirms. Alice claims output from state N+1.
8810 let chanmon_cfgs = create_chanmon_cfgs(2);
8811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8813 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8815 // Create some initial channel
8816 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8817 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8819 // Rebalance the network to generate htlc in the two directions
8820 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8822 // Route a HTLC from node 0 to node 1 (but don't settle)
8823 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8825 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8826 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8827 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8828 let persister = test_utils::TestPersister::new();
8829 let watchtower_alice = {
8830 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8831 let mut w = test_utils::TestVecWriter(Vec::new());
8832 monitor.write(&mut w).unwrap();
8833 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8834 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8835 assert!(new_monitor == *monitor);
8836 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);
8837 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8840 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8841 let block = Block { header, txdata: vec![] };
8842 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8843 // transaction lock time requirements here.
8844 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));
8845 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8847 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8849 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8850 assert_eq!(txn.len(), 2);
8854 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8855 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8856 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8857 let persister = test_utils::TestPersister::new();
8858 let watchtower_bob = {
8859 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8860 let mut w = test_utils::TestVecWriter(Vec::new());
8861 monitor.write(&mut w).unwrap();
8862 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8863 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8864 assert!(new_monitor == *monitor);
8865 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);
8866 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8869 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8870 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8872 // Route another payment to generate another update with still previous HTLC pending
8873 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8875 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8877 check_added_monitors!(nodes[1], 1);
8879 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8880 assert_eq!(updates.update_add_htlcs.len(), 1);
8881 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8882 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8883 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8884 // Watchtower Alice should already have seen the block and reject the update
8885 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8886 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8887 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8888 } else { assert!(false); }
8889 } else { assert!(false); };
8890 // Our local monitor is in-sync and hasn't processed yet timeout
8891 check_added_monitors!(nodes[0], 1);
8893 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8894 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8895 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8897 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8900 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8901 assert_eq!(txn.len(), 2);
8902 bob_state_y = txn[0].clone();
8906 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8907 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8908 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);
8910 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8911 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8912 // the onchain detection of the HTLC output
8913 assert_eq!(htlc_txn.len(), 2);
8914 check_spends!(htlc_txn[0], bob_state_y);
8915 check_spends!(htlc_txn[1], bob_state_y);
8920 fn test_pre_lockin_no_chan_closed_update() {
8921 // Test that if a peer closes a channel in response to a funding_created message we don't
8922 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8925 // Doing so would imply a channel monitor update before the initial channel monitor
8926 // registration, violating our API guarantees.
8928 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8929 // then opening a second channel with the same funding output as the first (which is not
8930 // rejected because the first channel does not exist in the ChannelManager) and closing it
8931 // before receiving funding_signed.
8932 let chanmon_cfgs = create_chanmon_cfgs(2);
8933 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8934 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8935 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8937 // Create an initial channel
8938 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8939 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8940 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8941 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8942 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8944 // Move the first channel through the funding flow...
8945 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8947 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8948 check_added_monitors!(nodes[0], 0);
8950 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8951 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8952 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8953 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8954 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8958 fn test_htlc_no_detection() {
8959 // This test is a mutation to underscore the detection logic bug we had
8960 // before #653. HTLC value routed is above the remaining balance, thus
8961 // inverting HTLC and `to_remote` output. HTLC will come second and
8962 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8963 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8964 // outputs order detection for correct spending children filtring.
8966 let chanmon_cfgs = create_chanmon_cfgs(2);
8967 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8968 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8969 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8971 // Create some initial channels
8972 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8974 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8975 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8976 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8977 assert_eq!(local_txn[0].input.len(), 1);
8978 assert_eq!(local_txn[0].output.len(), 3);
8979 check_spends!(local_txn[0], chan_1.3);
8981 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8982 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8983 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8984 // We deliberately connect the local tx twice as this should provoke a failure calling
8985 // this test before #653 fix.
8986 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);
8987 check_closed_broadcast!(nodes[0], true);
8988 check_added_monitors!(nodes[0], 1);
8989 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8990 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8992 let htlc_timeout = {
8993 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8994 assert_eq!(node_txn[1].input.len(), 1);
8995 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8996 check_spends!(node_txn[1], local_txn[0]);
9000 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9001 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9002 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9003 expect_payment_failed!(nodes[0], our_payment_hash, true);
9006 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9007 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9008 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9009 // Carol, Alice would be the upstream node, and Carol the downstream.)
9011 // Steps of the test:
9012 // 1) Alice sends a HTLC to Carol through Bob.
9013 // 2) Carol doesn't settle the HTLC.
9014 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9015 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9016 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9017 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9018 // 5) Carol release the preimage to Bob off-chain.
9019 // 6) Bob claims the offered output on the broadcasted commitment.
9020 let chanmon_cfgs = create_chanmon_cfgs(3);
9021 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9022 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9023 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9025 // Create some initial channels
9026 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9027 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9029 // Steps (1) and (2):
9030 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9031 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9033 // Check that Alice's commitment transaction now contains an output for this HTLC.
9034 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9035 check_spends!(alice_txn[0], chan_ab.3);
9036 assert_eq!(alice_txn[0].output.len(), 2);
9037 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9038 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9039 assert_eq!(alice_txn.len(), 2);
9041 // Steps (3) and (4):
9042 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9043 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9044 let mut force_closing_node = 0; // Alice force-closes
9045 let mut counterparty_node = 1; // Bob if Alice force-closes
9048 if !broadcast_alice {
9049 force_closing_node = 1;
9050 counterparty_node = 0;
9052 nodes[force_closing_node].node.force_close_channel(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9053 check_closed_broadcast!(nodes[force_closing_node], true);
9054 check_added_monitors!(nodes[force_closing_node], 1);
9055 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9056 if go_onchain_before_fulfill {
9057 let txn_to_broadcast = match broadcast_alice {
9058 true => alice_txn.clone(),
9059 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9061 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9062 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9063 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9064 if broadcast_alice {
9065 check_closed_broadcast!(nodes[1], true);
9066 check_added_monitors!(nodes[1], 1);
9067 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9069 assert_eq!(bob_txn.len(), 1);
9070 check_spends!(bob_txn[0], chan_ab.3);
9074 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9075 // process of removing the HTLC from their commitment transactions.
9076 nodes[2].node.claim_funds(payment_preimage);
9077 check_added_monitors!(nodes[2], 1);
9078 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9080 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9081 assert!(carol_updates.update_add_htlcs.is_empty());
9082 assert!(carol_updates.update_fail_htlcs.is_empty());
9083 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9084 assert!(carol_updates.update_fee.is_none());
9085 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9087 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9088 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9089 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9090 if !go_onchain_before_fulfill && broadcast_alice {
9091 let events = nodes[1].node.get_and_clear_pending_msg_events();
9092 assert_eq!(events.len(), 1);
9094 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9095 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9097 _ => panic!("Unexpected event"),
9100 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9101 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9102 // Carol<->Bob's updated commitment transaction info.
9103 check_added_monitors!(nodes[1], 2);
9105 let events = nodes[1].node.get_and_clear_pending_msg_events();
9106 assert_eq!(events.len(), 2);
9107 let bob_revocation = match events[0] {
9108 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9109 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9112 _ => panic!("Unexpected event"),
9114 let bob_updates = match events[1] {
9115 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9116 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9119 _ => panic!("Unexpected event"),
9122 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9123 check_added_monitors!(nodes[2], 1);
9124 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9125 check_added_monitors!(nodes[2], 1);
9127 let events = nodes[2].node.get_and_clear_pending_msg_events();
9128 assert_eq!(events.len(), 1);
9129 let carol_revocation = match events[0] {
9130 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9131 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9134 _ => panic!("Unexpected event"),
9136 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9137 check_added_monitors!(nodes[1], 1);
9139 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9140 // here's where we put said channel's commitment tx on-chain.
9141 let mut txn_to_broadcast = alice_txn.clone();
9142 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9143 if !go_onchain_before_fulfill {
9144 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9145 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9146 // If Bob was the one to force-close, he will have already passed these checks earlier.
9147 if broadcast_alice {
9148 check_closed_broadcast!(nodes[1], true);
9149 check_added_monitors!(nodes[1], 1);
9150 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9152 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9153 if broadcast_alice {
9154 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9155 // new block being connected. The ChannelManager being notified triggers a monitor update,
9156 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9157 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9159 assert_eq!(bob_txn.len(), 3);
9160 check_spends!(bob_txn[1], chan_ab.3);
9162 assert_eq!(bob_txn.len(), 2);
9163 check_spends!(bob_txn[0], chan_ab.3);
9168 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9169 // broadcasted commitment transaction.
9171 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9172 if go_onchain_before_fulfill {
9173 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9174 assert_eq!(bob_txn.len(), 2);
9176 let script_weight = match broadcast_alice {
9177 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9178 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9180 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9181 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9182 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9183 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9184 if broadcast_alice && !go_onchain_before_fulfill {
9185 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9186 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9188 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9189 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9195 fn test_onchain_htlc_settlement_after_close() {
9196 do_test_onchain_htlc_settlement_after_close(true, true);
9197 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9198 do_test_onchain_htlc_settlement_after_close(true, false);
9199 do_test_onchain_htlc_settlement_after_close(false, false);
9203 fn test_duplicate_chan_id() {
9204 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9205 // already open we reject it and keep the old channel.
9207 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9208 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9209 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9210 // updating logic for the existing channel.
9211 let chanmon_cfgs = create_chanmon_cfgs(2);
9212 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9213 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9214 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9216 // Create an initial channel
9217 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9218 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9219 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9220 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()));
9222 // Try to create a second channel with the same temporary_channel_id as the first and check
9223 // that it is rejected.
9224 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9226 let events = nodes[1].node.get_and_clear_pending_msg_events();
9227 assert_eq!(events.len(), 1);
9229 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9230 // Technically, at this point, nodes[1] would be justified in thinking both the
9231 // first (valid) and second (invalid) channels are closed, given they both have
9232 // the same non-temporary channel_id. However, currently we do not, so we just
9233 // move forward with it.
9234 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9235 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9237 _ => panic!("Unexpected event"),
9241 // Move the first channel through the funding flow...
9242 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9244 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9245 check_added_monitors!(nodes[0], 0);
9247 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9248 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9250 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9251 assert_eq!(added_monitors.len(), 1);
9252 assert_eq!(added_monitors[0].0, funding_output);
9253 added_monitors.clear();
9255 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9257 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9258 let channel_id = funding_outpoint.to_channel_id();
9260 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9263 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9264 // Technically this is allowed by the spec, but we don't support it and there's little reason
9265 // to. Still, it shouldn't cause any other issues.
9266 open_chan_msg.temporary_channel_id = channel_id;
9267 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9269 let events = nodes[1].node.get_and_clear_pending_msg_events();
9270 assert_eq!(events.len(), 1);
9272 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9273 // Technically, at this point, nodes[1] would be justified in thinking both
9274 // channels are closed, but currently we do not, so we just move forward with it.
9275 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9276 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9278 _ => panic!("Unexpected event"),
9282 // Now try to create a second channel which has a duplicate funding output.
9283 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9284 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9285 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9286 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()));
9287 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9289 let funding_created = {
9290 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9291 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9292 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9293 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9294 // channelmanager in a possibly nonsense state instead).
9295 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9296 let logger = test_utils::TestLogger::new();
9297 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9299 check_added_monitors!(nodes[0], 0);
9300 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9301 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9302 // still needs to be cleared here.
9303 check_added_monitors!(nodes[1], 1);
9305 // ...still, nodes[1] will reject the duplicate channel.
9307 let events = nodes[1].node.get_and_clear_pending_msg_events();
9308 assert_eq!(events.len(), 1);
9310 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9311 // Technically, at this point, nodes[1] would be justified in thinking both
9312 // channels are closed, but currently we do not, so we just move forward with it.
9313 assert_eq!(msg.channel_id, channel_id);
9314 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9316 _ => panic!("Unexpected event"),
9320 // finally, finish creating the original channel and send a payment over it to make sure
9321 // everything is functional.
9322 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9324 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9325 assert_eq!(added_monitors.len(), 1);
9326 assert_eq!(added_monitors[0].0, funding_output);
9327 added_monitors.clear();
9330 let events_4 = nodes[0].node.get_and_clear_pending_events();
9331 assert_eq!(events_4.len(), 0);
9332 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9333 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9335 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9336 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9337 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9338 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9342 fn test_error_chans_closed() {
9343 // Test that we properly handle error messages, closing appropriate channels.
9345 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9346 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9347 // we can test various edge cases around it to ensure we don't regress.
9348 let chanmon_cfgs = create_chanmon_cfgs(3);
9349 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9350 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9351 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9353 // Create some initial channels
9354 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9355 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9356 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9358 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9359 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9360 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9362 // Closing a channel from a different peer has no effect
9363 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9364 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9366 // Closing one channel doesn't impact others
9367 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9368 check_added_monitors!(nodes[0], 1);
9369 check_closed_broadcast!(nodes[0], false);
9370 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9371 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9372 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9373 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);
9374 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);
9376 // A null channel ID should close all channels
9377 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9378 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9379 check_added_monitors!(nodes[0], 2);
9380 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9381 let events = nodes[0].node.get_and_clear_pending_msg_events();
9382 assert_eq!(events.len(), 2);
9384 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9385 assert_eq!(msg.contents.flags & 2, 2);
9387 _ => panic!("Unexpected event"),
9390 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9391 assert_eq!(msg.contents.flags & 2, 2);
9393 _ => panic!("Unexpected event"),
9395 // Note that at this point users of a standard PeerHandler will end up calling
9396 // peer_disconnected with no_connection_possible set to false, duplicating the
9397 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9398 // users with their own peer handling logic. We duplicate the call here, however.
9399 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9400 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9402 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9403 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9404 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9408 fn test_invalid_funding_tx() {
9409 // Test that we properly handle invalid funding transactions sent to us from a peer.
9411 // Previously, all other major lightning implementations had failed to properly sanitize
9412 // funding transactions from their counterparties, leading to a multi-implementation critical
9413 // security vulnerability (though we always sanitized properly, we've previously had
9414 // un-released crashes in the sanitization process).
9415 let chanmon_cfgs = create_chanmon_cfgs(2);
9416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9420 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9421 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()));
9422 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()));
9424 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9425 for output in tx.output.iter_mut() {
9426 // Make the confirmed funding transaction have a bogus script_pubkey
9427 output.script_pubkey = bitcoin::Script::new();
9430 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9431 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()));
9432 check_added_monitors!(nodes[1], 1);
9434 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()));
9435 check_added_monitors!(nodes[0], 1);
9437 let events_1 = nodes[0].node.get_and_clear_pending_events();
9438 assert_eq!(events_1.len(), 0);
9440 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9441 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9442 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9444 let expected_err = "funding tx had wrong script/value or output index";
9445 confirm_transaction_at(&nodes[1], &tx, 1);
9446 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9447 check_added_monitors!(nodes[1], 1);
9448 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9449 assert_eq!(events_2.len(), 1);
9450 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9451 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9452 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9453 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9454 } else { panic!(); }
9455 } else { panic!(); }
9456 assert_eq!(nodes[1].node.list_channels().len(), 0);
9459 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9460 // In the first version of the chain::Confirm interface, after a refactor was made to not
9461 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9462 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9463 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9464 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9465 // spending transaction until height N+1 (or greater). This was due to the way
9466 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9467 // spending transaction at the height the input transaction was confirmed at, not whether we
9468 // should broadcast a spending transaction at the current height.
9469 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9470 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9471 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9472 // until we learned about an additional block.
9474 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9475 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9476 let chanmon_cfgs = create_chanmon_cfgs(3);
9477 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9478 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9479 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9480 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9482 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9483 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9484 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9485 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9486 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9488 nodes[1].node.force_close_channel(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9489 check_closed_broadcast!(nodes[1], true);
9490 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9491 check_added_monitors!(nodes[1], 1);
9492 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9493 assert_eq!(node_txn.len(), 1);
9495 let conf_height = nodes[1].best_block_info().1;
9496 if !test_height_before_timelock {
9497 connect_blocks(&nodes[1], 24 * 6);
9499 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9500 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9501 if test_height_before_timelock {
9502 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9503 // generate any events or broadcast any transactions
9504 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9505 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9507 // We should broadcast an HTLC transaction spending our funding transaction first
9508 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9509 assert_eq!(spending_txn.len(), 2);
9510 assert_eq!(spending_txn[0], node_txn[0]);
9511 check_spends!(spending_txn[1], node_txn[0]);
9512 // We should also generate a SpendableOutputs event with the to_self output (as its
9514 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9515 assert_eq!(descriptor_spend_txn.len(), 1);
9517 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9518 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9519 // additional block built on top of the current chain.
9520 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9521 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9522 expect_pending_htlcs_forwardable!(nodes[1]);
9523 check_added_monitors!(nodes[1], 1);
9525 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9526 assert!(updates.update_add_htlcs.is_empty());
9527 assert!(updates.update_fulfill_htlcs.is_empty());
9528 assert_eq!(updates.update_fail_htlcs.len(), 1);
9529 assert!(updates.update_fail_malformed_htlcs.is_empty());
9530 assert!(updates.update_fee.is_none());
9531 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9532 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9533 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9538 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9539 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9540 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9544 fn test_forwardable_regen() {
9545 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9546 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9548 // We test it for both payment receipt and payment forwarding.
9550 let chanmon_cfgs = create_chanmon_cfgs(3);
9551 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9552 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9553 let persister: test_utils::TestPersister;
9554 let new_chain_monitor: test_utils::TestChainMonitor;
9555 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9556 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9557 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9558 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9560 // First send a payment to nodes[1]
9561 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9562 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9563 check_added_monitors!(nodes[0], 1);
9565 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9566 assert_eq!(events.len(), 1);
9567 let payment_event = SendEvent::from_event(events.pop().unwrap());
9568 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9569 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9571 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9573 // Next send a payment which is forwarded by nodes[1]
9574 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9575 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9576 check_added_monitors!(nodes[0], 1);
9578 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9579 assert_eq!(events.len(), 1);
9580 let payment_event = SendEvent::from_event(events.pop().unwrap());
9581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9582 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9584 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9586 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9588 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9590 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9592 let nodes_1_serialized = nodes[1].node.encode();
9593 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9594 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9595 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9596 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9598 persister = test_utils::TestPersister::new();
9599 let keys_manager = &chanmon_cfgs[1].keys_manager;
9600 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);
9601 nodes[1].chain_monitor = &new_chain_monitor;
9603 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9604 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9605 &mut chan_0_monitor_read, keys_manager).unwrap();
9606 assert!(chan_0_monitor_read.is_empty());
9607 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9608 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9609 &mut chan_1_monitor_read, keys_manager).unwrap();
9610 assert!(chan_1_monitor_read.is_empty());
9612 let mut nodes_1_read = &nodes_1_serialized[..];
9613 let (_, nodes_1_deserialized_tmp) = {
9614 let mut channel_monitors = HashMap::new();
9615 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9616 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9617 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9618 default_config: UserConfig::default(),
9620 fee_estimator: node_cfgs[1].fee_estimator,
9621 chain_monitor: nodes[1].chain_monitor,
9622 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9623 logger: nodes[1].logger,
9627 nodes_1_deserialized = nodes_1_deserialized_tmp;
9628 assert!(nodes_1_read.is_empty());
9630 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9631 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9632 nodes[1].node = &nodes_1_deserialized;
9633 check_added_monitors!(nodes[1], 2);
9635 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9636 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9637 // the commitment state.
9638 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9640 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9642 expect_pending_htlcs_forwardable!(nodes[1]);
9643 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9644 check_added_monitors!(nodes[1], 1);
9646 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9647 assert_eq!(events.len(), 1);
9648 let payment_event = SendEvent::from_event(events.pop().unwrap());
9649 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9650 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9651 expect_pending_htlcs_forwardable!(nodes[2]);
9652 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9654 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9655 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9658 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9659 let chanmon_cfgs = create_chanmon_cfgs(2);
9660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9662 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9664 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9666 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9667 .with_features(InvoiceFeatures::known());
9668 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9670 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9673 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9674 check_added_monitors!(nodes[0], 1);
9675 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9676 assert_eq!(events.len(), 1);
9677 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9678 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9679 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9681 expect_pending_htlcs_forwardable!(nodes[1]);
9682 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9685 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9686 check_added_monitors!(nodes[0], 1);
9687 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9688 assert_eq!(events.len(), 1);
9689 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9690 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9691 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9692 // At this point, nodes[1] would notice it has too much value for the payment. It will
9693 // assume the second is a privacy attack (no longer particularly relevant
9694 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9695 // the first HTLC delivered above.
9698 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9699 nodes[1].node.process_pending_htlc_forwards();
9701 if test_for_second_fail_panic {
9702 // Now we go fail back the first HTLC from the user end.
9703 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9705 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9706 nodes[1].node.process_pending_htlc_forwards();
9708 check_added_monitors!(nodes[1], 1);
9709 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9710 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9712 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9713 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9714 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9716 let failure_events = nodes[0].node.get_and_clear_pending_events();
9717 assert_eq!(failure_events.len(), 2);
9718 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9719 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9721 // Let the second HTLC fail and claim the first
9722 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9723 nodes[1].node.process_pending_htlc_forwards();
9725 check_added_monitors!(nodes[1], 1);
9726 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9727 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9728 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9730 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9732 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9737 fn test_dup_htlc_second_fail_panic() {
9738 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9739 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9740 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9741 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9742 do_test_dup_htlc_second_rejected(true);
9746 fn test_dup_htlc_second_rejected() {
9747 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9748 // simply reject the second HTLC but are still able to claim the first HTLC.
9749 do_test_dup_htlc_second_rejected(false);
9753 fn test_inconsistent_mpp_params() {
9754 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9755 // such HTLC and allow the second to stay.
9756 let chanmon_cfgs = create_chanmon_cfgs(4);
9757 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9758 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9759 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9761 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9762 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9763 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9764 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9766 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9767 .with_features(InvoiceFeatures::known());
9768 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9769 assert_eq!(route.paths.len(), 2);
9770 route.paths.sort_by(|path_a, _| {
9771 // Sort the path so that the path through nodes[1] comes first
9772 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9773 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9775 let payment_params_opt = Some(payment_params);
9777 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9779 let cur_height = nodes[0].best_block_info().1;
9780 let payment_id = PaymentId([42; 32]);
9782 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();
9783 check_added_monitors!(nodes[0], 1);
9785 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9786 assert_eq!(events.len(), 1);
9787 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9789 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9792 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();
9793 check_added_monitors!(nodes[0], 1);
9795 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9796 assert_eq!(events.len(), 1);
9797 let payment_event = SendEvent::from_event(events.pop().unwrap());
9799 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9800 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9802 expect_pending_htlcs_forwardable!(nodes[2]);
9803 check_added_monitors!(nodes[2], 1);
9805 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9806 assert_eq!(events.len(), 1);
9807 let payment_event = SendEvent::from_event(events.pop().unwrap());
9809 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9810 check_added_monitors!(nodes[3], 0);
9811 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9813 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9814 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9815 // post-payment_secrets) and fail back the new HTLC.
9817 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9818 nodes[3].node.process_pending_htlc_forwards();
9819 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9820 nodes[3].node.process_pending_htlc_forwards();
9822 check_added_monitors!(nodes[3], 1);
9824 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9825 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9826 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9828 expect_pending_htlcs_forwardable!(nodes[2]);
9829 check_added_monitors!(nodes[2], 1);
9831 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9832 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9833 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9835 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9837 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();
9838 check_added_monitors!(nodes[0], 1);
9840 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9841 assert_eq!(events.len(), 1);
9842 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9844 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9848 fn test_keysend_payments_to_public_node() {
9849 let chanmon_cfgs = create_chanmon_cfgs(2);
9850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9852 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9854 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9855 let network_graph = nodes[0].network_graph;
9856 let payer_pubkey = nodes[0].node.get_our_node_id();
9857 let payee_pubkey = nodes[1].node.get_our_node_id();
9858 let route_params = RouteParameters {
9859 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9860 final_value_msat: 10000,
9861 final_cltv_expiry_delta: 40,
9863 let scorer = test_utils::TestScorer::with_penalty(0);
9864 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9865 let route = find_route(&payer_pubkey, &route_params, &network_graph.read_only(), None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9867 let test_preimage = PaymentPreimage([42; 32]);
9868 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9869 check_added_monitors!(nodes[0], 1);
9870 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9871 assert_eq!(events.len(), 1);
9872 let event = events.pop().unwrap();
9873 let path = vec![&nodes[1]];
9874 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9875 claim_payment(&nodes[0], &path, test_preimage);
9879 fn test_keysend_payments_to_private_node() {
9880 let chanmon_cfgs = create_chanmon_cfgs(2);
9881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9885 let payer_pubkey = nodes[0].node.get_our_node_id();
9886 let payee_pubkey = nodes[1].node.get_our_node_id();
9887 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9888 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9890 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9891 let route_params = RouteParameters {
9892 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9893 final_value_msat: 10000,
9894 final_cltv_expiry_delta: 40,
9896 let network_graph = nodes[0].network_graph;
9897 let first_hops = nodes[0].node.list_usable_channels();
9898 let scorer = test_utils::TestScorer::with_penalty(0);
9899 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9900 let route = find_route(
9901 &payer_pubkey, &route_params, &network_graph.read_only(),
9902 Some(&first_hops.iter().collect::<Vec<_>>()), nodes[0].logger, &scorer, &random_seed_bytes
9905 let test_preimage = PaymentPreimage([42; 32]);
9906 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9907 check_added_monitors!(nodes[0], 1);
9908 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9909 assert_eq!(events.len(), 1);
9910 let event = events.pop().unwrap();
9911 let path = vec![&nodes[1]];
9912 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9913 claim_payment(&nodes[0], &path, test_preimage);
9917 fn test_double_partial_claim() {
9918 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9919 // time out, the sender resends only some of the MPP parts, then the user processes the
9920 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9922 let chanmon_cfgs = create_chanmon_cfgs(4);
9923 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9924 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9925 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9927 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9928 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9929 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9930 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9932 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9933 assert_eq!(route.paths.len(), 2);
9934 route.paths.sort_by(|path_a, _| {
9935 // Sort the path so that the path through nodes[1] comes first
9936 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9937 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9940 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9941 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
9942 // amount of time to respond to.
9944 // Connect some blocks to time out the payment
9945 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9946 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9948 expect_pending_htlcs_forwardable!(nodes[3]);
9950 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9952 // nodes[1] now retries one of the two paths...
9953 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9954 check_added_monitors!(nodes[0], 2);
9956 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9957 assert_eq!(events.len(), 2);
9958 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
9960 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9961 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
9962 nodes[3].node.claim_funds(payment_preimage);
9963 check_added_monitors!(nodes[3], 0);
9964 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9967 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
9968 // Test what happens if a node receives an MPP payment, claims it, but crashes before
9969 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
9970 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
9971 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
9972 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
9973 // not have the preimage tied to the still-pending HTLC.
9975 // To get to the correct state, on startup we should propagate the preimage to the
9976 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
9977 // receiving the preimage without a state update.
9979 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
9980 // definitely claimed.
9981 let chanmon_cfgs = create_chanmon_cfgs(4);
9982 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9983 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9985 let persister: test_utils::TestPersister;
9986 let new_chain_monitor: test_utils::TestChainMonitor;
9987 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9989 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9991 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9992 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9993 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9994 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
9996 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
9997 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9998 assert_eq!(route.paths.len(), 2);
9999 route.paths.sort_by(|path_a, _| {
10000 // Sort the path so that the path through nodes[1] comes first
10001 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10002 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10005 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10006 check_added_monitors!(nodes[0], 2);
10008 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10009 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10010 assert_eq!(send_events.len(), 2);
10011 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);
10012 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);
10014 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10015 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10016 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10017 if !persist_both_monitors {
10018 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10019 if outpoint.to_channel_id() == chan_id_not_persisted {
10020 assert!(original_monitor.0.is_empty());
10021 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10026 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10027 nodes[3].node.write(&mut original_manager).unwrap();
10029 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10031 nodes[3].node.claim_funds(payment_preimage);
10032 check_added_monitors!(nodes[3], 2);
10033 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10035 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10036 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10037 // with the old ChannelManager.
10038 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10039 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10040 if outpoint.to_channel_id() == chan_id_persisted {
10041 assert!(updated_monitor.0.is_empty());
10042 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10045 // If `persist_both_monitors` is set, get the second monitor here as well
10046 if persist_both_monitors {
10047 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10048 if outpoint.to_channel_id() == chan_id_not_persisted {
10049 assert!(original_monitor.0.is_empty());
10050 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10055 // Now restart nodes[3].
10056 persister = test_utils::TestPersister::new();
10057 let keys_manager = &chanmon_cfgs[3].keys_manager;
10058 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);
10059 nodes[3].chain_monitor = &new_chain_monitor;
10060 let mut monitors = Vec::new();
10061 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10062 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10063 monitors.push(deserialized_monitor);
10066 let config = UserConfig::default();
10067 nodes_3_deserialized = {
10068 let mut channel_monitors = HashMap::new();
10069 for monitor in monitors.iter_mut() {
10070 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10072 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10073 default_config: config,
10075 fee_estimator: node_cfgs[3].fee_estimator,
10076 chain_monitor: nodes[3].chain_monitor,
10077 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10078 logger: nodes[3].logger,
10082 nodes[3].node = &nodes_3_deserialized;
10084 for monitor in monitors {
10085 // On startup the preimage should have been copied into the non-persisted monitor:
10086 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10087 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10089 check_added_monitors!(nodes[3], 2);
10091 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10092 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10094 // During deserialization, we should have closed one channel and broadcast its latest
10095 // commitment transaction. We should also still have the original PaymentReceived event we
10096 // never finished processing.
10097 let events = nodes[3].node.get_and_clear_pending_events();
10098 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10099 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10100 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10101 if persist_both_monitors {
10102 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10105 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10106 // ChannelManager prior to handling the original one.
10107 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10108 events[if persist_both_monitors { 3 } else { 2 }]
10110 assert_eq!(payment_hash, our_payment_hash);
10111 } else { panic!(); }
10113 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10114 if !persist_both_monitors {
10115 // If one of the two channels is still live, reveal the payment preimage over it.
10117 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10118 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10119 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10120 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10122 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10123 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10124 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10126 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10128 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10129 // claim should fly.
10130 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10131 check_added_monitors!(nodes[3], 1);
10132 assert_eq!(ds_msgs.len(), 2);
10133 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10135 let cs_updates = match ds_msgs[0] {
10136 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10137 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10138 check_added_monitors!(nodes[2], 1);
10139 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10140 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10141 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10147 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10148 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10149 expect_payment_sent!(nodes[0], payment_preimage);
10154 fn test_partial_claim_before_restart() {
10155 do_test_partial_claim_before_restart(false);
10156 do_test_partial_claim_before_restart(true);
10159 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10160 #[derive(Clone, Copy, PartialEq)]
10161 enum ExposureEvent {
10162 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10164 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10166 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10167 AtUpdateFeeOutbound,
10170 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10171 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10174 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10175 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10176 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10177 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10178 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10179 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10180 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10181 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10183 let chanmon_cfgs = create_chanmon_cfgs(2);
10184 let mut config = test_default_channel_config();
10185 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10187 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10188 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10190 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10191 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10192 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10193 open_channel.max_accepted_htlcs = 60;
10195 open_channel.dust_limit_satoshis = 546;
10197 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10198 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10199 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10201 let opt_anchors = false;
10203 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10206 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10207 chan.holder_dust_limit_satoshis = 546;
10211 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10212 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()));
10213 check_added_monitors!(nodes[1], 1);
10215 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()));
10216 check_added_monitors!(nodes[0], 1);
10218 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10219 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10220 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10222 let dust_buffer_feerate = {
10223 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10224 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10225 chan.get_dust_buffer_feerate(None) as u64
10227 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;
10228 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10230 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;
10231 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10233 let dust_htlc_on_counterparty_tx: u64 = 25;
10234 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10237 if dust_outbound_balance {
10238 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10239 // Outbound dust balance: 4372 sats
10240 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10241 for i in 0..dust_outbound_htlc_on_holder_tx {
10242 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10243 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10246 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10247 // Inbound dust balance: 4372 sats
10248 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10249 for _ in 0..dust_inbound_htlc_on_holder_tx {
10250 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10254 if dust_outbound_balance {
10255 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10256 // Outbound dust balance: 5000 sats
10257 for i in 0..dust_htlc_on_counterparty_tx {
10258 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10259 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10262 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10263 // Inbound dust balance: 5000 sats
10264 for _ in 0..dust_htlc_on_counterparty_tx {
10265 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10270 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10271 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10272 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 });
10273 let mut config = UserConfig::default();
10274 // With default dust exposure: 5000 sats
10276 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10277 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10278 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)));
10280 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
10282 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10283 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 });
10284 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10285 check_added_monitors!(nodes[1], 1);
10286 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10287 assert_eq!(events.len(), 1);
10288 let payment_event = SendEvent::from_event(events.remove(0));
10289 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10290 // With default dust exposure: 5000 sats
10292 // Outbound dust balance: 6399 sats
10293 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10294 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10295 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);
10297 // Outbound dust balance: 5200 sats
10298 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);
10300 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10301 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10302 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10304 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10305 *feerate_lock = *feerate_lock * 10;
10307 nodes[0].node.timer_tick_occurred();
10308 check_added_monitors!(nodes[0], 1);
10309 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);
10312 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10313 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10314 added_monitors.clear();
10318 fn test_max_dust_htlc_exposure() {
10319 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10320 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10321 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10322 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10323 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10324 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10325 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10326 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10327 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10328 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10329 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10330 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);