1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
59 fn test_insane_channel_opens() {
60 // Stand up a network of 2 nodes
61 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
62 let mut cfg = UserConfig::default();
63 cfg.peer_channel_config_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
64 let chanmon_cfgs = create_chanmon_cfgs(2);
65 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
66 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
67 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
69 // Instantiate channel parameters where we push the maximum msats given our
71 let channel_value_sat = 31337; // same as funding satoshis
72 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
73 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
75 // Have node0 initiate a channel to node1 with aforementioned parameters
76 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
78 // Extract the channel open message from node0 to node1
79 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
81 // Test helper that asserts we get the correct error string given a mutator
82 // that supposedly makes the channel open message insane
83 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
84 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
85 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
86 assert_eq!(msg_events.len(), 1);
87 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
88 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
90 &ErrorAction::SendErrorMessage { .. } => {
91 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
93 _ => panic!("unexpected event!"),
95 } else { assert!(false); }
98 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
100 // Test all mutations that would make the channel open message insane
101 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
102 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
104 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
106 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
108 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
110 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 fn test_funding_exceeds_no_wumbo_limit() {
121 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
123 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
124 let chanmon_cfgs = create_chanmon_cfgs(2);
125 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
130 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
131 Err(APIError::APIMisuseError { err }) => {
132 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
138 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
139 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
140 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
141 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
142 // in normal testing, we test it explicitly here.
143 let chanmon_cfgs = create_chanmon_cfgs(2);
144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
146 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
148 // Have node0 initiate a channel to node1 with aforementioned parameters
149 let mut push_amt = 100_000_000;
150 let feerate_per_kw = 253;
151 let opt_anchors = false;
152 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
153 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
155 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
156 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
157 if !send_from_initiator {
158 open_channel_message.channel_reserve_satoshis = 0;
159 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
161 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
163 // Extract the channel accept message from node1 to node0
164 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
165 if send_from_initiator {
166 accept_channel_message.channel_reserve_satoshis = 0;
167 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
172 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
173 chan.holder_selected_channel_reserve_satoshis = 0;
174 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
177 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
178 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
179 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
181 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
182 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
183 if send_from_initiator {
184 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
185 // Note that for outbound channels we have to consider the commitment tx fee and the
186 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
187 // well as an additional HTLC.
188 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
190 send_payment(&nodes[1], &[&nodes[0]], push_amt);
195 fn test_counterparty_no_reserve() {
196 do_test_counterparty_no_reserve(true);
197 do_test_counterparty_no_reserve(false);
201 fn test_async_inbound_update_fee() {
202 let chanmon_cfgs = create_chanmon_cfgs(2);
203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
205 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
206 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
209 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
213 // send (1) commitment_signed -.
214 // <- update_add_htlc/commitment_signed
215 // send (2) RAA (awaiting remote revoke) -.
216 // (1) commitment_signed is delivered ->
217 // .- send (3) RAA (awaiting remote revoke)
218 // (2) RAA is delivered ->
219 // .- send (4) commitment_signed
220 // <- (3) RAA is delivered
221 // send (5) commitment_signed -.
222 // <- (4) commitment_signed is delivered
224 // (5) commitment_signed is delivered ->
226 // (6) RAA is delivered ->
228 // First nodes[0] generates an update_fee
230 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
233 nodes[0].node.timer_tick_occurred();
234 check_added_monitors!(nodes[0], 1);
236 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
237 assert_eq!(events_0.len(), 1);
238 let (update_msg, commitment_signed) = match events_0[0] { // (1)
239 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
240 (update_fee.as_ref(), commitment_signed)
242 _ => panic!("Unexpected event"),
245 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
247 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
248 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
249 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
250 check_added_monitors!(nodes[1], 1);
252 let payment_event = {
253 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
254 assert_eq!(events_1.len(), 1);
255 SendEvent::from_event(events_1.remove(0))
257 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
258 assert_eq!(payment_event.msgs.len(), 1);
260 // ...now when the messages get delivered everyone should be happy
261 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
262 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
263 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
264 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
265 check_added_monitors!(nodes[0], 1);
267 // deliver(1), generate (3):
268 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
269 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
270 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
271 check_added_monitors!(nodes[1], 1);
273 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
274 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
275 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
276 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
277 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
278 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
279 assert!(bs_update.update_fee.is_none()); // (4)
280 check_added_monitors!(nodes[1], 1);
282 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
283 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
284 assert!(as_update.update_add_htlcs.is_empty()); // (5)
285 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
286 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
287 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
288 assert!(as_update.update_fee.is_none()); // (5)
289 check_added_monitors!(nodes[0], 1);
291 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
292 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
293 // only (6) so get_event_msg's assert(len == 1) passes
294 check_added_monitors!(nodes[0], 1);
296 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
297 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
298 check_added_monitors!(nodes[1], 1);
300 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
301 check_added_monitors!(nodes[0], 1);
303 let events_2 = nodes[0].node.get_and_clear_pending_events();
304 assert_eq!(events_2.len(), 1);
306 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
307 _ => panic!("Unexpected event"),
310 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
311 check_added_monitors!(nodes[1], 1);
315 fn test_update_fee_unordered_raa() {
316 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
317 // crash in an earlier version of the update_fee patch)
318 let chanmon_cfgs = create_chanmon_cfgs(2);
319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
322 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
325 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
327 // First nodes[0] generates an update_fee
329 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
332 nodes[0].node.timer_tick_occurred();
333 check_added_monitors!(nodes[0], 1);
335 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336 assert_eq!(events_0.len(), 1);
337 let update_msg = match events_0[0] { // (1)
338 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
341 _ => panic!("Unexpected event"),
344 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
346 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
347 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
348 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
349 check_added_monitors!(nodes[1], 1);
351 let payment_event = {
352 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
353 assert_eq!(events_1.len(), 1);
354 SendEvent::from_event(events_1.remove(0))
356 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
357 assert_eq!(payment_event.msgs.len(), 1);
359 // ...now when the messages get delivered everyone should be happy
360 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
361 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
362 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
363 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
364 check_added_monitors!(nodes[0], 1);
366 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
367 check_added_monitors!(nodes[1], 1);
369 // We can't continue, sadly, because our (1) now has a bogus signature
373 fn test_multi_flight_update_fee() {
374 let chanmon_cfgs = create_chanmon_cfgs(2);
375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
378 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
381 // update_fee/commitment_signed ->
382 // .- send (1) RAA and (2) commitment_signed
383 // update_fee (never committed) ->
385 // We have to manually generate the above update_fee, it is allowed by the protocol but we
386 // don't track which updates correspond to which revoke_and_ack responses so we're in
387 // AwaitingRAA mode and will not generate the update_fee yet.
388 // <- (1) RAA delivered
389 // (3) is generated and send (4) CS -.
390 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
391 // know the per_commitment_point to use for it.
392 // <- (2) commitment_signed delivered
394 // B should send no response here
395 // (4) commitment_signed delivered ->
396 // <- RAA/commitment_signed delivered
399 // First nodes[0] generates an update_fee
402 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
403 initial_feerate = *feerate_lock;
404 *feerate_lock = initial_feerate + 20;
406 nodes[0].node.timer_tick_occurred();
407 check_added_monitors!(nodes[0], 1);
409 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
410 assert_eq!(events_0.len(), 1);
411 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
412 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
413 (update_fee.as_ref().unwrap(), commitment_signed)
415 _ => panic!("Unexpected event"),
418 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
419 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
420 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
421 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
422 check_added_monitors!(nodes[1], 1);
424 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
427 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
428 *feerate_lock = initial_feerate + 40;
430 nodes[0].node.timer_tick_occurred();
431 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
432 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
434 // Create the (3) update_fee message that nodes[0] will generate before it does...
435 let mut update_msg_2 = msgs::UpdateFee {
436 channel_id: update_msg_1.channel_id.clone(),
437 feerate_per_kw: (initial_feerate + 30) as u32,
440 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
442 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
444 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
446 // Deliver (1), generating (3) and (4)
447 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
448 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
449 check_added_monitors!(nodes[0], 1);
450 assert!(as_second_update.update_add_htlcs.is_empty());
451 assert!(as_second_update.update_fulfill_htlcs.is_empty());
452 assert!(as_second_update.update_fail_htlcs.is_empty());
453 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
454 // Check that the update_fee newly generated matches what we delivered:
455 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
456 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
458 // Deliver (2) commitment_signed
459 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
460 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 // No commitment_signed so get_event_msg's assert(len == 1) passes
464 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
465 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
466 check_added_monitors!(nodes[1], 1);
469 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
470 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
471 check_added_monitors!(nodes[1], 1);
473 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
474 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
475 check_added_monitors!(nodes[0], 1);
477 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
478 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479 // No commitment_signed so get_event_msg's assert(len == 1) passes
480 check_added_monitors!(nodes[0], 1);
482 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
483 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484 check_added_monitors!(nodes[1], 1);
487 fn do_test_sanity_on_in_flight_opens(steps: u8) {
488 // Previously, we had issues deserializing channels when we hadn't connected the first block
489 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
490 // serialization round-trips and simply do steps towards opening a channel and then drop the
493 let chanmon_cfgs = create_chanmon_cfgs(2);
494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
498 if steps & 0b1000_0000 != 0{
500 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
503 connect_block(&nodes[0], &block);
504 connect_block(&nodes[1], &block);
507 if steps & 0x0f == 0 { return; }
508 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
509 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
511 if steps & 0x0f == 1 { return; }
512 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
513 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
515 if steps & 0x0f == 2 { return; }
516 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
518 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
520 if steps & 0x0f == 3 { return; }
521 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
522 check_added_monitors!(nodes[0], 0);
523 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
525 if steps & 0x0f == 4 { return; }
526 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
528 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
529 assert_eq!(added_monitors.len(), 1);
530 assert_eq!(added_monitors[0].0, funding_output);
531 added_monitors.clear();
533 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
535 if steps & 0x0f == 5 { return; }
536 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
538 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
539 assert_eq!(added_monitors.len(), 1);
540 assert_eq!(added_monitors[0].0, funding_output);
541 added_monitors.clear();
544 let events_4 = nodes[0].node.get_and_clear_pending_events();
545 assert_eq!(events_4.len(), 0);
547 if steps & 0x0f == 6 { return; }
548 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
550 if steps & 0x0f == 7 { return; }
551 confirm_transaction_at(&nodes[0], &tx, 2);
552 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
553 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
557 fn test_sanity_on_in_flight_opens() {
558 do_test_sanity_on_in_flight_opens(0);
559 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
560 do_test_sanity_on_in_flight_opens(1);
561 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
562 do_test_sanity_on_in_flight_opens(2);
563 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
564 do_test_sanity_on_in_flight_opens(3);
565 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
566 do_test_sanity_on_in_flight_opens(4);
567 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
568 do_test_sanity_on_in_flight_opens(5);
569 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
570 do_test_sanity_on_in_flight_opens(6);
571 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
572 do_test_sanity_on_in_flight_opens(7);
573 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
574 do_test_sanity_on_in_flight_opens(8);
575 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
579 fn test_update_fee_vanilla() {
580 let chanmon_cfgs = create_chanmon_cfgs(2);
581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
584 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
587 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
590 nodes[0].node.timer_tick_occurred();
591 check_added_monitors!(nodes[0], 1);
593 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
594 assert_eq!(events_0.len(), 1);
595 let (update_msg, commitment_signed) = match events_0[0] {
596 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
597 (update_fee.as_ref(), commitment_signed)
599 _ => panic!("Unexpected event"),
601 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
604 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
605 check_added_monitors!(nodes[1], 1);
607 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
608 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
609 check_added_monitors!(nodes[0], 1);
611 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
612 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
613 // No commitment_signed so get_event_msg's assert(len == 1) passes
614 check_added_monitors!(nodes[0], 1);
616 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
617 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
618 check_added_monitors!(nodes[1], 1);
622 fn test_update_fee_that_funder_cannot_afford() {
623 let chanmon_cfgs = create_chanmon_cfgs(2);
624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627 let channel_value = 5000;
629 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
630 let channel_id = chan.2;
631 let secp_ctx = Secp256k1::new();
632 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
634 let opt_anchors = false;
636 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
637 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
638 // calculate two different feerates here - the expected local limit as well as the expected
640 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
641 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
643 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
644 *feerate_lock = feerate;
646 nodes[0].node.timer_tick_occurred();
647 check_added_monitors!(nodes[0], 1);
648 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
650 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
652 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
654 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
656 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
658 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
659 assert_eq!(commitment_tx.output.len(), 2);
660 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
661 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
662 actual_fee = channel_value - actual_fee;
663 assert_eq!(total_fee, actual_fee);
667 // Increment the feerate by a small constant, accounting for rounding errors
668 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
671 nodes[0].node.timer_tick_occurred();
672 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
673 check_added_monitors!(nodes[0], 0);
675 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
677 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
678 // needed to sign the new commitment tx and (2) sign the new commitment tx.
679 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
680 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
681 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
682 let chan_signer = local_chan.get_signer();
683 let pubkeys = chan_signer.pubkeys();
684 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
685 pubkeys.funding_pubkey)
687 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
688 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
689 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
690 let chan_signer = remote_chan.get_signer();
691 let pubkeys = chan_signer.pubkeys();
692 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
693 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
694 pubkeys.funding_pubkey)
697 // Assemble the set of keys we can use for signatures for our commitment_signed message.
698 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
699 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
702 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
703 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
704 let local_chan_signer = local_chan.get_signer();
705 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
706 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
707 INITIAL_COMMITMENT_NUMBER - 1,
709 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
710 opt_anchors, local_funding, remote_funding,
711 commit_tx_keys.clone(),
712 non_buffer_feerate + 4,
714 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
716 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
719 let commit_signed_msg = msgs::CommitmentSigned {
722 htlc_signatures: res.1
725 let update_fee = msgs::UpdateFee {
727 feerate_per_kw: non_buffer_feerate + 4,
730 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
732 //While producing the commitment_signed response after handling a received update_fee request the
733 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
734 //Should produce and error.
735 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
736 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
737 check_added_monitors!(nodes[1], 1);
738 check_closed_broadcast!(nodes[1], true);
739 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
743 fn test_update_fee_with_fundee_update_add_htlc() {
744 let chanmon_cfgs = create_chanmon_cfgs(2);
745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
747 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
748 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
751 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
754 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
757 nodes[0].node.timer_tick_occurred();
758 check_added_monitors!(nodes[0], 1);
760 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761 assert_eq!(events_0.len(), 1);
762 let (update_msg, commitment_signed) = match events_0[0] {
763 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
764 (update_fee.as_ref(), commitment_signed)
766 _ => panic!("Unexpected event"),
768 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
771 check_added_monitors!(nodes[1], 1);
773 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
775 // nothing happens since node[1] is in AwaitingRemoteRevoke
776 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
778 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
779 assert_eq!(added_monitors.len(), 0);
780 added_monitors.clear();
782 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
783 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784 // node[1] has nothing to do
786 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
787 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
788 check_added_monitors!(nodes[0], 1);
790 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
791 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792 // No commitment_signed so get_event_msg's assert(len == 1) passes
793 check_added_monitors!(nodes[0], 1);
794 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
795 check_added_monitors!(nodes[1], 1);
796 // AwaitingRemoteRevoke ends here
798 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
800 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
801 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
802 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
803 assert_eq!(commitment_update.update_fee.is_none(), true);
805 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
806 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
807 check_added_monitors!(nodes[0], 1);
808 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
810 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
811 check_added_monitors!(nodes[1], 1);
812 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
814 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
815 check_added_monitors!(nodes[1], 1);
816 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
817 // No commitment_signed so get_event_msg's assert(len == 1) passes
819 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
820 check_added_monitors!(nodes[0], 1);
821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
823 expect_pending_htlcs_forwardable!(nodes[0]);
825 let events = nodes[0].node.get_and_clear_pending_events();
826 assert_eq!(events.len(), 1);
828 Event::PaymentReceived { .. } => { },
829 _ => panic!("Unexpected event"),
832 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
834 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
835 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
836 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
837 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
838 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
842 fn test_update_fee() {
843 let chanmon_cfgs = create_chanmon_cfgs(2);
844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
847 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
848 let channel_id = chan.2;
851 // (1) update_fee/commitment_signed ->
852 // <- (2) revoke_and_ack
853 // .- send (3) commitment_signed
854 // (4) update_fee/commitment_signed ->
855 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
856 // <- (3) commitment_signed delivered
857 // send (6) revoke_and_ack -.
858 // <- (5) deliver revoke_and_ack
859 // (6) deliver revoke_and_ack ->
860 // .- send (7) commitment_signed in response to (4)
861 // <- (7) deliver commitment_signed
864 // Create and deliver (1)...
867 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
868 feerate = *feerate_lock;
869 *feerate_lock = feerate + 20;
871 nodes[0].node.timer_tick_occurred();
872 check_added_monitors!(nodes[0], 1);
874 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
875 assert_eq!(events_0.len(), 1);
876 let (update_msg, commitment_signed) = match events_0[0] {
877 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
878 (update_fee.as_ref(), commitment_signed)
880 _ => panic!("Unexpected event"),
882 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
884 // Generate (2) and (3):
885 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
886 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887 check_added_monitors!(nodes[1], 1);
890 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
892 check_added_monitors!(nodes[0], 1);
894 // Create and deliver (4)...
896 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
897 *feerate_lock = feerate + 30;
899 nodes[0].node.timer_tick_occurred();
900 check_added_monitors!(nodes[0], 1);
901 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
902 assert_eq!(events_0.len(), 1);
903 let (update_msg, commitment_signed) = match events_0[0] {
904 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
905 (update_fee.as_ref(), commitment_signed)
907 _ => panic!("Unexpected event"),
910 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
911 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912 check_added_monitors!(nodes[1], 1);
914 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
915 // No commitment_signed so get_event_msg's assert(len == 1) passes
917 // Handle (3), creating (6):
918 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
919 check_added_monitors!(nodes[0], 1);
920 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
921 // No commitment_signed so get_event_msg's assert(len == 1) passes
924 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
925 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
926 check_added_monitors!(nodes[0], 1);
928 // Deliver (6), creating (7):
929 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
930 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
931 assert!(commitment_update.update_add_htlcs.is_empty());
932 assert!(commitment_update.update_fulfill_htlcs.is_empty());
933 assert!(commitment_update.update_fail_htlcs.is_empty());
934 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
935 assert!(commitment_update.update_fee.is_none());
936 check_added_monitors!(nodes[1], 1);
939 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
940 check_added_monitors!(nodes[0], 1);
941 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
942 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
945 check_added_monitors!(nodes[1], 1);
946 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
948 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
949 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
950 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
951 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
952 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
956 fn fake_network_test() {
957 // Simple test which builds a network of ChannelManagers, connects them to each other, and
958 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
959 let chanmon_cfgs = create_chanmon_cfgs(4);
960 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
961 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
962 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
964 // Create some initial channels
965 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
966 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
967 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
969 // Rebalance the network a bit by relaying one payment through all the channels...
970 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
971 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
972 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
973 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
975 // Send some more payments
976 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
977 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
978 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
980 // Test failure packets
981 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
982 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
984 // Add a new channel that skips 3
985 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
987 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
988 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
989 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
990 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
991 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
992 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
993 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995 // Do some rebalance loop payments, simultaneously
996 let mut hops = Vec::with_capacity(3);
998 pubkey: nodes[2].node.get_our_node_id(),
999 node_features: NodeFeatures::empty(),
1000 short_channel_id: chan_2.0.contents.short_channel_id,
1001 channel_features: ChannelFeatures::empty(),
1003 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1005 hops.push(RouteHop {
1006 pubkey: nodes[3].node.get_our_node_id(),
1007 node_features: NodeFeatures::empty(),
1008 short_channel_id: chan_3.0.contents.short_channel_id,
1009 channel_features: ChannelFeatures::empty(),
1011 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1013 hops.push(RouteHop {
1014 pubkey: nodes[1].node.get_our_node_id(),
1015 node_features: NodeFeatures::known(),
1016 short_channel_id: chan_4.0.contents.short_channel_id,
1017 channel_features: ChannelFeatures::known(),
1019 cltv_expiry_delta: TEST_FINAL_CLTV,
1021 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1022 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1023 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1025 let mut hops = Vec::with_capacity(3);
1026 hops.push(RouteHop {
1027 pubkey: nodes[3].node.get_our_node_id(),
1028 node_features: NodeFeatures::empty(),
1029 short_channel_id: chan_4.0.contents.short_channel_id,
1030 channel_features: ChannelFeatures::empty(),
1032 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1034 hops.push(RouteHop {
1035 pubkey: nodes[2].node.get_our_node_id(),
1036 node_features: NodeFeatures::empty(),
1037 short_channel_id: chan_3.0.contents.short_channel_id,
1038 channel_features: ChannelFeatures::empty(),
1040 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1042 hops.push(RouteHop {
1043 pubkey: nodes[1].node.get_our_node_id(),
1044 node_features: NodeFeatures::known(),
1045 short_channel_id: chan_2.0.contents.short_channel_id,
1046 channel_features: ChannelFeatures::known(),
1048 cltv_expiry_delta: TEST_FINAL_CLTV,
1050 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1051 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1052 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1054 // Claim the rebalances...
1055 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1056 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1058 // Add a duplicate new channel from 2 to 4
1059 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1061 // Send some payments across both channels
1062 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1063 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1064 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1067 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1068 let events = nodes[0].node.get_and_clear_pending_msg_events();
1069 assert_eq!(events.len(), 0);
1070 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1072 //TODO: Test that routes work again here as we've been notified that the channel is full
1074 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1075 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1076 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1091 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1092 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1093 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1097 fn holding_cell_htlc_counting() {
1098 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100 // commitment dance rounds.
1101 let chanmon_cfgs = create_chanmon_cfgs(3);
1102 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1103 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1104 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1105 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1106 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1108 let mut payments = Vec::new();
1109 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1110 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1112 payments.push((payment_preimage, payment_hash));
1114 check_added_monitors!(nodes[1], 1);
1116 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1117 assert_eq!(events.len(), 1);
1118 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1119 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1121 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1122 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1124 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1126 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1127 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1136 check_added_monitors!(nodes[0], 1);
1139 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1140 assert_eq!(events.len(), 1);
1141 let payment_event = SendEvent::from_event(events.pop().unwrap());
1142 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1144 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1145 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1146 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1147 // fails), the second will process the resulting failure and fail the HTLC backward.
1148 expect_pending_htlcs_forwardable!(nodes[1]);
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 check_added_monitors!(nodes[1], 1);
1152 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1153 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1154 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1156 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1158 // Now forward all the pending HTLCs and claim them back
1159 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1160 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1161 check_added_monitors!(nodes[2], 1);
1163 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1164 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1165 check_added_monitors!(nodes[1], 1);
1166 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1168 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1169 check_added_monitors!(nodes[1], 1);
1170 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1172 for ref update in as_updates.update_add_htlcs.iter() {
1173 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1175 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1176 check_added_monitors!(nodes[2], 1);
1177 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1178 check_added_monitors!(nodes[2], 1);
1179 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1181 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1182 check_added_monitors!(nodes[1], 1);
1183 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1184 check_added_monitors!(nodes[1], 1);
1185 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1187 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1188 check_added_monitors!(nodes[2], 1);
1190 expect_pending_htlcs_forwardable!(nodes[2]);
1192 let events = nodes[2].node.get_and_clear_pending_events();
1193 assert_eq!(events.len(), payments.len());
1194 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1196 &Event::PaymentReceived { ref payment_hash, .. } => {
1197 assert_eq!(*payment_hash, *hash);
1199 _ => panic!("Unexpected event"),
1203 for (preimage, _) in payments.drain(..) {
1204 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1207 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1211 fn duplicate_htlc_test() {
1212 // Test that we accept duplicate payment_hash HTLCs across the network and that
1213 // claiming/failing them are all separate and don't affect each other
1214 let chanmon_cfgs = create_chanmon_cfgs(6);
1215 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1216 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1217 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1219 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1220 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1221 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1222 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1223 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1224 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1226 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1228 *nodes[0].network_payment_count.borrow_mut() -= 1;
1229 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1234 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1235 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1236 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1240 fn test_duplicate_htlc_different_direction_onchain() {
1241 // Test that ChannelMonitor doesn't generate 2 preimage txn
1242 // when we have 2 HTLCs with same preimage that go across a node
1243 // in opposite directions, even with the same payment secret.
1244 let chanmon_cfgs = create_chanmon_cfgs(2);
1245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1249 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1252 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1254 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1256 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1257 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1258 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1260 // Provide preimage to node 0 by claiming payment
1261 nodes[0].node.claim_funds(payment_preimage);
1262 check_added_monitors!(nodes[0], 1);
1264 // Broadcast node 1 commitment txn
1265 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1267 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1268 let mut has_both_htlcs = 0; // check htlcs match ones committed
1269 for outp in remote_txn[0].output.iter() {
1270 if outp.value == 800_000 / 1000 {
1271 has_both_htlcs += 1;
1272 } else if outp.value == 900_000 / 1000 {
1273 has_both_htlcs += 1;
1276 assert_eq!(has_both_htlcs, 2);
1278 mine_transaction(&nodes[0], &remote_txn[0]);
1279 check_added_monitors!(nodes[0], 1);
1280 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1281 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1283 // Check we only broadcast 1 timeout tx
1284 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1285 assert_eq!(claim_txn.len(), 8);
1286 assert_eq!(claim_txn[1], claim_txn[4]);
1287 assert_eq!(claim_txn[2], claim_txn[5]);
1288 check_spends!(claim_txn[1], chan_1.3);
1289 check_spends!(claim_txn[2], claim_txn[1]);
1290 check_spends!(claim_txn[7], claim_txn[1]);
1292 assert_eq!(claim_txn[0].input.len(), 1);
1293 assert_eq!(claim_txn[3].input.len(), 1);
1294 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1296 assert_eq!(claim_txn[0].input.len(), 1);
1297 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1298 check_spends!(claim_txn[0], remote_txn[0]);
1299 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1300 assert_eq!(claim_txn[6].input.len(), 1);
1301 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1302 check_spends!(claim_txn[6], remote_txn[0]);
1303 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1305 let events = nodes[0].node.get_and_clear_pending_msg_events();
1306 assert_eq!(events.len(), 3);
1309 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1310 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1311 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1312 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1314 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, .. } } => {
1315 assert!(update_add_htlcs.is_empty());
1316 assert!(update_fail_htlcs.is_empty());
1317 assert_eq!(update_fulfill_htlcs.len(), 1);
1318 assert!(update_fail_malformed_htlcs.is_empty());
1319 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1321 _ => panic!("Unexpected event"),
1327 fn test_basic_channel_reserve() {
1328 let chanmon_cfgs = create_chanmon_cfgs(2);
1329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1334 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1335 let channel_reserve = chan_stat.channel_reserve_msat;
1337 // The 2* and +1 are for the fee spike reserve.
1338 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1339 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1340 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1341 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1343 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1345 &APIError::ChannelUnavailable{ref err} =>
1346 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1347 _ => panic!("Unexpected error variant"),
1350 _ => panic!("Unexpected error variant"),
1352 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1353 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);
1355 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1359 fn test_fee_spike_violation_fails_htlc() {
1360 let chanmon_cfgs = create_chanmon_cfgs(2);
1361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1366 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1367 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1368 let secp_ctx = Secp256k1::new();
1369 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1371 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1373 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1374 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1375 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1376 let msg = msgs::UpdateAddHTLC {
1379 amount_msat: htlc_msat,
1380 payment_hash: payment_hash,
1381 cltv_expiry: htlc_cltv,
1382 onion_routing_packet: onion_packet,
1385 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1387 // Now manually create the commitment_signed message corresponding to the update_add
1388 // nodes[0] just sent. In the code for construction of this message, "local" refers
1389 // to the sender of the message, and "remote" refers to the receiver.
1391 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1393 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1395 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1396 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1397 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1398 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1399 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1400 let chan_signer = local_chan.get_signer();
1401 // Make the signer believe we validated another commitment, so we can release the secret
1402 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1404 let pubkeys = chan_signer.pubkeys();
1405 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1406 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1407 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1408 chan_signer.pubkeys().funding_pubkey)
1410 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1411 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1412 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1413 let chan_signer = remote_chan.get_signer();
1414 let pubkeys = chan_signer.pubkeys();
1415 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1416 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1417 chan_signer.pubkeys().funding_pubkey)
1420 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1421 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1422 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1424 // Build the remote commitment transaction so we can sign it, and then later use the
1425 // signature for the commitment_signed message.
1426 let local_chan_balance = 1313;
1428 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1430 amount_msat: 3460001,
1431 cltv_expiry: htlc_cltv,
1433 transaction_output_index: Some(1),
1436 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1439 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1440 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1441 let local_chan_signer = local_chan.get_signer();
1442 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1446 local_chan.opt_anchors(), local_funding, remote_funding,
1447 commit_tx_keys.clone(),
1449 &mut vec![(accepted_htlc_info, ())],
1450 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1452 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1455 let commit_signed_msg = msgs::CommitmentSigned {
1458 htlc_signatures: res.1
1461 // Send the commitment_signed message to the nodes[1].
1462 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1463 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1465 // Send the RAA to nodes[1].
1466 let raa_msg = msgs::RevokeAndACK {
1468 per_commitment_secret: local_secret,
1469 next_per_commitment_point: next_local_point
1471 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1473 let events = nodes[1].node.get_and_clear_pending_msg_events();
1474 assert_eq!(events.len(), 1);
1475 // Make sure the HTLC failed in the way we expect.
1477 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1478 assert_eq!(update_fail_htlcs.len(), 1);
1479 update_fail_htlcs[0].clone()
1481 _ => panic!("Unexpected event"),
1483 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1484 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1486 check_added_monitors!(nodes[1], 2);
1490 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1491 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1492 // Set the fee rate for the channel very high, to the point where the fundee
1493 // sending any above-dust amount would result in a channel reserve violation.
1494 // In this test we check that we would be prevented from sending an HTLC in
1496 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1499 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1501 let opt_anchors = false;
1503 let mut push_amt = 100_000_000;
1504 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1505 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1507 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1509 // Sending exactly enough to hit the reserve amount should be accepted
1510 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1511 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1514 // However one more HTLC should be significantly over the reserve amount and fail.
1515 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1516 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1517 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1518 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1519 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);
1523 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1524 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1528 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1530 let opt_anchors = false;
1532 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1533 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1534 // transaction fee with 0 HTLCs (183 sats)).
1535 let mut push_amt = 100_000_000;
1536 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1537 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1538 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1540 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1541 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1542 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1545 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1546 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1547 let secp_ctx = Secp256k1::new();
1548 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1549 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1550 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1551 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1552 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1553 let msg = msgs::UpdateAddHTLC {
1555 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1556 amount_msat: htlc_msat,
1557 payment_hash: payment_hash,
1558 cltv_expiry: htlc_cltv,
1559 onion_routing_packet: onion_packet,
1562 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1563 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1564 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);
1565 assert_eq!(nodes[0].node.list_channels().len(), 0);
1566 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1567 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1568 check_added_monitors!(nodes[0], 1);
1569 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() });
1573 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1574 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1575 // calculating our commitment transaction fee (this was previously broken).
1576 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1577 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1581 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1583 let opt_anchors = false;
1585 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1586 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1587 // transaction fee with 0 HTLCs (183 sats)).
1588 let mut push_amt = 100_000_000;
1589 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1590 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1591 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1593 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1594 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1595 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1596 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1597 // commitment transaction fee.
1598 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1600 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1601 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1602 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1605 // One more than the dust amt should fail, however.
1606 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1607 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1608 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1612 fn test_chan_init_feerate_unaffordability() {
1613 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1614 // channel reserve and feerate requirements.
1615 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1616 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1619 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1621 let opt_anchors = false;
1623 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1625 let mut push_amt = 100_000_000;
1626 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1627 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1628 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1630 // During open, we don't have a "counterparty channel reserve" to check against, so that
1631 // requirement only comes into play on the open_channel handling side.
1632 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1633 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1634 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1635 open_channel_msg.push_msat += 1;
1636 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1638 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1639 assert_eq!(msg_events.len(), 1);
1640 match msg_events[0] {
1641 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1642 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1644 _ => panic!("Unexpected event"),
1649 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1650 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1651 // calculating our counterparty's commitment transaction fee (this was previously broken).
1652 let chanmon_cfgs = create_chanmon_cfgs(2);
1653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1655 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1656 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1658 let payment_amt = 46000; // Dust amount
1659 // In the previous code, these first four payments would succeed.
1660 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1666 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1673 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1674 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1675 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1680 let chanmon_cfgs = create_chanmon_cfgs(3);
1681 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1682 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1683 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1684 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1685 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1688 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1689 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1690 let feerate = get_feerate!(nodes[0], chan.2);
1691 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1693 // Add a 2* and +1 for the fee spike reserve.
1694 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1695 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;
1696 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1698 // Add a pending HTLC.
1699 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1700 let payment_event_1 = {
1701 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1702 check_added_monitors!(nodes[0], 1);
1704 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1705 assert_eq!(events.len(), 1);
1706 SendEvent::from_event(events.remove(0))
1708 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1710 // Attempt to trigger a channel reserve violation --> payment failure.
1711 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1712 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;
1713 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1714 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1716 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1717 let secp_ctx = Secp256k1::new();
1718 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1719 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1720 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1721 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1722 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1723 let msg = msgs::UpdateAddHTLC {
1726 amount_msat: htlc_msat + 1,
1727 payment_hash: our_payment_hash_1,
1728 cltv_expiry: htlc_cltv,
1729 onion_routing_packet: onion_packet,
1732 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1733 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1734 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1735 assert_eq!(nodes[1].node.list_channels().len(), 1);
1736 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1737 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1738 check_added_monitors!(nodes[1], 1);
1739 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1743 fn test_inbound_outbound_capacity_is_not_zero() {
1744 let chanmon_cfgs = create_chanmon_cfgs(2);
1745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1748 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1749 let channels0 = node_chanmgrs[0].list_channels();
1750 let channels1 = node_chanmgrs[1].list_channels();
1751 assert_eq!(channels0.len(), 1);
1752 assert_eq!(channels1.len(), 1);
1754 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1755 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1756 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1758 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1759 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1762 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1763 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1767 fn test_channel_reserve_holding_cell_htlcs() {
1768 let chanmon_cfgs = create_chanmon_cfgs(3);
1769 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1770 // When this test was written, the default base fee floated based on the HTLC count.
1771 // It is now fixed, so we simply set the fee to the expected value here.
1772 let mut config = test_default_channel_config();
1773 config.channel_options.forwarding_fee_base_msat = 239;
1774 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1775 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1776 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1777 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1779 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1780 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1782 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1783 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1785 macro_rules! expect_forward {
1787 let mut events = $node.node.get_and_clear_pending_msg_events();
1788 assert_eq!(events.len(), 1);
1789 check_added_monitors!($node, 1);
1790 let payment_event = SendEvent::from_event(events.remove(0));
1795 let feemsat = 239; // set above
1796 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1797 let feerate = get_feerate!(nodes[0], chan_1.2);
1798 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1800 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1802 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1804 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1805 route.paths[0].last_mut().unwrap().fee_msat += 1;
1806 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1807 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1808 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)));
1809 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1810 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);
1813 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1814 // nodes[0]'s wealth
1816 let amt_msat = recv_value_0 + total_fee_msat;
1817 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1818 // Also, ensure that each payment has enough to be over the dust limit to
1819 // ensure it'll be included in each commit tx fee calculation.
1820 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1821 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1822 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1825 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1827 let (stat01_, stat11_, stat12_, stat22_) = (
1828 get_channel_value_stat!(nodes[0], chan_1.2),
1829 get_channel_value_stat!(nodes[1], chan_1.2),
1830 get_channel_value_stat!(nodes[1], chan_2.2),
1831 get_channel_value_stat!(nodes[2], chan_2.2),
1834 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1835 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1836 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1837 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1838 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1841 // adding pending output.
1842 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1843 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1844 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1845 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1846 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1847 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1848 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1849 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1850 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1852 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1853 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1854 let amt_msat_1 = recv_value_1 + total_fee_msat;
1856 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);
1857 let payment_event_1 = {
1858 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1859 check_added_monitors!(nodes[0], 1);
1861 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1862 assert_eq!(events.len(), 1);
1863 SendEvent::from_event(events.remove(0))
1865 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1867 // channel reserve test with htlc pending output > 0
1868 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1870 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1871 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1872 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1873 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1876 // split the rest to test holding cell
1877 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1878 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1879 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1880 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1882 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1883 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);
1886 // now see if they go through on both sides
1887 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);
1888 // but this will stuck in the holding cell
1889 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1890 check_added_monitors!(nodes[0], 0);
1891 let events = nodes[0].node.get_and_clear_pending_events();
1892 assert_eq!(events.len(), 0);
1894 // test with outbound holding cell amount > 0
1896 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1897 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1898 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1899 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1900 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);
1903 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);
1904 // this will also stuck in the holding cell
1905 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1906 check_added_monitors!(nodes[0], 0);
1907 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1908 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910 // flush the pending htlc
1911 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1912 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1913 check_added_monitors!(nodes[1], 1);
1915 // the pending htlc should be promoted to committed
1916 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1917 check_added_monitors!(nodes[0], 1);
1918 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1920 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1921 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1922 // No commitment_signed so get_event_msg's assert(len == 1) passes
1923 check_added_monitors!(nodes[0], 1);
1925 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1926 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1927 check_added_monitors!(nodes[1], 1);
1929 expect_pending_htlcs_forwardable!(nodes[1]);
1931 let ref payment_event_11 = expect_forward!(nodes[1]);
1932 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1933 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1935 expect_pending_htlcs_forwardable!(nodes[2]);
1936 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1938 // flush the htlcs in the holding cell
1939 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1940 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1942 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1943 expect_pending_htlcs_forwardable!(nodes[1]);
1945 let ref payment_event_3 = expect_forward!(nodes[1]);
1946 assert_eq!(payment_event_3.msgs.len(), 2);
1947 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1948 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1950 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1951 expect_pending_htlcs_forwardable!(nodes[2]);
1953 let events = nodes[2].node.get_and_clear_pending_events();
1954 assert_eq!(events.len(), 2);
1956 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1957 assert_eq!(our_payment_hash_21, *payment_hash);
1958 assert_eq!(recv_value_21, amt);
1960 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1961 assert!(payment_preimage.is_none());
1962 assert_eq!(our_payment_secret_21, *payment_secret);
1964 _ => panic!("expected PaymentPurpose::InvoicePayment")
1967 _ => panic!("Unexpected event"),
1970 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1971 assert_eq!(our_payment_hash_22, *payment_hash);
1972 assert_eq!(recv_value_22, amt);
1974 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1975 assert!(payment_preimage.is_none());
1976 assert_eq!(our_payment_secret_22, *payment_secret);
1978 _ => panic!("expected PaymentPurpose::InvoicePayment")
1981 _ => panic!("Unexpected event"),
1984 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1985 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1986 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1988 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1989 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1990 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1992 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1993 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);
1994 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1995 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1996 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1998 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1999 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2003 fn channel_reserve_in_flight_removes() {
2004 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2005 // can send to its counterparty, but due to update ordering, the other side may not yet have
2006 // considered those HTLCs fully removed.
2007 // This tests that we don't count HTLCs which will not be included in the next remote
2008 // commitment transaction towards the reserve value (as it implies no commitment transaction
2009 // will be generated which violates the remote reserve value).
2010 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2012 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2013 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2014 // you only consider the value of the first HTLC, it may not),
2015 // * start routing a third HTLC from A to B,
2016 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2017 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2018 // * deliver the first fulfill from B
2019 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2021 // * deliver A's response CS and RAA.
2022 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2023 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2024 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2025 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2026 let chanmon_cfgs = create_chanmon_cfgs(2);
2027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2029 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2030 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2032 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2033 // Route the first two HTLCs.
2034 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2035 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2037 // Start routing the third HTLC (this is just used to get everyone in the right state).
2038 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2040 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2041 check_added_monitors!(nodes[0], 1);
2042 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2043 assert_eq!(events.len(), 1);
2044 SendEvent::from_event(events.remove(0))
2047 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2048 // initial fulfill/CS.
2049 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2050 check_added_monitors!(nodes[1], 1);
2051 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2053 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2054 // remove the second HTLC when we send the HTLC back from B to A.
2055 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2056 check_added_monitors!(nodes[1], 1);
2057 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2059 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2060 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2061 check_added_monitors!(nodes[0], 1);
2062 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2063 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2065 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2066 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2067 check_added_monitors!(nodes[1], 1);
2068 // B is already AwaitingRAA, so cant generate a CS here
2069 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2071 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2072 check_added_monitors!(nodes[1], 1);
2073 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2075 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2076 check_added_monitors!(nodes[0], 1);
2077 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2079 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2080 check_added_monitors!(nodes[1], 1);
2081 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2083 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2084 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2085 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2086 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2087 // on-chain as necessary).
2088 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2089 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2090 check_added_monitors!(nodes[0], 1);
2091 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2092 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
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 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2098 expect_pending_htlcs_forwardable!(nodes[1]);
2099 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2101 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2102 // resolve the second HTLC from A's point of view.
2103 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2104 check_added_monitors!(nodes[0], 1);
2105 expect_payment_path_successful!(nodes[0]);
2106 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2108 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2109 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2110 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2112 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2113 check_added_monitors!(nodes[1], 1);
2114 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2115 assert_eq!(events.len(), 1);
2116 SendEvent::from_event(events.remove(0))
2119 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2120 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2121 check_added_monitors!(nodes[0], 1);
2122 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2124 // Now just resolve all the outstanding messages/HTLCs for completeness...
2126 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2127 check_added_monitors!(nodes[1], 1);
2128 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2130 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2131 check_added_monitors!(nodes[1], 1);
2133 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2134 check_added_monitors!(nodes[0], 1);
2135 expect_payment_path_successful!(nodes[0]);
2136 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2138 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2139 check_added_monitors!(nodes[1], 1);
2140 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2142 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2143 check_added_monitors!(nodes[0], 1);
2145 expect_pending_htlcs_forwardable!(nodes[0]);
2146 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2148 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2149 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2153 fn channel_monitor_network_test() {
2154 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2155 // tests that ChannelMonitor is able to recover from various states.
2156 let chanmon_cfgs = create_chanmon_cfgs(5);
2157 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2158 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2159 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2161 // Create some initial channels
2162 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2163 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2164 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2165 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2167 // Make sure all nodes are at the same starting height
2168 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2169 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2170 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2171 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2172 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2174 // Rebalance the network a bit by relaying one payment through all the channels...
2175 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2176 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2177 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2178 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2180 // Simple case with no pending HTLCs:
2181 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2182 check_added_monitors!(nodes[1], 1);
2183 check_closed_broadcast!(nodes[1], false);
2185 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2186 assert_eq!(node_txn.len(), 1);
2187 mine_transaction(&nodes[0], &node_txn[0]);
2188 check_added_monitors!(nodes[0], 1);
2189 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2191 check_closed_broadcast!(nodes[0], true);
2192 assert_eq!(nodes[0].node.list_channels().len(), 0);
2193 assert_eq!(nodes[1].node.list_channels().len(), 1);
2194 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2195 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2197 // One pending HTLC is discarded by the force-close:
2198 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2200 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2201 // broadcasted until we reach the timelock time).
2202 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2203 check_closed_broadcast!(nodes[1], false);
2204 check_added_monitors!(nodes[1], 1);
2206 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2207 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2208 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2209 mine_transaction(&nodes[2], &node_txn[0]);
2210 check_added_monitors!(nodes[2], 1);
2211 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2213 check_closed_broadcast!(nodes[2], true);
2214 assert_eq!(nodes[1].node.list_channels().len(), 0);
2215 assert_eq!(nodes[2].node.list_channels().len(), 1);
2216 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2217 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2219 macro_rules! claim_funds {
2220 ($node: expr, $prev_node: expr, $preimage: expr) => {
2222 assert!($node.node.claim_funds($preimage));
2223 check_added_monitors!($node, 1);
2225 let events = $node.node.get_and_clear_pending_msg_events();
2226 assert_eq!(events.len(), 1);
2228 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2229 assert!(update_add_htlcs.is_empty());
2230 assert!(update_fail_htlcs.is_empty());
2231 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2233 _ => panic!("Unexpected event"),
2239 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2240 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2241 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2242 check_added_monitors!(nodes[2], 1);
2243 check_closed_broadcast!(nodes[2], false);
2244 let node2_commitment_txid;
2246 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2247 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2248 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2249 node2_commitment_txid = node_txn[0].txid();
2251 // Claim the payment on nodes[3], giving it knowledge of the preimage
2252 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2253 mine_transaction(&nodes[3], &node_txn[0]);
2254 check_added_monitors!(nodes[3], 1);
2255 check_preimage_claim(&nodes[3], &node_txn);
2257 check_closed_broadcast!(nodes[3], true);
2258 assert_eq!(nodes[2].node.list_channels().len(), 0);
2259 assert_eq!(nodes[3].node.list_channels().len(), 1);
2260 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2261 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2263 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2264 // confusing us in the following tests.
2265 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2267 // One pending HTLC to time out:
2268 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2269 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2272 let (close_chan_update_1, close_chan_update_2) = {
2273 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2274 let events = nodes[3].node.get_and_clear_pending_msg_events();
2275 assert_eq!(events.len(), 2);
2276 let close_chan_update_1 = match events[0] {
2277 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2280 _ => panic!("Unexpected event"),
2283 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2284 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2286 _ => panic!("Unexpected event"),
2288 check_added_monitors!(nodes[3], 1);
2290 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2292 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2293 node_txn.retain(|tx| {
2294 if tx.input[0].previous_output.txid == node2_commitment_txid {
2300 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2302 // Claim the payment on nodes[4], giving it knowledge of the preimage
2303 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2305 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2306 let events = nodes[4].node.get_and_clear_pending_msg_events();
2307 assert_eq!(events.len(), 2);
2308 let close_chan_update_2 = match events[0] {
2309 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2312 _ => panic!("Unexpected event"),
2315 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2316 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2318 _ => panic!("Unexpected event"),
2320 check_added_monitors!(nodes[4], 1);
2321 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2323 mine_transaction(&nodes[4], &node_txn[0]);
2324 check_preimage_claim(&nodes[4], &node_txn);
2325 (close_chan_update_1, close_chan_update_2)
2327 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2328 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2329 assert_eq!(nodes[3].node.list_channels().len(), 0);
2330 assert_eq!(nodes[4].node.list_channels().len(), 0);
2332 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2333 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2334 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2338 fn test_justice_tx() {
2339 // Test justice txn built on revoked HTLC-Success tx, against both sides
2340 let mut alice_config = UserConfig::default();
2341 alice_config.channel_options.announced_channel = true;
2342 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2343 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2344 let mut bob_config = UserConfig::default();
2345 bob_config.channel_options.announced_channel = true;
2346 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2347 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2348 let user_cfgs = [Some(alice_config), Some(bob_config)];
2349 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2350 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2351 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2352 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2353 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2354 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2355 // Create some new channels:
2356 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2358 // A pending HTLC which will be revoked:
2359 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2360 // Get the will-be-revoked local txn from nodes[0]
2361 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2362 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2363 assert_eq!(revoked_local_txn[0].input.len(), 1);
2364 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2365 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2366 assert_eq!(revoked_local_txn[1].input.len(), 1);
2367 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2368 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2369 // Revoke the old state
2370 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2373 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2375 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2376 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2377 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2379 check_spends!(node_txn[0], revoked_local_txn[0]);
2380 node_txn.swap_remove(0);
2381 node_txn.truncate(1);
2383 check_added_monitors!(nodes[1], 1);
2384 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2385 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2387 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2388 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2389 // Verify broadcast of revoked HTLC-timeout
2390 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2391 check_added_monitors!(nodes[0], 1);
2392 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2393 // Broadcast revoked HTLC-timeout on node 1
2394 mine_transaction(&nodes[1], &node_txn[1]);
2395 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2397 get_announce_close_broadcast_events(&nodes, 0, 1);
2399 assert_eq!(nodes[0].node.list_channels().len(), 0);
2400 assert_eq!(nodes[1].node.list_channels().len(), 0);
2402 // We test justice_tx build by A on B's revoked HTLC-Success tx
2403 // Create some new channels:
2404 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2406 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2410 // A pending HTLC which will be revoked:
2411 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2412 // Get the will-be-revoked local txn from B
2413 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2414 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2415 assert_eq!(revoked_local_txn[0].input.len(), 1);
2416 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2417 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2418 // Revoke the old state
2419 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2421 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2423 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2424 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2425 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2427 check_spends!(node_txn[0], revoked_local_txn[0]);
2428 node_txn.swap_remove(0);
2430 check_added_monitors!(nodes[0], 1);
2431 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2433 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2434 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2435 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2436 check_added_monitors!(nodes[1], 1);
2437 mine_transaction(&nodes[0], &node_txn[1]);
2438 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2439 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2441 get_announce_close_broadcast_events(&nodes, 0, 1);
2442 assert_eq!(nodes[0].node.list_channels().len(), 0);
2443 assert_eq!(nodes[1].node.list_channels().len(), 0);
2447 fn revoked_output_claim() {
2448 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2449 // transaction is broadcast by its counterparty
2450 let chanmon_cfgs = create_chanmon_cfgs(2);
2451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2453 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2454 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2455 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2456 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2457 assert_eq!(revoked_local_txn.len(), 1);
2458 // Only output is the full channel value back to nodes[0]:
2459 assert_eq!(revoked_local_txn[0].output.len(), 1);
2460 // Send a payment through, updating everyone's latest commitment txn
2461 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2463 // Inform nodes[1] that nodes[0] broadcast a stale tx
2464 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2465 check_added_monitors!(nodes[1], 1);
2466 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2467 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2468 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2470 check_spends!(node_txn[0], revoked_local_txn[0]);
2471 check_spends!(node_txn[1], chan_1.3);
2473 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2474 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2475 get_announce_close_broadcast_events(&nodes, 0, 1);
2476 check_added_monitors!(nodes[0], 1);
2477 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2481 fn claim_htlc_outputs_shared_tx() {
2482 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2483 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2484 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2487 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2489 // Create some new channel:
2490 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2492 // Rebalance the network to generate htlc in the two directions
2493 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2494 // 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
2495 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2496 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2498 // Get the will-be-revoked local txn from node[0]
2499 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2500 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2501 assert_eq!(revoked_local_txn[0].input.len(), 1);
2502 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2503 assert_eq!(revoked_local_txn[1].input.len(), 1);
2504 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2505 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2506 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2508 //Revoke the old state
2509 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2512 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2513 check_added_monitors!(nodes[0], 1);
2514 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2515 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2516 check_added_monitors!(nodes[1], 1);
2517 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2518 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2519 expect_payment_failed!(nodes[1], payment_hash_2, true);
2521 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2522 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2524 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2525 check_spends!(node_txn[0], revoked_local_txn[0]);
2527 let mut witness_lens = BTreeSet::new();
2528 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2529 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2530 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2531 assert_eq!(witness_lens.len(), 3);
2532 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2533 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2534 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2536 // Next nodes[1] broadcasts its current local tx state:
2537 assert_eq!(node_txn[1].input.len(), 1);
2538 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2540 get_announce_close_broadcast_events(&nodes, 0, 1);
2541 assert_eq!(nodes[0].node.list_channels().len(), 0);
2542 assert_eq!(nodes[1].node.list_channels().len(), 0);
2546 fn claim_htlc_outputs_single_tx() {
2547 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2548 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2549 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2552 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2554 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2556 // Rebalance the network to generate htlc in the two directions
2557 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2558 // 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
2559 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2560 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2561 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2563 // Get the will-be-revoked local txn from node[0]
2564 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2566 //Revoke the old state
2567 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2570 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2571 check_added_monitors!(nodes[0], 1);
2572 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2573 check_added_monitors!(nodes[1], 1);
2574 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2575 let mut events = nodes[0].node.get_and_clear_pending_events();
2576 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2578 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2579 _ => panic!("Unexpected event"),
2582 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2583 expect_payment_failed!(nodes[1], payment_hash_2, true);
2585 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2586 assert_eq!(node_txn.len(), 9);
2587 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2588 // ChannelManager: local commmitment + local HTLC-timeout (2)
2589 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2590 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2592 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2593 assert_eq!(node_txn[0].input.len(), 1);
2594 check_spends!(node_txn[0], chan_1.3);
2595 assert_eq!(node_txn[1].input.len(), 1);
2596 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2597 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2598 check_spends!(node_txn[1], node_txn[0]);
2600 // Justice transactions are indices 1-2-4
2601 assert_eq!(node_txn[2].input.len(), 1);
2602 assert_eq!(node_txn[3].input.len(), 1);
2603 assert_eq!(node_txn[4].input.len(), 1);
2605 check_spends!(node_txn[2], revoked_local_txn[0]);
2606 check_spends!(node_txn[3], revoked_local_txn[0]);
2607 check_spends!(node_txn[4], revoked_local_txn[0]);
2609 let mut witness_lens = BTreeSet::new();
2610 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2611 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2612 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2613 assert_eq!(witness_lens.len(), 3);
2614 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2615 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2616 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2618 get_announce_close_broadcast_events(&nodes, 0, 1);
2619 assert_eq!(nodes[0].node.list_channels().len(), 0);
2620 assert_eq!(nodes[1].node.list_channels().len(), 0);
2624 fn test_htlc_on_chain_success() {
2625 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2626 // the preimage backward accordingly. So here we test that ChannelManager is
2627 // broadcasting the right event to other nodes in payment path.
2628 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2629 // A --------------------> B ----------------------> C (preimage)
2630 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2631 // commitment transaction was broadcast.
2632 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2634 // B should be able to claim via preimage if A then broadcasts its local tx.
2635 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2636 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2637 // PaymentSent event).
2639 let chanmon_cfgs = create_chanmon_cfgs(3);
2640 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2641 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2642 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2644 // Create some initial channels
2645 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2646 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2648 // Ensure all nodes are at the same height
2649 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2650 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2651 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2652 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2654 // Rebalance the network a bit by relaying one payment through all the channels...
2655 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2656 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2658 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2659 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2661 // Broadcast legit commitment tx from C on B's chain
2662 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2663 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2664 assert_eq!(commitment_tx.len(), 1);
2665 check_spends!(commitment_tx[0], chan_2.3);
2666 nodes[2].node.claim_funds(our_payment_preimage);
2667 nodes[2].node.claim_funds(our_payment_preimage_2);
2668 check_added_monitors!(nodes[2], 2);
2669 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2670 assert!(updates.update_add_htlcs.is_empty());
2671 assert!(updates.update_fail_htlcs.is_empty());
2672 assert!(updates.update_fail_malformed_htlcs.is_empty());
2673 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2675 mine_transaction(&nodes[2], &commitment_tx[0]);
2676 check_closed_broadcast!(nodes[2], true);
2677 check_added_monitors!(nodes[2], 1);
2678 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2679 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)
2680 assert_eq!(node_txn.len(), 5);
2681 assert_eq!(node_txn[0], node_txn[3]);
2682 assert_eq!(node_txn[1], node_txn[4]);
2683 assert_eq!(node_txn[2], commitment_tx[0]);
2684 check_spends!(node_txn[0], commitment_tx[0]);
2685 check_spends!(node_txn[1], commitment_tx[0]);
2686 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2687 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2688 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2689 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2690 assert_eq!(node_txn[0].lock_time, 0);
2691 assert_eq!(node_txn[1].lock_time, 0);
2693 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2694 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2695 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2696 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2698 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2699 assert_eq!(added_monitors.len(), 1);
2700 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2701 added_monitors.clear();
2703 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2704 assert_eq!(forwarded_events.len(), 3);
2705 match forwarded_events[0] {
2706 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2707 _ => panic!("Unexpected event"),
2709 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2710 } else { panic!(); }
2711 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2712 } else { panic!(); }
2713 let events = nodes[1].node.get_and_clear_pending_msg_events();
2715 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2716 assert_eq!(added_monitors.len(), 2);
2717 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2718 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2719 added_monitors.clear();
2721 assert_eq!(events.len(), 3);
2723 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2724 _ => panic!("Unexpected event"),
2727 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2728 _ => panic!("Unexpected event"),
2732 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, .. } } => {
2733 assert!(update_add_htlcs.is_empty());
2734 assert!(update_fail_htlcs.is_empty());
2735 assert_eq!(update_fulfill_htlcs.len(), 1);
2736 assert!(update_fail_malformed_htlcs.is_empty());
2737 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2739 _ => panic!("Unexpected event"),
2741 macro_rules! check_tx_local_broadcast {
2742 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2743 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2744 assert_eq!(node_txn.len(), 3);
2745 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2746 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2747 check_spends!(node_txn[1], $commitment_tx);
2748 check_spends!(node_txn[2], $commitment_tx);
2749 assert_ne!(node_txn[1].lock_time, 0);
2750 assert_ne!(node_txn[2].lock_time, 0);
2752 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2753 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2754 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2755 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2757 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2758 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2759 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2760 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2762 check_spends!(node_txn[0], $chan_tx);
2763 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2767 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2768 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2769 // timeout-claim of the output that nodes[2] just claimed via success.
2770 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2772 // Broadcast legit commitment tx from A on B's chain
2773 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2774 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2775 check_spends!(node_a_commitment_tx[0], chan_1.3);
2776 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2777 check_closed_broadcast!(nodes[1], true);
2778 check_added_monitors!(nodes[1], 1);
2779 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2780 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2781 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2782 let commitment_spend =
2783 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2784 check_spends!(node_txn[1], commitment_tx[0]);
2785 check_spends!(node_txn[2], commitment_tx[0]);
2786 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2789 check_spends!(node_txn[0], commitment_tx[0]);
2790 check_spends!(node_txn[1], commitment_tx[0]);
2791 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2795 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2796 assert_eq!(commitment_spend.input.len(), 2);
2797 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2798 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2799 assert_eq!(commitment_spend.lock_time, 0);
2800 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2801 check_spends!(node_txn[3], chan_1.3);
2802 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2803 check_spends!(node_txn[4], node_txn[3]);
2804 check_spends!(node_txn[5], node_txn[3]);
2805 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2806 // we already checked the same situation with A.
2808 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2809 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2810 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2811 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2812 check_closed_broadcast!(nodes[0], true);
2813 check_added_monitors!(nodes[0], 1);
2814 let events = nodes[0].node.get_and_clear_pending_events();
2815 assert_eq!(events.len(), 5);
2816 let mut first_claimed = false;
2817 for event in events {
2819 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2820 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2821 assert!(!first_claimed);
2822 first_claimed = true;
2824 assert_eq!(payment_preimage, our_payment_preimage_2);
2825 assert_eq!(payment_hash, payment_hash_2);
2828 Event::PaymentPathSuccessful { .. } => {},
2829 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2830 _ => panic!("Unexpected event"),
2833 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2836 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2837 // Test that in case of a unilateral close onchain, we detect the state of output and
2838 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2839 // broadcasting the right event to other nodes in payment path.
2840 // A ------------------> B ----------------------> C (timeout)
2841 // B's commitment tx C's commitment tx
2843 // B's HTLC timeout tx B's timeout tx
2845 let chanmon_cfgs = create_chanmon_cfgs(3);
2846 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2847 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2848 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2849 *nodes[0].connect_style.borrow_mut() = connect_style;
2850 *nodes[1].connect_style.borrow_mut() = connect_style;
2851 *nodes[2].connect_style.borrow_mut() = connect_style;
2853 // Create some intial channels
2854 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2855 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2857 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2858 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2859 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2861 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2863 // Broadcast legit commitment tx from C on B's chain
2864 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2865 check_spends!(commitment_tx[0], chan_2.3);
2866 nodes[2].node.fail_htlc_backwards(&payment_hash);
2867 check_added_monitors!(nodes[2], 0);
2868 expect_pending_htlcs_forwardable!(nodes[2]);
2869 check_added_monitors!(nodes[2], 1);
2871 let events = nodes[2].node.get_and_clear_pending_msg_events();
2872 assert_eq!(events.len(), 1);
2874 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, .. } } => {
2875 assert!(update_add_htlcs.is_empty());
2876 assert!(!update_fail_htlcs.is_empty());
2877 assert!(update_fulfill_htlcs.is_empty());
2878 assert!(update_fail_malformed_htlcs.is_empty());
2879 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2881 _ => panic!("Unexpected event"),
2883 mine_transaction(&nodes[2], &commitment_tx[0]);
2884 check_closed_broadcast!(nodes[2], true);
2885 check_added_monitors!(nodes[2], 1);
2886 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2887 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2888 assert_eq!(node_txn.len(), 1);
2889 check_spends!(node_txn[0], chan_2.3);
2890 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2892 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2893 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2894 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2895 mine_transaction(&nodes[1], &commitment_tx[0]);
2896 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2899 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2900 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2901 assert_eq!(node_txn[0], node_txn[3]);
2902 assert_eq!(node_txn[1], node_txn[4]);
2904 check_spends!(node_txn[2], commitment_tx[0]);
2905 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2907 check_spends!(node_txn[0], chan_2.3);
2908 check_spends!(node_txn[1], node_txn[0]);
2909 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2910 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2912 timeout_tx = node_txn[2].clone();
2916 mine_transaction(&nodes[1], &timeout_tx);
2917 check_added_monitors!(nodes[1], 1);
2918 check_closed_broadcast!(nodes[1], true);
2920 // B will rebroadcast a fee-bumped timeout transaction here.
2921 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2922 assert_eq!(node_txn.len(), 1);
2923 check_spends!(node_txn[0], commitment_tx[0]);
2926 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2928 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2929 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2930 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2931 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2932 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2933 if node_txn.len() == 1 {
2934 check_spends!(node_txn[0], chan_2.3);
2936 assert_eq!(node_txn.len(), 0);
2940 expect_pending_htlcs_forwardable!(nodes[1]);
2941 check_added_monitors!(nodes[1], 1);
2942 let events = nodes[1].node.get_and_clear_pending_msg_events();
2943 assert_eq!(events.len(), 1);
2945 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, .. } } => {
2946 assert!(update_add_htlcs.is_empty());
2947 assert!(!update_fail_htlcs.is_empty());
2948 assert!(update_fulfill_htlcs.is_empty());
2949 assert!(update_fail_malformed_htlcs.is_empty());
2950 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2952 _ => panic!("Unexpected event"),
2955 // Broadcast legit commitment tx from B on A's chain
2956 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2957 check_spends!(commitment_tx[0], chan_1.3);
2959 mine_transaction(&nodes[0], &commitment_tx[0]);
2960 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2962 check_closed_broadcast!(nodes[0], true);
2963 check_added_monitors!(nodes[0], 1);
2964 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2965 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2966 assert_eq!(node_txn.len(), 2);
2967 check_spends!(node_txn[0], chan_1.3);
2968 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2969 check_spends!(node_txn[1], commitment_tx[0]);
2970 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2974 fn test_htlc_on_chain_timeout() {
2975 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2976 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2977 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2981 fn test_simple_commitment_revoked_fail_backward() {
2982 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2983 // and fail backward accordingly.
2985 let chanmon_cfgs = create_chanmon_cfgs(3);
2986 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2987 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2988 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2990 // Create some initial channels
2991 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2992 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2994 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2995 // Get the will-be-revoked local txn from nodes[2]
2996 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2997 // Revoke the old state
2998 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3000 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3002 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3003 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3004 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3005 check_added_monitors!(nodes[1], 1);
3006 check_closed_broadcast!(nodes[1], true);
3008 expect_pending_htlcs_forwardable!(nodes[1]);
3009 check_added_monitors!(nodes[1], 1);
3010 let events = nodes[1].node.get_and_clear_pending_msg_events();
3011 assert_eq!(events.len(), 1);
3013 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, .. } } => {
3014 assert!(update_add_htlcs.is_empty());
3015 assert_eq!(update_fail_htlcs.len(), 1);
3016 assert!(update_fulfill_htlcs.is_empty());
3017 assert!(update_fail_malformed_htlcs.is_empty());
3018 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3020 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3021 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3022 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3024 _ => panic!("Unexpected event"),
3028 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3029 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3030 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3031 // commitment transaction anymore.
3032 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3033 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3034 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3035 // technically disallowed and we should probably handle it reasonably.
3036 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3037 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3039 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3040 // commitment_signed (implying it will be in the latest remote commitment transaction).
3041 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3042 // and once they revoke the previous commitment transaction (allowing us to send a new
3043 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3044 let chanmon_cfgs = create_chanmon_cfgs(3);
3045 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3046 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3047 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3049 // Create some initial channels
3050 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3051 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3053 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 });
3054 // Get the will-be-revoked local txn from nodes[2]
3055 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3056 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3057 // Revoke the old state
3058 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3060 let value = if use_dust {
3061 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3062 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3063 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3066 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3067 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3068 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3070 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3071 expect_pending_htlcs_forwardable!(nodes[2]);
3072 check_added_monitors!(nodes[2], 1);
3073 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3074 assert!(updates.update_add_htlcs.is_empty());
3075 assert!(updates.update_fulfill_htlcs.is_empty());
3076 assert!(updates.update_fail_malformed_htlcs.is_empty());
3077 assert_eq!(updates.update_fail_htlcs.len(), 1);
3078 assert!(updates.update_fee.is_none());
3079 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3080 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3081 // Drop the last RAA from 3 -> 2
3083 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3084 expect_pending_htlcs_forwardable!(nodes[2]);
3085 check_added_monitors!(nodes[2], 1);
3086 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3087 assert!(updates.update_add_htlcs.is_empty());
3088 assert!(updates.update_fulfill_htlcs.is_empty());
3089 assert!(updates.update_fail_malformed_htlcs.is_empty());
3090 assert_eq!(updates.update_fail_htlcs.len(), 1);
3091 assert!(updates.update_fee.is_none());
3092 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3093 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3094 check_added_monitors!(nodes[1], 1);
3095 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3096 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3097 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3098 check_added_monitors!(nodes[2], 1);
3100 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3101 expect_pending_htlcs_forwardable!(nodes[2]);
3102 check_added_monitors!(nodes[2], 1);
3103 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3104 assert!(updates.update_add_htlcs.is_empty());
3105 assert!(updates.update_fulfill_htlcs.is_empty());
3106 assert!(updates.update_fail_malformed_htlcs.is_empty());
3107 assert_eq!(updates.update_fail_htlcs.len(), 1);
3108 assert!(updates.update_fee.is_none());
3109 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3110 // At this point first_payment_hash has dropped out of the latest two commitment
3111 // transactions that nodes[1] is tracking...
3112 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3113 check_added_monitors!(nodes[1], 1);
3114 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3115 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3116 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3117 check_added_monitors!(nodes[2], 1);
3119 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3120 // on nodes[2]'s RAA.
3121 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3122 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3123 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3124 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3125 check_added_monitors!(nodes[1], 0);
3128 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3129 // One monitor for the new revocation preimage, no second on as we won't generate a new
3130 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3131 check_added_monitors!(nodes[1], 1);
3132 let events = nodes[1].node.get_and_clear_pending_events();
3133 assert_eq!(events.len(), 1);
3135 Event::PendingHTLCsForwardable { .. } => { },
3136 _ => panic!("Unexpected event"),
3138 // Deliberately don't process the pending fail-back so they all fail back at once after
3139 // block connection just like the !deliver_bs_raa case
3142 let mut failed_htlcs = HashSet::new();
3143 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3145 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3146 check_added_monitors!(nodes[1], 1);
3147 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3148 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3150 let events = nodes[1].node.get_and_clear_pending_events();
3151 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3153 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3154 _ => panic!("Unexepected event"),
3157 Event::PaymentPathFailed { ref payment_hash, .. } => {
3158 assert_eq!(*payment_hash, fourth_payment_hash);
3160 _ => panic!("Unexpected event"),
3162 if !deliver_bs_raa {
3164 Event::PaymentFailed { ref payment_hash, .. } => {
3165 assert_eq!(*payment_hash, fourth_payment_hash);
3167 _ => panic!("Unexpected event"),
3170 Event::PendingHTLCsForwardable { .. } => { },
3171 _ => panic!("Unexpected event"),
3174 nodes[1].node.process_pending_htlc_forwards();
3175 check_added_monitors!(nodes[1], 1);
3177 let events = nodes[1].node.get_and_clear_pending_msg_events();
3178 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3179 match events[if deliver_bs_raa { 1 } else { 0 }] {
3180 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3181 _ => panic!("Unexpected event"),
3183 match events[if deliver_bs_raa { 2 } else { 1 }] {
3184 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3185 assert_eq!(channel_id, chan_2.2);
3186 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3188 _ => panic!("Unexpected event"),
3192 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, .. } } => {
3193 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3194 assert_eq!(update_add_htlcs.len(), 1);
3195 assert!(update_fulfill_htlcs.is_empty());
3196 assert!(update_fail_htlcs.is_empty());
3197 assert!(update_fail_malformed_htlcs.is_empty());
3199 _ => panic!("Unexpected event"),
3202 match events[if deliver_bs_raa { 3 } else { 2 }] {
3203 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, .. } } => {
3204 assert!(update_add_htlcs.is_empty());
3205 assert_eq!(update_fail_htlcs.len(), 3);
3206 assert!(update_fulfill_htlcs.is_empty());
3207 assert!(update_fail_malformed_htlcs.is_empty());
3208 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3210 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3211 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3212 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3214 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3216 let events = nodes[0].node.get_and_clear_pending_events();
3217 assert_eq!(events.len(), 3);
3219 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3220 assert!(failed_htlcs.insert(payment_hash.0));
3221 // If we delivered B's RAA we got an unknown preimage error, not something
3222 // that we should update our routing table for.
3223 if !deliver_bs_raa {
3224 assert!(network_update.is_some());
3227 _ => panic!("Unexpected event"),
3230 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3231 assert!(failed_htlcs.insert(payment_hash.0));
3232 assert!(network_update.is_some());
3234 _ => panic!("Unexpected event"),
3237 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3238 assert!(failed_htlcs.insert(payment_hash.0));
3239 assert!(network_update.is_some());
3241 _ => panic!("Unexpected event"),
3244 _ => panic!("Unexpected event"),
3247 assert!(failed_htlcs.contains(&first_payment_hash.0));
3248 assert!(failed_htlcs.contains(&second_payment_hash.0));
3249 assert!(failed_htlcs.contains(&third_payment_hash.0));
3253 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3254 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3255 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3256 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3257 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3261 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3262 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3263 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3264 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3265 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3269 fn fail_backward_pending_htlc_upon_channel_failure() {
3270 let chanmon_cfgs = create_chanmon_cfgs(2);
3271 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3272 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3273 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3274 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3276 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3278 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3279 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3280 check_added_monitors!(nodes[0], 1);
3282 let payment_event = {
3283 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3284 assert_eq!(events.len(), 1);
3285 SendEvent::from_event(events.remove(0))
3287 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3288 assert_eq!(payment_event.msgs.len(), 1);
3291 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3292 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3294 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3295 check_added_monitors!(nodes[0], 0);
3297 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3300 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3302 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3304 let secp_ctx = Secp256k1::new();
3305 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3306 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3307 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3308 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3309 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3311 // Send a 0-msat update_add_htlc to fail the channel.
3312 let update_add_htlc = msgs::UpdateAddHTLC {
3318 onion_routing_packet,
3320 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3322 let events = nodes[0].node.get_and_clear_pending_events();
3323 assert_eq!(events.len(), 2);
3324 // Check that Alice fails backward the pending HTLC from the second payment.
3326 Event::PaymentPathFailed { payment_hash, .. } => {
3327 assert_eq!(payment_hash, failed_payment_hash);
3329 _ => panic!("Unexpected event"),
3332 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3333 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3335 _ => panic!("Unexpected event {:?}", events[1]),
3337 check_closed_broadcast!(nodes[0], true);
3338 check_added_monitors!(nodes[0], 1);
3342 fn test_htlc_ignore_latest_remote_commitment() {
3343 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3344 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3345 let chanmon_cfgs = create_chanmon_cfgs(2);
3346 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3347 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3348 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3349 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3351 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3352 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3353 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3354 check_closed_broadcast!(nodes[0], true);
3355 check_added_monitors!(nodes[0], 1);
3356 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3358 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3359 assert_eq!(node_txn.len(), 3);
3360 assert_eq!(node_txn[0], node_txn[1]);
3362 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3363 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3364 check_closed_broadcast!(nodes[1], true);
3365 check_added_monitors!(nodes[1], 1);
3366 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3368 // Duplicate the connect_block call since this may happen due to other listeners
3369 // registering new transactions
3370 header.prev_blockhash = header.block_hash();
3371 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3375 fn test_force_close_fail_back() {
3376 // Check which HTLCs are failed-backwards on channel force-closure
3377 let chanmon_cfgs = create_chanmon_cfgs(3);
3378 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3379 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3380 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3381 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3382 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3384 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3386 let mut payment_event = {
3387 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3388 check_added_monitors!(nodes[0], 1);
3390 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3391 assert_eq!(events.len(), 1);
3392 SendEvent::from_event(events.remove(0))
3395 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3396 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3398 expect_pending_htlcs_forwardable!(nodes[1]);
3400 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3401 assert_eq!(events_2.len(), 1);
3402 payment_event = SendEvent::from_event(events_2.remove(0));
3403 assert_eq!(payment_event.msgs.len(), 1);
3405 check_added_monitors!(nodes[1], 1);
3406 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3407 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3408 check_added_monitors!(nodes[2], 1);
3409 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3411 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3412 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3413 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3415 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3416 check_closed_broadcast!(nodes[2], true);
3417 check_added_monitors!(nodes[2], 1);
3418 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3420 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3421 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3422 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3423 // back to nodes[1] upon timeout otherwise.
3424 assert_eq!(node_txn.len(), 1);
3428 mine_transaction(&nodes[1], &tx);
3430 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3431 check_closed_broadcast!(nodes[1], true);
3432 check_added_monitors!(nodes[1], 1);
3433 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3435 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3437 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3438 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3440 mine_transaction(&nodes[2], &tx);
3441 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3442 assert_eq!(node_txn.len(), 1);
3443 assert_eq!(node_txn[0].input.len(), 1);
3444 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3445 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3446 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3448 check_spends!(node_txn[0], tx);
3452 fn test_dup_events_on_peer_disconnect() {
3453 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3454 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3455 // as we used to generate the event immediately upon receipt of the payment preimage in the
3456 // update_fulfill_htlc message.
3458 let chanmon_cfgs = create_chanmon_cfgs(2);
3459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3460 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3461 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3462 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3464 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3466 assert!(nodes[1].node.claim_funds(payment_preimage));
3467 check_added_monitors!(nodes[1], 1);
3468 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3469 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3470 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3472 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3473 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3475 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3476 expect_payment_path_successful!(nodes[0]);
3480 fn test_simple_peer_disconnect() {
3481 // Test that we can reconnect when there are no lost messages
3482 let chanmon_cfgs = create_chanmon_cfgs(3);
3483 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3484 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3485 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3486 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3487 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3489 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3490 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3491 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3493 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3494 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3495 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3496 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3498 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3499 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3500 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3502 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3503 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3504 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3505 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3507 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3508 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3510 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3511 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3513 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3515 let events = nodes[0].node.get_and_clear_pending_events();
3516 assert_eq!(events.len(), 3);
3518 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3519 assert_eq!(payment_preimage, payment_preimage_3);
3520 assert_eq!(payment_hash, payment_hash_3);
3522 _ => panic!("Unexpected event"),
3525 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3526 assert_eq!(payment_hash, payment_hash_5);
3527 assert!(rejected_by_dest);
3529 _ => panic!("Unexpected event"),
3532 Event::PaymentPathSuccessful { .. } => {},
3533 _ => panic!("Unexpected event"),
3537 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3538 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3541 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3542 // Test that we can reconnect when in-flight HTLC updates get dropped
3543 let chanmon_cfgs = create_chanmon_cfgs(2);
3544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3546 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3548 let mut as_funding_locked = None;
3549 if messages_delivered == 0 {
3550 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3551 as_funding_locked = Some(funding_locked);
3552 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3553 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3554 // it before the channel_reestablish message.
3556 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3559 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3561 let payment_event = {
3562 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3563 check_added_monitors!(nodes[0], 1);
3565 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3566 assert_eq!(events.len(), 1);
3567 SendEvent::from_event(events.remove(0))
3569 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3571 if messages_delivered < 2 {
3572 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3574 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3575 if messages_delivered >= 3 {
3576 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3577 check_added_monitors!(nodes[1], 1);
3578 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3580 if messages_delivered >= 4 {
3581 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3582 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3583 check_added_monitors!(nodes[0], 1);
3585 if messages_delivered >= 5 {
3586 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3587 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3588 // No commitment_signed so get_event_msg's assert(len == 1) passes
3589 check_added_monitors!(nodes[0], 1);
3591 if messages_delivered >= 6 {
3592 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3593 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3594 check_added_monitors!(nodes[1], 1);
3601 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3602 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3603 if messages_delivered < 3 {
3604 if simulate_broken_lnd {
3605 // lnd has a long-standing bug where they send a funding_locked prior to a
3606 // channel_reestablish if you reconnect prior to funding_locked time.
3608 // Here we simulate that behavior, delivering a funding_locked immediately on
3609 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3610 // in `reconnect_nodes` but we currently don't fail based on that.
3612 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3613 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3615 // Even if the funding_locked messages get exchanged, as long as nothing further was
3616 // received on either side, both sides will need to resend them.
3617 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3618 } else if messages_delivered == 3 {
3619 // nodes[0] still wants its RAA + commitment_signed
3620 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3621 } else if messages_delivered == 4 {
3622 // nodes[0] still wants its commitment_signed
3623 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3624 } else if messages_delivered == 5 {
3625 // nodes[1] still wants its final RAA
3626 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3627 } else if messages_delivered == 6 {
3628 // Everything was delivered...
3629 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3632 let events_1 = nodes[1].node.get_and_clear_pending_events();
3633 assert_eq!(events_1.len(), 1);
3635 Event::PendingHTLCsForwardable { .. } => { },
3636 _ => panic!("Unexpected event"),
3639 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3640 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3641 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3643 nodes[1].node.process_pending_htlc_forwards();
3645 let events_2 = nodes[1].node.get_and_clear_pending_events();
3646 assert_eq!(events_2.len(), 1);
3648 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3649 assert_eq!(payment_hash_1, *payment_hash);
3650 assert_eq!(amt, 1000000);
3652 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3653 assert!(payment_preimage.is_none());
3654 assert_eq!(payment_secret_1, *payment_secret);
3656 _ => panic!("expected PaymentPurpose::InvoicePayment")
3659 _ => panic!("Unexpected event"),
3662 nodes[1].node.claim_funds(payment_preimage_1);
3663 check_added_monitors!(nodes[1], 1);
3665 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3666 assert_eq!(events_3.len(), 1);
3667 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3668 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3669 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3670 assert!(updates.update_add_htlcs.is_empty());
3671 assert!(updates.update_fail_htlcs.is_empty());
3672 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3673 assert!(updates.update_fail_malformed_htlcs.is_empty());
3674 assert!(updates.update_fee.is_none());
3675 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3677 _ => panic!("Unexpected event"),
3680 if messages_delivered >= 1 {
3681 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3683 let events_4 = nodes[0].node.get_and_clear_pending_events();
3684 assert_eq!(events_4.len(), 1);
3686 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3687 assert_eq!(payment_preimage_1, *payment_preimage);
3688 assert_eq!(payment_hash_1, *payment_hash);
3690 _ => panic!("Unexpected event"),
3693 if messages_delivered >= 2 {
3694 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3695 check_added_monitors!(nodes[0], 1);
3696 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3698 if messages_delivered >= 3 {
3699 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3700 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3701 check_added_monitors!(nodes[1], 1);
3703 if messages_delivered >= 4 {
3704 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3705 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3706 // No commitment_signed so get_event_msg's assert(len == 1) passes
3707 check_added_monitors!(nodes[1], 1);
3709 if messages_delivered >= 5 {
3710 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3711 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3712 check_added_monitors!(nodes[0], 1);
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 if messages_delivered < 2 {
3722 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3723 if messages_delivered < 1 {
3724 expect_payment_sent!(nodes[0], payment_preimage_1);
3726 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3728 } else if messages_delivered == 2 {
3729 // nodes[0] still wants its RAA + commitment_signed
3730 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3731 } else if messages_delivered == 3 {
3732 // nodes[0] still wants its commitment_signed
3733 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734 } else if messages_delivered == 4 {
3735 // nodes[1] still wants its final RAA
3736 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3737 } else if messages_delivered == 5 {
3738 // Everything was delivered...
3739 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3742 if messages_delivered == 1 || messages_delivered == 2 {
3743 expect_payment_path_successful!(nodes[0]);
3746 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3747 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3748 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3750 if messages_delivered > 2 {
3751 expect_payment_path_successful!(nodes[0]);
3754 // Channel should still work fine...
3755 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3756 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3757 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3761 fn test_drop_messages_peer_disconnect_a() {
3762 do_test_drop_messages_peer_disconnect(0, true);
3763 do_test_drop_messages_peer_disconnect(0, false);
3764 do_test_drop_messages_peer_disconnect(1, false);
3765 do_test_drop_messages_peer_disconnect(2, false);
3769 fn test_drop_messages_peer_disconnect_b() {
3770 do_test_drop_messages_peer_disconnect(3, false);
3771 do_test_drop_messages_peer_disconnect(4, false);
3772 do_test_drop_messages_peer_disconnect(5, false);
3773 do_test_drop_messages_peer_disconnect(6, false);
3777 fn test_funding_peer_disconnect() {
3778 // Test that we can lock in our funding tx while disconnected
3779 let chanmon_cfgs = create_chanmon_cfgs(2);
3780 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3781 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3782 let persister: test_utils::TestPersister;
3783 let new_chain_monitor: test_utils::TestChainMonitor;
3784 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3785 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3786 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3788 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3789 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3791 confirm_transaction(&nodes[0], &tx);
3792 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3793 assert!(events_1.is_empty());
3795 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3797 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3798 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3800 confirm_transaction(&nodes[1], &tx);
3801 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3802 assert!(events_2.is_empty());
3804 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3805 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3806 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3807 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3809 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3810 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3811 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3812 assert_eq!(events_3.len(), 1);
3813 let as_funding_locked = match events_3[0] {
3814 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3815 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3818 _ => panic!("Unexpected event {:?}", events_3[0]),
3821 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3822 // announcement_signatures as well as channel_update.
3823 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3824 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3825 assert_eq!(events_4.len(), 3);
3827 let bs_funding_locked = match events_4[0] {
3828 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3829 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3830 chan_id = msg.channel_id;
3833 _ => panic!("Unexpected event {:?}", events_4[0]),
3835 let bs_announcement_sigs = match events_4[1] {
3836 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3837 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3840 _ => panic!("Unexpected event {:?}", events_4[1]),
3843 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3844 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3846 _ => panic!("Unexpected event {:?}", events_4[2]),
3849 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3850 // generates a duplicative private channel_update
3851 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3852 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3853 assert_eq!(events_5.len(), 1);
3855 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3856 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3858 _ => panic!("Unexpected event {:?}", events_5[0]),
3861 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3862 // announcement_signatures.
3863 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3864 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3865 assert_eq!(events_6.len(), 1);
3866 let as_announcement_sigs = match events_6[0] {
3867 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3868 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3871 _ => panic!("Unexpected event {:?}", events_6[0]),
3874 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3875 // broadcast the channel announcement globally, as well as re-send its (now-public)
3877 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3878 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3879 assert_eq!(events_7.len(), 1);
3880 let (chan_announcement, as_update) = match events_7[0] {
3881 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3882 (msg.clone(), update_msg.clone())
3884 _ => panic!("Unexpected event {:?}", events_7[0]),
3887 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3888 // same channel_announcement.
3889 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3890 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3891 assert_eq!(events_8.len(), 1);
3892 let bs_update = match events_8[0] {
3893 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3894 assert_eq!(*msg, chan_announcement);
3897 _ => panic!("Unexpected event {:?}", events_8[0]),
3900 // Provide the channel announcement and public updates to the network graph
3901 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3902 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3903 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3905 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3906 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3907 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3909 // Check that after deserialization and reconnection we can still generate an identical
3910 // channel_announcement from the cached signatures.
3911 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3913 let nodes_0_serialized = nodes[0].node.encode();
3914 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3915 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3917 persister = test_utils::TestPersister::new();
3918 let keys_manager = &chanmon_cfgs[0].keys_manager;
3919 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);
3920 nodes[0].chain_monitor = &new_chain_monitor;
3921 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3922 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3923 &mut chan_0_monitor_read, keys_manager).unwrap();
3924 assert!(chan_0_monitor_read.is_empty());
3926 let mut nodes_0_read = &nodes_0_serialized[..];
3927 let (_, nodes_0_deserialized_tmp) = {
3928 let mut channel_monitors = HashMap::new();
3929 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3930 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3931 default_config: UserConfig::default(),
3933 fee_estimator: node_cfgs[0].fee_estimator,
3934 chain_monitor: nodes[0].chain_monitor,
3935 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3936 logger: nodes[0].logger,
3940 nodes_0_deserialized = nodes_0_deserialized_tmp;
3941 assert!(nodes_0_read.is_empty());
3943 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3944 nodes[0].node = &nodes_0_deserialized;
3945 check_added_monitors!(nodes[0], 1);
3947 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3949 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3950 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3951 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3952 let mut found_announcement = false;
3953 for event in msgs.iter() {
3955 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3956 if *msg == chan_announcement { found_announcement = true; }
3958 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3959 _ => panic!("Unexpected event"),
3962 assert!(found_announcement);
3966 fn test_funding_locked_without_best_block_updated() {
3967 // Previously, if we were offline when a funding transaction was locked in, and then we came
3968 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3969 // generate a funding_locked until a later best_block_updated. This tests that we generate the
3970 // funding_locked immediately instead.
3971 let chanmon_cfgs = create_chanmon_cfgs(2);
3972 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3973 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3974 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3975 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3977 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
3979 let conf_height = nodes[0].best_block_info().1 + 1;
3980 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3981 let block_txn = [funding_tx];
3982 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3983 let conf_block_header = nodes[0].get_block_header(conf_height);
3984 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3986 // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
3987 let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
3988 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3992 fn test_drop_messages_peer_disconnect_dual_htlc() {
3993 // Test that we can handle reconnecting when both sides of a channel have pending
3994 // commitment_updates when we disconnect.
3995 let chanmon_cfgs = create_chanmon_cfgs(2);
3996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3998 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3999 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4001 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4003 // Now try to send a second payment which will fail to send
4004 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4005 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4006 check_added_monitors!(nodes[0], 1);
4008 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4009 assert_eq!(events_1.len(), 1);
4011 MessageSendEvent::UpdateHTLCs { .. } => {},
4012 _ => panic!("Unexpected event"),
4015 assert!(nodes[1].node.claim_funds(payment_preimage_1));
4016 check_added_monitors!(nodes[1], 1);
4018 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4019 assert_eq!(events_2.len(), 1);
4021 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 } } => {
4022 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4023 assert!(update_add_htlcs.is_empty());
4024 assert_eq!(update_fulfill_htlcs.len(), 1);
4025 assert!(update_fail_htlcs.is_empty());
4026 assert!(update_fail_malformed_htlcs.is_empty());
4027 assert!(update_fee.is_none());
4029 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4030 let events_3 = nodes[0].node.get_and_clear_pending_events();
4031 assert_eq!(events_3.len(), 1);
4033 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4034 assert_eq!(*payment_preimage, payment_preimage_1);
4035 assert_eq!(*payment_hash, payment_hash_1);
4037 _ => panic!("Unexpected event"),
4040 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4041 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4042 // No commitment_signed so get_event_msg's assert(len == 1) passes
4043 check_added_monitors!(nodes[0], 1);
4045 _ => panic!("Unexpected event"),
4048 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4049 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4051 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4052 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4053 assert_eq!(reestablish_1.len(), 1);
4054 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4055 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4056 assert_eq!(reestablish_2.len(), 1);
4058 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4059 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4060 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4061 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4063 assert!(as_resp.0.is_none());
4064 assert!(bs_resp.0.is_none());
4066 assert!(bs_resp.1.is_none());
4067 assert!(bs_resp.2.is_none());
4069 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4071 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4072 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4073 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4074 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4075 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4076 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4077 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4078 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4079 // No commitment_signed so get_event_msg's assert(len == 1) passes
4080 check_added_monitors!(nodes[1], 1);
4082 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4083 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4084 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4085 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4086 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4087 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4088 assert!(bs_second_commitment_signed.update_fee.is_none());
4089 check_added_monitors!(nodes[1], 1);
4091 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4092 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4093 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4094 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4095 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4096 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4097 assert!(as_commitment_signed.update_fee.is_none());
4098 check_added_monitors!(nodes[0], 1);
4100 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4101 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4102 // No commitment_signed so get_event_msg's assert(len == 1) passes
4103 check_added_monitors!(nodes[0], 1);
4105 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4106 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4107 // No commitment_signed so get_event_msg's assert(len == 1) passes
4108 check_added_monitors!(nodes[1], 1);
4110 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4111 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4112 check_added_monitors!(nodes[1], 1);
4114 expect_pending_htlcs_forwardable!(nodes[1]);
4116 let events_5 = nodes[1].node.get_and_clear_pending_events();
4117 assert_eq!(events_5.len(), 1);
4119 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4120 assert_eq!(payment_hash_2, *payment_hash);
4122 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4123 assert!(payment_preimage.is_none());
4124 assert_eq!(payment_secret_2, *payment_secret);
4126 _ => panic!("expected PaymentPurpose::InvoicePayment")
4129 _ => panic!("Unexpected event"),
4132 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4133 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4134 check_added_monitors!(nodes[0], 1);
4136 expect_payment_path_successful!(nodes[0]);
4137 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4140 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4141 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4142 // to avoid our counterparty failing the channel.
4143 let chanmon_cfgs = create_chanmon_cfgs(2);
4144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4146 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4148 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4150 let our_payment_hash = if send_partial_mpp {
4151 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4152 // Use the utility function send_payment_along_path to send the payment with MPP data which
4153 // indicates there are more HTLCs coming.
4154 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.
4155 let payment_id = PaymentId([42; 32]);
4156 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();
4157 check_added_monitors!(nodes[0], 1);
4158 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4159 assert_eq!(events.len(), 1);
4160 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4161 // hop should *not* yet generate any PaymentReceived event(s).
4162 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4165 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4168 let mut block = Block {
4169 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4172 connect_block(&nodes[0], &block);
4173 connect_block(&nodes[1], &block);
4174 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4175 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4176 block.header.prev_blockhash = block.block_hash();
4177 connect_block(&nodes[0], &block);
4178 connect_block(&nodes[1], &block);
4181 expect_pending_htlcs_forwardable!(nodes[1]);
4183 check_added_monitors!(nodes[1], 1);
4184 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4185 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4186 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4187 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4188 assert!(htlc_timeout_updates.update_fee.is_none());
4190 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4191 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4192 // 100_000 msat as u64, followed by the height at which we failed back above
4193 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4194 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4195 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4199 fn test_htlc_timeout() {
4200 do_test_htlc_timeout(true);
4201 do_test_htlc_timeout(false);
4204 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4205 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4206 let chanmon_cfgs = create_chanmon_cfgs(3);
4207 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4208 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4209 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4210 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4211 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4213 // Make sure all nodes are at the same starting height
4214 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4215 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4216 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4218 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4219 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4221 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4223 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4224 check_added_monitors!(nodes[1], 1);
4226 // Now attempt to route a second payment, which should be placed in the holding cell
4227 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4228 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4229 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4231 check_added_monitors!(nodes[0], 1);
4232 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4233 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4234 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4235 expect_pending_htlcs_forwardable!(nodes[1]);
4237 check_added_monitors!(nodes[1], 0);
4239 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4240 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4241 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4242 connect_blocks(&nodes[1], 1);
4245 expect_pending_htlcs_forwardable!(nodes[1]);
4246 check_added_monitors!(nodes[1], 1);
4247 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4248 assert_eq!(fail_commit.len(), 1);
4249 match fail_commit[0] {
4250 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4251 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4252 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4254 _ => unreachable!(),
4256 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4258 let events = nodes[1].node.get_and_clear_pending_events();
4259 assert_eq!(events.len(), 2);
4260 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4261 assert_eq!(*payment_hash, second_payment_hash);
4262 } else { panic!("Unexpected event"); }
4263 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4264 assert_eq!(*payment_hash, second_payment_hash);
4265 } else { panic!("Unexpected event"); }
4270 fn test_holding_cell_htlc_add_timeouts() {
4271 do_test_holding_cell_htlc_add_timeouts(false);
4272 do_test_holding_cell_htlc_add_timeouts(true);
4276 fn test_no_txn_manager_serialize_deserialize() {
4277 let chanmon_cfgs = create_chanmon_cfgs(2);
4278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4280 let logger: test_utils::TestLogger;
4281 let fee_estimator: test_utils::TestFeeEstimator;
4282 let persister: test_utils::TestPersister;
4283 let new_chain_monitor: test_utils::TestChainMonitor;
4284 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4285 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4287 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4289 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4291 let nodes_0_serialized = nodes[0].node.encode();
4292 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4293 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4294 .write(&mut chan_0_monitor_serialized).unwrap();
4296 logger = test_utils::TestLogger::new();
4297 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4298 persister = test_utils::TestPersister::new();
4299 let keys_manager = &chanmon_cfgs[0].keys_manager;
4300 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4301 nodes[0].chain_monitor = &new_chain_monitor;
4302 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4303 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4304 &mut chan_0_monitor_read, keys_manager).unwrap();
4305 assert!(chan_0_monitor_read.is_empty());
4307 let mut nodes_0_read = &nodes_0_serialized[..];
4308 let config = UserConfig::default();
4309 let (_, nodes_0_deserialized_tmp) = {
4310 let mut channel_monitors = HashMap::new();
4311 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4312 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4313 default_config: config,
4315 fee_estimator: &fee_estimator,
4316 chain_monitor: nodes[0].chain_monitor,
4317 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4322 nodes_0_deserialized = nodes_0_deserialized_tmp;
4323 assert!(nodes_0_read.is_empty());
4325 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4326 nodes[0].node = &nodes_0_deserialized;
4327 assert_eq!(nodes[0].node.list_channels().len(), 1);
4328 check_added_monitors!(nodes[0], 1);
4330 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4331 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4332 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4333 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4335 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4336 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4337 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4338 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4340 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4341 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4342 for node in nodes.iter() {
4343 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4344 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4345 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4348 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4352 fn test_manager_serialize_deserialize_events() {
4353 // This test makes sure the events field in ChannelManager survives de/serialization
4354 let chanmon_cfgs = create_chanmon_cfgs(2);
4355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4357 let fee_estimator: test_utils::TestFeeEstimator;
4358 let persister: test_utils::TestPersister;
4359 let logger: test_utils::TestLogger;
4360 let new_chain_monitor: test_utils::TestChainMonitor;
4361 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4364 // Start creating a channel, but stop right before broadcasting the funding transaction
4365 let channel_value = 100000;
4366 let push_msat = 10001;
4367 let a_flags = InitFeatures::known();
4368 let b_flags = InitFeatures::known();
4369 let node_a = nodes.remove(0);
4370 let node_b = nodes.remove(0);
4371 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4372 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()));
4373 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()));
4375 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4377 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4378 check_added_monitors!(node_a, 0);
4380 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()));
4382 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4383 assert_eq!(added_monitors.len(), 1);
4384 assert_eq!(added_monitors[0].0, funding_output);
4385 added_monitors.clear();
4388 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4389 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4391 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4392 assert_eq!(added_monitors.len(), 1);
4393 assert_eq!(added_monitors[0].0, funding_output);
4394 added_monitors.clear();
4396 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4401 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4402 let nodes_0_serialized = nodes[0].node.encode();
4403 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4404 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4406 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4407 logger = test_utils::TestLogger::new();
4408 persister = test_utils::TestPersister::new();
4409 let keys_manager = &chanmon_cfgs[0].keys_manager;
4410 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4411 nodes[0].chain_monitor = &new_chain_monitor;
4412 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4413 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4414 &mut chan_0_monitor_read, keys_manager).unwrap();
4415 assert!(chan_0_monitor_read.is_empty());
4417 let mut nodes_0_read = &nodes_0_serialized[..];
4418 let config = UserConfig::default();
4419 let (_, nodes_0_deserialized_tmp) = {
4420 let mut channel_monitors = HashMap::new();
4421 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4422 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4423 default_config: config,
4425 fee_estimator: &fee_estimator,
4426 chain_monitor: nodes[0].chain_monitor,
4427 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4432 nodes_0_deserialized = nodes_0_deserialized_tmp;
4433 assert!(nodes_0_read.is_empty());
4435 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4437 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4438 nodes[0].node = &nodes_0_deserialized;
4440 // After deserializing, make sure the funding_transaction is still held by the channel manager
4441 let events_4 = nodes[0].node.get_and_clear_pending_events();
4442 assert_eq!(events_4.len(), 0);
4443 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4444 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4446 // Make sure the channel is functioning as though the de/serialization never happened
4447 assert_eq!(nodes[0].node.list_channels().len(), 1);
4448 check_added_monitors!(nodes[0], 1);
4450 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4451 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4452 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4453 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4455 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4456 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4457 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4458 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4460 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4461 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4462 for node in nodes.iter() {
4463 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4464 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4465 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4468 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4472 fn test_simple_manager_serialize_deserialize() {
4473 let chanmon_cfgs = create_chanmon_cfgs(2);
4474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4476 let logger: test_utils::TestLogger;
4477 let fee_estimator: test_utils::TestFeeEstimator;
4478 let persister: test_utils::TestPersister;
4479 let new_chain_monitor: test_utils::TestChainMonitor;
4480 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4481 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4482 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4484 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4485 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4487 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4489 let nodes_0_serialized = nodes[0].node.encode();
4490 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4491 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4493 logger = test_utils::TestLogger::new();
4494 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4495 persister = test_utils::TestPersister::new();
4496 let keys_manager = &chanmon_cfgs[0].keys_manager;
4497 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4498 nodes[0].chain_monitor = &new_chain_monitor;
4499 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4500 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4501 &mut chan_0_monitor_read, keys_manager).unwrap();
4502 assert!(chan_0_monitor_read.is_empty());
4504 let mut nodes_0_read = &nodes_0_serialized[..];
4505 let (_, nodes_0_deserialized_tmp) = {
4506 let mut channel_monitors = HashMap::new();
4507 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4508 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4509 default_config: UserConfig::default(),
4511 fee_estimator: &fee_estimator,
4512 chain_monitor: nodes[0].chain_monitor,
4513 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4518 nodes_0_deserialized = nodes_0_deserialized_tmp;
4519 assert!(nodes_0_read.is_empty());
4521 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4522 nodes[0].node = &nodes_0_deserialized;
4523 check_added_monitors!(nodes[0], 1);
4525 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4527 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4528 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4532 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4533 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4534 let chanmon_cfgs = create_chanmon_cfgs(4);
4535 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4536 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4537 let logger: test_utils::TestLogger;
4538 let fee_estimator: test_utils::TestFeeEstimator;
4539 let persister: test_utils::TestPersister;
4540 let new_chain_monitor: test_utils::TestChainMonitor;
4541 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4542 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4543 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4544 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4545 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4547 let mut node_0_stale_monitors_serialized = Vec::new();
4548 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4549 let mut writer = test_utils::TestVecWriter(Vec::new());
4550 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4551 node_0_stale_monitors_serialized.push(writer.0);
4554 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4556 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4557 let nodes_0_serialized = nodes[0].node.encode();
4559 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4560 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4561 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4562 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4564 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4566 let mut node_0_monitors_serialized = Vec::new();
4567 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4568 let mut writer = test_utils::TestVecWriter(Vec::new());
4569 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4570 node_0_monitors_serialized.push(writer.0);
4573 logger = test_utils::TestLogger::new();
4574 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4575 persister = test_utils::TestPersister::new();
4576 let keys_manager = &chanmon_cfgs[0].keys_manager;
4577 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4578 nodes[0].chain_monitor = &new_chain_monitor;
4581 let mut node_0_stale_monitors = Vec::new();
4582 for serialized in node_0_stale_monitors_serialized.iter() {
4583 let mut read = &serialized[..];
4584 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4585 assert!(read.is_empty());
4586 node_0_stale_monitors.push(monitor);
4589 let mut node_0_monitors = Vec::new();
4590 for serialized in node_0_monitors_serialized.iter() {
4591 let mut read = &serialized[..];
4592 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4593 assert!(read.is_empty());
4594 node_0_monitors.push(monitor);
4597 let mut nodes_0_read = &nodes_0_serialized[..];
4598 if let Err(msgs::DecodeError::InvalidValue) =
4599 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4600 default_config: UserConfig::default(),
4602 fee_estimator: &fee_estimator,
4603 chain_monitor: nodes[0].chain_monitor,
4604 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4606 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4608 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4611 let mut nodes_0_read = &nodes_0_serialized[..];
4612 let (_, nodes_0_deserialized_tmp) =
4613 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4614 default_config: UserConfig::default(),
4616 fee_estimator: &fee_estimator,
4617 chain_monitor: nodes[0].chain_monitor,
4618 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4620 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4622 nodes_0_deserialized = nodes_0_deserialized_tmp;
4623 assert!(nodes_0_read.is_empty());
4625 { // Channel close should result in a commitment tx
4626 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4627 assert_eq!(txn.len(), 1);
4628 check_spends!(txn[0], funding_tx);
4629 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4632 for monitor in node_0_monitors.drain(..) {
4633 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4634 check_added_monitors!(nodes[0], 1);
4636 nodes[0].node = &nodes_0_deserialized;
4637 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4639 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4640 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4641 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4642 //... and we can even still claim the payment!
4643 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4645 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4646 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4647 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4648 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4649 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4650 assert_eq!(msg_events.len(), 1);
4651 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4653 &ErrorAction::SendErrorMessage { ref msg } => {
4654 assert_eq!(msg.channel_id, channel_id);
4656 _ => panic!("Unexpected event!"),
4661 macro_rules! check_spendable_outputs {
4662 ($node: expr, $keysinterface: expr) => {
4664 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4665 let mut txn = Vec::new();
4666 let mut all_outputs = Vec::new();
4667 let secp_ctx = Secp256k1::new();
4668 for event in events.drain(..) {
4670 Event::SpendableOutputs { mut outputs } => {
4671 for outp in outputs.drain(..) {
4672 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4673 all_outputs.push(outp);
4676 _ => panic!("Unexpected event"),
4679 if all_outputs.len() > 1 {
4680 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) {
4690 fn test_claim_sizeable_push_msat() {
4691 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4692 let chanmon_cfgs = create_chanmon_cfgs(2);
4693 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4694 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4695 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4697 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4698 nodes[1].node.force_close_channel(&chan.2).unwrap();
4699 check_closed_broadcast!(nodes[1], true);
4700 check_added_monitors!(nodes[1], 1);
4701 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4702 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4703 assert_eq!(node_txn.len(), 1);
4704 check_spends!(node_txn[0], chan.3);
4705 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
4707 mine_transaction(&nodes[1], &node_txn[0]);
4708 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4710 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4711 assert_eq!(spend_txn.len(), 1);
4712 assert_eq!(spend_txn[0].input.len(), 1);
4713 check_spends!(spend_txn[0], node_txn[0]);
4714 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4718 fn test_claim_on_remote_sizeable_push_msat() {
4719 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4720 // to_remote output is encumbered by a P2WPKH
4721 let chanmon_cfgs = create_chanmon_cfgs(2);
4722 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4723 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4724 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4726 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4727 nodes[0].node.force_close_channel(&chan.2).unwrap();
4728 check_closed_broadcast!(nodes[0], true);
4729 check_added_monitors!(nodes[0], 1);
4730 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4732 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4733 assert_eq!(node_txn.len(), 1);
4734 check_spends!(node_txn[0], chan.3);
4735 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
4737 mine_transaction(&nodes[1], &node_txn[0]);
4738 check_closed_broadcast!(nodes[1], true);
4739 check_added_monitors!(nodes[1], 1);
4740 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4741 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4743 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4744 assert_eq!(spend_txn.len(), 1);
4745 check_spends!(spend_txn[0], node_txn[0]);
4749 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4750 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4751 // to_remote output is encumbered by a P2WPKH
4753 let chanmon_cfgs = create_chanmon_cfgs(2);
4754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4756 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4758 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4759 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4760 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4761 assert_eq!(revoked_local_txn[0].input.len(), 1);
4762 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4764 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4765 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4766 check_closed_broadcast!(nodes[1], true);
4767 check_added_monitors!(nodes[1], 1);
4768 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4770 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4771 mine_transaction(&nodes[1], &node_txn[0]);
4772 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4774 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4775 assert_eq!(spend_txn.len(), 3);
4776 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4777 check_spends!(spend_txn[1], node_txn[0]);
4778 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4782 fn test_static_spendable_outputs_preimage_tx() {
4783 let chanmon_cfgs = create_chanmon_cfgs(2);
4784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4788 // Create some initial channels
4789 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4791 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4793 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4794 assert_eq!(commitment_tx[0].input.len(), 1);
4795 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4797 // Settle A's commitment tx on B's chain
4798 assert!(nodes[1].node.claim_funds(payment_preimage));
4799 check_added_monitors!(nodes[1], 1);
4800 mine_transaction(&nodes[1], &commitment_tx[0]);
4801 check_added_monitors!(nodes[1], 1);
4802 let events = nodes[1].node.get_and_clear_pending_msg_events();
4804 MessageSendEvent::UpdateHTLCs { .. } => {},
4805 _ => panic!("Unexpected event"),
4808 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4809 _ => panic!("Unexepected event"),
4812 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4813 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4814 assert_eq!(node_txn.len(), 3);
4815 check_spends!(node_txn[0], commitment_tx[0]);
4816 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4817 check_spends!(node_txn[1], chan_1.3);
4818 check_spends!(node_txn[2], node_txn[1]);
4820 mine_transaction(&nodes[1], &node_txn[0]);
4821 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4822 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4824 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4825 assert_eq!(spend_txn.len(), 1);
4826 check_spends!(spend_txn[0], node_txn[0]);
4830 fn test_static_spendable_outputs_timeout_tx() {
4831 let chanmon_cfgs = create_chanmon_cfgs(2);
4832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4834 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4836 // Create some initial channels
4837 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4839 // Rebalance the network a bit by relaying one payment through all the channels ...
4840 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4842 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4844 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4845 assert_eq!(commitment_tx[0].input.len(), 1);
4846 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4848 // Settle A's commitment tx on B' chain
4849 mine_transaction(&nodes[1], &commitment_tx[0]);
4850 check_added_monitors!(nodes[1], 1);
4851 let events = nodes[1].node.get_and_clear_pending_msg_events();
4853 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4854 _ => panic!("Unexpected event"),
4856 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4858 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4859 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4860 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4861 check_spends!(node_txn[0], chan_1.3.clone());
4862 check_spends!(node_txn[1], commitment_tx[0].clone());
4863 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4865 mine_transaction(&nodes[1], &node_txn[1]);
4866 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4867 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4868 expect_payment_failed!(nodes[1], our_payment_hash, true);
4870 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4871 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4872 check_spends!(spend_txn[0], commitment_tx[0]);
4873 check_spends!(spend_txn[1], node_txn[1]);
4874 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4878 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4879 let chanmon_cfgs = create_chanmon_cfgs(2);
4880 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4881 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4882 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4884 // Create some initial channels
4885 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4887 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4888 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4889 assert_eq!(revoked_local_txn[0].input.len(), 1);
4890 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4892 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4894 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4895 check_closed_broadcast!(nodes[1], true);
4896 check_added_monitors!(nodes[1], 1);
4897 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4899 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4900 assert_eq!(node_txn.len(), 2);
4901 assert_eq!(node_txn[0].input.len(), 2);
4902 check_spends!(node_txn[0], revoked_local_txn[0]);
4904 mine_transaction(&nodes[1], &node_txn[0]);
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_justice_tx_revoked_htlc_timeout_tx() {
4914 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4915 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4916 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4917 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4918 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4920 // Create some initial channels
4921 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4923 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4924 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4925 assert_eq!(revoked_local_txn[0].input.len(), 1);
4926 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4928 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4930 // A will generate HTLC-Timeout from revoked commitment tx
4931 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4932 check_closed_broadcast!(nodes[0], true);
4933 check_added_monitors!(nodes[0], 1);
4934 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4935 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4937 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4938 assert_eq!(revoked_htlc_txn.len(), 2);
4939 check_spends!(revoked_htlc_txn[0], chan_1.3);
4940 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4941 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4942 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4943 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4945 // B will generate justice tx from A's revoked commitment/HTLC tx
4946 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4947 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4948 check_closed_broadcast!(nodes[1], true);
4949 check_added_monitors!(nodes[1], 1);
4950 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4952 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4953 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4954 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4955 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4956 // transactions next...
4957 assert_eq!(node_txn[0].input.len(), 3);
4958 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4960 assert_eq!(node_txn[1].input.len(), 2);
4961 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4962 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4963 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4965 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4966 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4969 assert_eq!(node_txn[2].input.len(), 1);
4970 check_spends!(node_txn[2], chan_1.3);
4972 mine_transaction(&nodes[1], &node_txn[1]);
4973 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4975 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4976 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4977 assert_eq!(spend_txn.len(), 1);
4978 assert_eq!(spend_txn[0].input.len(), 1);
4979 check_spends!(spend_txn[0], node_txn[1]);
4983 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4984 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4985 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4986 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4987 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4988 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4990 // Create some initial channels
4991 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4993 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4994 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4995 assert_eq!(revoked_local_txn[0].input.len(), 1);
4996 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4998 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4999 assert_eq!(revoked_local_txn[0].output.len(), 2);
5001 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5003 // B will generate HTLC-Success from revoked commitment tx
5004 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5005 check_closed_broadcast!(nodes[1], true);
5006 check_added_monitors!(nodes[1], 1);
5007 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5008 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5010 assert_eq!(revoked_htlc_txn.len(), 2);
5011 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5012 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5013 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5015 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5016 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5017 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5019 // A will generate justice tx from B's revoked commitment/HTLC tx
5020 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5021 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5022 check_closed_broadcast!(nodes[0], true);
5023 check_added_monitors!(nodes[0], 1);
5024 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5026 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5027 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5029 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5030 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5031 // transactions next...
5032 assert_eq!(node_txn[0].input.len(), 2);
5033 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5034 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5035 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5037 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5038 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5041 assert_eq!(node_txn[1].input.len(), 1);
5042 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5044 check_spends!(node_txn[2], chan_1.3);
5046 mine_transaction(&nodes[0], &node_txn[1]);
5047 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5049 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5050 // didn't try to generate any new transactions.
5052 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5053 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5054 assert_eq!(spend_txn.len(), 3);
5055 assert_eq!(spend_txn[0].input.len(), 1);
5056 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5057 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5058 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5059 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5063 fn test_onchain_to_onchain_claim() {
5064 // Test that in case of channel closure, we detect the state of output and claim HTLC
5065 // on downstream peer's remote commitment tx.
5066 // First, have C claim an HTLC against its own latest commitment transaction.
5067 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5069 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5072 let chanmon_cfgs = create_chanmon_cfgs(3);
5073 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5074 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5075 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5077 // Create some initial channels
5078 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5079 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5081 // Ensure all nodes are at the same height
5082 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5083 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5084 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5085 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5087 // Rebalance the network a bit by relaying one payment through all the channels ...
5088 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5089 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5091 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5092 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5093 check_spends!(commitment_tx[0], chan_2.3);
5094 nodes[2].node.claim_funds(payment_preimage);
5095 check_added_monitors!(nodes[2], 1);
5096 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5097 assert!(updates.update_add_htlcs.is_empty());
5098 assert!(updates.update_fail_htlcs.is_empty());
5099 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5100 assert!(updates.update_fail_malformed_htlcs.is_empty());
5102 mine_transaction(&nodes[2], &commitment_tx[0]);
5103 check_closed_broadcast!(nodes[2], true);
5104 check_added_monitors!(nodes[2], 1);
5105 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5107 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5108 assert_eq!(c_txn.len(), 3);
5109 assert_eq!(c_txn[0], c_txn[2]);
5110 assert_eq!(commitment_tx[0], c_txn[1]);
5111 check_spends!(c_txn[1], chan_2.3);
5112 check_spends!(c_txn[2], c_txn[1]);
5113 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5114 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5115 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5116 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5118 // 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
5119 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5120 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5121 check_added_monitors!(nodes[1], 1);
5122 let events = nodes[1].node.get_and_clear_pending_events();
5123 assert_eq!(events.len(), 2);
5125 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5126 _ => panic!("Unexpected event"),
5129 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5130 assert_eq!(fee_earned_msat, Some(1000));
5131 assert_eq!(claim_from_onchain_tx, true);
5133 _ => panic!("Unexpected event"),
5136 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5137 // ChannelMonitor: claim tx
5138 assert_eq!(b_txn.len(), 1);
5139 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5142 check_added_monitors!(nodes[1], 1);
5143 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5144 assert_eq!(msg_events.len(), 3);
5145 match msg_events[0] {
5146 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5147 _ => panic!("Unexpected event"),
5149 match msg_events[1] {
5150 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5151 _ => panic!("Unexpected event"),
5153 match msg_events[2] {
5154 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, .. } } => {
5155 assert!(update_add_htlcs.is_empty());
5156 assert!(update_fail_htlcs.is_empty());
5157 assert_eq!(update_fulfill_htlcs.len(), 1);
5158 assert!(update_fail_malformed_htlcs.is_empty());
5159 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5161 _ => panic!("Unexpected event"),
5163 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5164 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5165 mine_transaction(&nodes[1], &commitment_tx[0]);
5166 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5167 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5168 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5169 assert_eq!(b_txn.len(), 3);
5170 check_spends!(b_txn[1], chan_1.3);
5171 check_spends!(b_txn[2], b_txn[1]);
5172 check_spends!(b_txn[0], commitment_tx[0]);
5173 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5174 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5175 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5177 check_closed_broadcast!(nodes[1], true);
5178 check_added_monitors!(nodes[1], 1);
5182 fn test_duplicate_payment_hash_one_failure_one_success() {
5183 // Topology : A --> B --> C --> D
5184 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5185 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5186 // we forward one of the payments onwards to D.
5187 let chanmon_cfgs = create_chanmon_cfgs(4);
5188 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5189 // When this test was written, the default base fee floated based on the HTLC count.
5190 // It is now fixed, so we simply set the fee to the expected value here.
5191 let mut config = test_default_channel_config();
5192 config.channel_options.forwarding_fee_base_msat = 196;
5193 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5194 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5195 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5197 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5198 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5199 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5201 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5202 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5203 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5204 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5205 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5207 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5209 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5210 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5211 // script push size limit so that the below script length checks match
5212 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5213 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5214 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5216 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5217 assert_eq!(commitment_txn[0].input.len(), 1);
5218 check_spends!(commitment_txn[0], chan_2.3);
5220 mine_transaction(&nodes[1], &commitment_txn[0]);
5221 check_closed_broadcast!(nodes[1], true);
5222 check_added_monitors!(nodes[1], 1);
5223 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5224 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5226 let htlc_timeout_tx;
5227 { // Extract one of the two HTLC-Timeout transaction
5228 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5229 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5230 assert_eq!(node_txn.len(), 4);
5231 check_spends!(node_txn[0], chan_2.3);
5233 check_spends!(node_txn[1], commitment_txn[0]);
5234 assert_eq!(node_txn[1].input.len(), 1);
5235 check_spends!(node_txn[2], commitment_txn[0]);
5236 assert_eq!(node_txn[2].input.len(), 1);
5237 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5238 check_spends!(node_txn[3], commitment_txn[0]);
5239 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5241 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5242 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5243 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5244 htlc_timeout_tx = node_txn[1].clone();
5247 nodes[2].node.claim_funds(our_payment_preimage);
5248 mine_transaction(&nodes[2], &commitment_txn[0]);
5249 check_added_monitors!(nodes[2], 2);
5250 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5251 let events = nodes[2].node.get_and_clear_pending_msg_events();
5253 MessageSendEvent::UpdateHTLCs { .. } => {},
5254 _ => panic!("Unexpected event"),
5257 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5258 _ => panic!("Unexepected event"),
5260 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5261 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)
5262 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5263 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5264 assert_eq!(htlc_success_txn[0].input.len(), 1);
5265 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5266 assert_eq!(htlc_success_txn[1].input.len(), 1);
5267 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5268 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5269 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5270 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5271 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5272 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5274 mine_transaction(&nodes[1], &htlc_timeout_tx);
5275 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5276 expect_pending_htlcs_forwardable!(nodes[1]);
5277 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5278 assert!(htlc_updates.update_add_htlcs.is_empty());
5279 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5280 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5281 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5282 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5283 check_added_monitors!(nodes[1], 1);
5285 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5286 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5288 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5290 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5292 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5293 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5294 // and nodes[2] fee) is rounded down and then claimed in full.
5295 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5296 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5297 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5298 assert!(updates.update_add_htlcs.is_empty());
5299 assert!(updates.update_fail_htlcs.is_empty());
5300 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5301 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5302 assert!(updates.update_fail_malformed_htlcs.is_empty());
5303 check_added_monitors!(nodes[1], 1);
5305 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5306 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5308 let events = nodes[0].node.get_and_clear_pending_events();
5310 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5311 assert_eq!(*payment_preimage, our_payment_preimage);
5312 assert_eq!(*payment_hash, duplicate_payment_hash);
5314 _ => panic!("Unexpected event"),
5319 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5320 let chanmon_cfgs = create_chanmon_cfgs(2);
5321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5323 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5325 // Create some initial channels
5326 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5328 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5329 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5330 assert_eq!(local_txn.len(), 1);
5331 assert_eq!(local_txn[0].input.len(), 1);
5332 check_spends!(local_txn[0], chan_1.3);
5334 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5335 nodes[1].node.claim_funds(payment_preimage);
5336 check_added_monitors!(nodes[1], 1);
5337 mine_transaction(&nodes[1], &local_txn[0]);
5338 check_added_monitors!(nodes[1], 1);
5339 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5340 let events = nodes[1].node.get_and_clear_pending_msg_events();
5342 MessageSendEvent::UpdateHTLCs { .. } => {},
5343 _ => panic!("Unexpected event"),
5346 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5347 _ => panic!("Unexepected event"),
5350 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5351 assert_eq!(node_txn.len(), 3);
5352 assert_eq!(node_txn[0], node_txn[2]);
5353 assert_eq!(node_txn[1], local_txn[0]);
5354 assert_eq!(node_txn[0].input.len(), 1);
5355 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5356 check_spends!(node_txn[0], local_txn[0]);
5360 mine_transaction(&nodes[1], &node_tx);
5361 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5363 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5364 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5365 assert_eq!(spend_txn.len(), 1);
5366 assert_eq!(spend_txn[0].input.len(), 1);
5367 check_spends!(spend_txn[0], node_tx);
5368 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5371 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5372 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5373 // unrevoked commitment transaction.
5374 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5375 // a remote RAA before they could be failed backwards (and combinations thereof).
5376 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5377 // use the same payment hashes.
5378 // Thus, we use a six-node network:
5383 // And test where C fails back to A/B when D announces its latest commitment transaction
5384 let chanmon_cfgs = create_chanmon_cfgs(6);
5385 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5386 // When this test was written, the default base fee floated based on the HTLC count.
5387 // It is now fixed, so we simply set the fee to the expected value here.
5388 let mut config = test_default_channel_config();
5389 config.channel_options.forwarding_fee_base_msat = 196;
5390 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5391 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5392 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5394 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5395 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5396 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5397 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5398 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5400 // Rebalance and check output sanity...
5401 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5402 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5403 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5405 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5407 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
5409 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
5410 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5412 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
5414 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
5416 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5418 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5419 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5421 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());
5423 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());
5426 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5428 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5429 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
5432 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
5434 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5435 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());
5437 // Double-check that six of the new HTLC were added
5438 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5439 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5440 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5441 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5443 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5444 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5445 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5446 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5447 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5448 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5449 check_added_monitors!(nodes[4], 0);
5450 expect_pending_htlcs_forwardable!(nodes[4]);
5451 check_added_monitors!(nodes[4], 1);
5453 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5454 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5455 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5456 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5457 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5458 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5460 // Fail 3rd below-dust and 7th above-dust HTLCs
5461 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5462 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5463 check_added_monitors!(nodes[5], 0);
5464 expect_pending_htlcs_forwardable!(nodes[5]);
5465 check_added_monitors!(nodes[5], 1);
5467 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5468 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5469 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5470 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5472 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5474 expect_pending_htlcs_forwardable!(nodes[3]);
5475 check_added_monitors!(nodes[3], 1);
5476 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5477 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5478 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5479 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5480 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5481 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5482 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5483 if deliver_last_raa {
5484 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5486 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5489 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5490 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5491 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5492 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5494 // We now broadcast the latest commitment transaction, which *should* result in failures for
5495 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5496 // the non-broadcast above-dust HTLCs.
5498 // Alternatively, we may broadcast the previous commitment transaction, which should only
5499 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5500 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5502 if announce_latest {
5503 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5505 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5507 let events = nodes[2].node.get_and_clear_pending_events();
5508 let close_event = if deliver_last_raa {
5509 assert_eq!(events.len(), 2);
5512 assert_eq!(events.len(), 1);
5516 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5517 _ => panic!("Unexpected event"),
5520 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5521 check_closed_broadcast!(nodes[2], true);
5522 if deliver_last_raa {
5523 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5525 expect_pending_htlcs_forwardable!(nodes[2]);
5527 check_added_monitors!(nodes[2], 3);
5529 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5530 assert_eq!(cs_msgs.len(), 2);
5531 let mut a_done = false;
5532 for msg in cs_msgs {
5534 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5535 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5536 // should be failed-backwards here.
5537 let target = if *node_id == nodes[0].node.get_our_node_id() {
5538 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5539 for htlc in &updates.update_fail_htlcs {
5540 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 });
5542 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5547 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5548 for htlc in &updates.update_fail_htlcs {
5549 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5551 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5552 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5555 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5556 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5557 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5558 if announce_latest {
5559 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5560 if *node_id == nodes[0].node.get_our_node_id() {
5561 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5564 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5566 _ => panic!("Unexpected event"),
5570 let as_events = nodes[0].node.get_and_clear_pending_events();
5571 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5572 let mut as_failds = HashSet::new();
5573 let mut as_updates = 0;
5574 for event in as_events.iter() {
5575 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5576 assert!(as_failds.insert(*payment_hash));
5577 if *payment_hash != payment_hash_2 {
5578 assert_eq!(*rejected_by_dest, deliver_last_raa);
5580 assert!(!rejected_by_dest);
5582 if network_update.is_some() {
5585 } else { panic!("Unexpected event"); }
5587 assert!(as_failds.contains(&payment_hash_1));
5588 assert!(as_failds.contains(&payment_hash_2));
5589 if announce_latest {
5590 assert!(as_failds.contains(&payment_hash_3));
5591 assert!(as_failds.contains(&payment_hash_5));
5593 assert!(as_failds.contains(&payment_hash_6));
5595 let bs_events = nodes[1].node.get_and_clear_pending_events();
5596 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5597 let mut bs_failds = HashSet::new();
5598 let mut bs_updates = 0;
5599 for event in bs_events.iter() {
5600 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5601 assert!(bs_failds.insert(*payment_hash));
5602 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5603 assert_eq!(*rejected_by_dest, deliver_last_raa);
5605 assert!(!rejected_by_dest);
5607 if network_update.is_some() {
5610 } else { panic!("Unexpected event"); }
5612 assert!(bs_failds.contains(&payment_hash_1));
5613 assert!(bs_failds.contains(&payment_hash_2));
5614 if announce_latest {
5615 assert!(bs_failds.contains(&payment_hash_4));
5617 assert!(bs_failds.contains(&payment_hash_5));
5619 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5620 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5621 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5622 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5623 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5624 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5628 fn test_fail_backwards_latest_remote_announce_a() {
5629 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5633 fn test_fail_backwards_latest_remote_announce_b() {
5634 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5638 fn test_fail_backwards_previous_remote_announce() {
5639 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5640 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5641 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5645 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5646 let chanmon_cfgs = create_chanmon_cfgs(2);
5647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5649 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5651 // Create some initial channels
5652 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5654 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5655 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5656 assert_eq!(local_txn[0].input.len(), 1);
5657 check_spends!(local_txn[0], chan_1.3);
5659 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5660 mine_transaction(&nodes[0], &local_txn[0]);
5661 check_closed_broadcast!(nodes[0], true);
5662 check_added_monitors!(nodes[0], 1);
5663 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5664 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5666 let htlc_timeout = {
5667 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5668 assert_eq!(node_txn.len(), 2);
5669 check_spends!(node_txn[0], chan_1.3);
5670 assert_eq!(node_txn[1].input.len(), 1);
5671 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5672 check_spends!(node_txn[1], local_txn[0]);
5676 mine_transaction(&nodes[0], &htlc_timeout);
5677 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5678 expect_payment_failed!(nodes[0], our_payment_hash, true);
5680 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5681 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5682 assert_eq!(spend_txn.len(), 3);
5683 check_spends!(spend_txn[0], local_txn[0]);
5684 assert_eq!(spend_txn[1].input.len(), 1);
5685 check_spends!(spend_txn[1], htlc_timeout);
5686 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5687 assert_eq!(spend_txn[2].input.len(), 2);
5688 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5689 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5690 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5694 fn test_key_derivation_params() {
5695 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5696 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5697 // let us re-derive the channel key set to then derive a delayed_payment_key.
5699 let chanmon_cfgs = create_chanmon_cfgs(3);
5701 // We manually create the node configuration to backup the seed.
5702 let seed = [42; 32];
5703 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5704 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);
5705 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, network_graph: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5706 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5707 node_cfgs.remove(0);
5708 node_cfgs.insert(0, node);
5710 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5711 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5713 // Create some initial channels
5714 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5716 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5717 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5718 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5720 // Ensure all nodes are at the same height
5721 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5722 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5723 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5724 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5726 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5727 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5728 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5729 assert_eq!(local_txn_1[0].input.len(), 1);
5730 check_spends!(local_txn_1[0], chan_1.3);
5732 // We check funding pubkey are unique
5733 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5734 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5735 if from_0_funding_key_0 == from_1_funding_key_0
5736 || from_0_funding_key_0 == from_1_funding_key_1
5737 || from_0_funding_key_1 == from_1_funding_key_0
5738 || from_0_funding_key_1 == from_1_funding_key_1 {
5739 panic!("Funding pubkeys aren't unique");
5742 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5743 mine_transaction(&nodes[0], &local_txn_1[0]);
5744 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5745 check_closed_broadcast!(nodes[0], true);
5746 check_added_monitors!(nodes[0], 1);
5747 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5749 let htlc_timeout = {
5750 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5751 assert_eq!(node_txn[1].input.len(), 1);
5752 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5753 check_spends!(node_txn[1], local_txn_1[0]);
5757 mine_transaction(&nodes[0], &htlc_timeout);
5758 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5759 expect_payment_failed!(nodes[0], our_payment_hash, true);
5761 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5762 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5763 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5764 assert_eq!(spend_txn.len(), 3);
5765 check_spends!(spend_txn[0], local_txn_1[0]);
5766 assert_eq!(spend_txn[1].input.len(), 1);
5767 check_spends!(spend_txn[1], htlc_timeout);
5768 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5769 assert_eq!(spend_txn[2].input.len(), 2);
5770 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5771 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5772 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5776 fn test_static_output_closing_tx() {
5777 let chanmon_cfgs = create_chanmon_cfgs(2);
5778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5780 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5782 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5784 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5785 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5787 mine_transaction(&nodes[0], &closing_tx);
5788 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5789 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5791 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5792 assert_eq!(spend_txn.len(), 1);
5793 check_spends!(spend_txn[0], closing_tx);
5795 mine_transaction(&nodes[1], &closing_tx);
5796 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5797 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5799 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5800 assert_eq!(spend_txn.len(), 1);
5801 check_spends!(spend_txn[0], closing_tx);
5804 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5805 let chanmon_cfgs = create_chanmon_cfgs(2);
5806 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5807 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5808 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5809 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5811 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5813 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5814 // present in B's local commitment transaction, but none of A's commitment transactions.
5815 assert!(nodes[1].node.claim_funds(payment_preimage));
5816 check_added_monitors!(nodes[1], 1);
5818 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5819 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5820 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5822 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5823 check_added_monitors!(nodes[0], 1);
5824 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5825 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5826 check_added_monitors!(nodes[1], 1);
5828 let starting_block = nodes[1].best_block_info();
5829 let mut block = Block {
5830 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5833 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5834 connect_block(&nodes[1], &block);
5835 block.header.prev_blockhash = block.block_hash();
5837 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5838 check_closed_broadcast!(nodes[1], true);
5839 check_added_monitors!(nodes[1], 1);
5840 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5843 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5844 let chanmon_cfgs = create_chanmon_cfgs(2);
5845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5847 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5848 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5850 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5851 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5852 check_added_monitors!(nodes[0], 1);
5854 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5856 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5857 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5858 // to "time out" the HTLC.
5860 let starting_block = nodes[1].best_block_info();
5861 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5863 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5864 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5865 header.prev_blockhash = header.block_hash();
5867 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5868 check_closed_broadcast!(nodes[0], true);
5869 check_added_monitors!(nodes[0], 1);
5870 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5873 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5874 let chanmon_cfgs = create_chanmon_cfgs(3);
5875 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5876 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5877 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5878 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5880 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5881 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5882 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5883 // actually revoked.
5884 let htlc_value = if use_dust { 50000 } else { 3000000 };
5885 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5886 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5887 expect_pending_htlcs_forwardable!(nodes[1]);
5888 check_added_monitors!(nodes[1], 1);
5890 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5891 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5892 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5893 check_added_monitors!(nodes[0], 1);
5894 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5895 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5896 check_added_monitors!(nodes[1], 1);
5897 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5898 check_added_monitors!(nodes[1], 1);
5899 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5901 if check_revoke_no_close {
5902 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5903 check_added_monitors!(nodes[0], 1);
5906 let starting_block = nodes[1].best_block_info();
5907 let mut block = Block {
5908 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5911 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5912 connect_block(&nodes[0], &block);
5913 block.header.prev_blockhash = block.block_hash();
5915 if !check_revoke_no_close {
5916 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5917 check_closed_broadcast!(nodes[0], true);
5918 check_added_monitors!(nodes[0], 1);
5919 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5921 let events = nodes[0].node.get_and_clear_pending_events();
5922 assert_eq!(events.len(), 2);
5923 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5924 assert_eq!(*payment_hash, our_payment_hash);
5925 } else { panic!("Unexpected event"); }
5926 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5927 assert_eq!(*payment_hash, our_payment_hash);
5928 } else { panic!("Unexpected event"); }
5932 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5933 // There are only a few cases to test here:
5934 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5935 // broadcastable commitment transactions result in channel closure,
5936 // * its included in an unrevoked-but-previous remote commitment transaction,
5937 // * its included in the latest remote or local commitment transactions.
5938 // We test each of the three possible commitment transactions individually and use both dust and
5940 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5941 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5942 // tested for at least one of the cases in other tests.
5944 fn htlc_claim_single_commitment_only_a() {
5945 do_htlc_claim_local_commitment_only(true);
5946 do_htlc_claim_local_commitment_only(false);
5948 do_htlc_claim_current_remote_commitment_only(true);
5949 do_htlc_claim_current_remote_commitment_only(false);
5953 fn htlc_claim_single_commitment_only_b() {
5954 do_htlc_claim_previous_remote_commitment_only(true, false);
5955 do_htlc_claim_previous_remote_commitment_only(false, false);
5956 do_htlc_claim_previous_remote_commitment_only(true, true);
5957 do_htlc_claim_previous_remote_commitment_only(false, true);
5962 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5963 let chanmon_cfgs = create_chanmon_cfgs(2);
5964 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5965 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5966 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5967 // Force duplicate randomness for every get-random call
5968 for node in nodes.iter() {
5969 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5972 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5973 let channel_value_satoshis=10000;
5974 let push_msat=10001;
5975 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5976 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5977 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5978 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5980 // Create a second channel with the same random values. This used to panic due to a colliding
5981 // channel_id, but now panics due to a colliding outbound SCID alias.
5982 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5986 fn bolt2_open_channel_sending_node_checks_part2() {
5987 let chanmon_cfgs = create_chanmon_cfgs(2);
5988 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5989 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5990 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5992 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5993 let channel_value_satoshis=2^24;
5994 let push_msat=10001;
5995 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5997 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5998 let channel_value_satoshis=10000;
5999 // Test when push_msat is equal to 1000 * funding_satoshis.
6000 let push_msat=1000*channel_value_satoshis+1;
6001 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6003 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6004 let channel_value_satoshis=10000;
6005 let push_msat=10001;
6006 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
6007 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6008 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6010 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6011 // 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
6012 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6014 // 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.
6015 assert!(BREAKDOWN_TIMEOUT>0);
6016 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6018 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6019 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6020 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6022 // 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.
6023 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6024 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6025 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6026 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6027 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6031 fn bolt2_open_channel_sane_dust_limit() {
6032 let chanmon_cfgs = create_chanmon_cfgs(2);
6033 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6034 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6035 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6037 let channel_value_satoshis=1000000;
6038 let push_msat=10001;
6039 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6040 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6041 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6042 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6044 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6045 let events = nodes[1].node.get_and_clear_pending_msg_events();
6046 let err_msg = match events[0] {
6047 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6050 _ => panic!("Unexpected event"),
6052 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6055 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6056 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6057 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6058 // is no longer affordable once it's freed.
6060 fn test_fail_holding_cell_htlc_upon_free() {
6061 let chanmon_cfgs = create_chanmon_cfgs(2);
6062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6064 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6065 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6067 // First nodes[0] generates an update_fee, setting the channel's
6068 // pending_update_fee.
6070 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6071 *feerate_lock += 20;
6073 nodes[0].node.timer_tick_occurred();
6074 check_added_monitors!(nodes[0], 1);
6076 let events = nodes[0].node.get_and_clear_pending_msg_events();
6077 assert_eq!(events.len(), 1);
6078 let (update_msg, commitment_signed) = match events[0] {
6079 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6080 (update_fee.as_ref(), commitment_signed)
6082 _ => panic!("Unexpected event"),
6085 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6087 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6088 let channel_reserve = chan_stat.channel_reserve_msat;
6089 let feerate = get_feerate!(nodes[0], chan.2);
6090 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6092 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6093 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6094 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6096 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6097 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6098 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6099 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6101 // Flush the pending fee update.
6102 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6103 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6104 check_added_monitors!(nodes[1], 1);
6105 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6106 check_added_monitors!(nodes[0], 1);
6108 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6109 // HTLC, but now that the fee has been raised the payment will now fail, causing
6110 // us to surface its failure to the user.
6111 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6112 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6113 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);
6114 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 {}",
6115 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6116 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6118 // Check that the payment failed to be sent out.
6119 let events = nodes[0].node.get_and_clear_pending_events();
6120 assert_eq!(events.len(), 1);
6122 &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, .. } => {
6123 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6124 assert_eq!(our_payment_hash.clone(), *payment_hash);
6125 assert_eq!(*rejected_by_dest, false);
6126 assert_eq!(*all_paths_failed, true);
6127 assert_eq!(*network_update, None);
6128 assert_eq!(*short_channel_id, None);
6129 assert_eq!(*error_code, None);
6130 assert_eq!(*error_data, None);
6132 _ => panic!("Unexpected event"),
6136 // Test that if multiple HTLCs are released from the holding cell and one is
6137 // valid but the other is no longer valid upon release, the valid HTLC can be
6138 // successfully completed while the other one fails as expected.
6140 fn test_free_and_fail_holding_cell_htlcs() {
6141 let chanmon_cfgs = create_chanmon_cfgs(2);
6142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6144 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6145 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6147 // First nodes[0] generates an update_fee, setting the channel's
6148 // pending_update_fee.
6150 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6151 *feerate_lock += 200;
6153 nodes[0].node.timer_tick_occurred();
6154 check_added_monitors!(nodes[0], 1);
6156 let events = nodes[0].node.get_and_clear_pending_msg_events();
6157 assert_eq!(events.len(), 1);
6158 let (update_msg, commitment_signed) = match events[0] {
6159 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6160 (update_fee.as_ref(), commitment_signed)
6162 _ => panic!("Unexpected event"),
6165 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6167 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6168 let channel_reserve = chan_stat.channel_reserve_msat;
6169 let feerate = get_feerate!(nodes[0], chan.2);
6170 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6172 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6174 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6175 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6176 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6178 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6179 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6180 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6181 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6182 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6183 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6184 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6186 // Flush the pending fee update.
6187 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6188 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6189 check_added_monitors!(nodes[1], 1);
6190 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6191 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6192 check_added_monitors!(nodes[0], 2);
6194 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6195 // but now that the fee has been raised the second payment will now fail, causing us
6196 // to surface its failure to the user. The first payment should succeed.
6197 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6198 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6199 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);
6200 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 {}",
6201 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6202 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6204 // Check that the second payment failed to be sent out.
6205 let events = nodes[0].node.get_and_clear_pending_events();
6206 assert_eq!(events.len(), 1);
6208 &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, .. } => {
6209 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6210 assert_eq!(payment_hash_2.clone(), *payment_hash);
6211 assert_eq!(*rejected_by_dest, false);
6212 assert_eq!(*all_paths_failed, true);
6213 assert_eq!(*network_update, None);
6214 assert_eq!(*short_channel_id, None);
6215 assert_eq!(*error_code, None);
6216 assert_eq!(*error_data, None);
6218 _ => panic!("Unexpected event"),
6221 // Complete the first payment and the RAA from the fee update.
6222 let (payment_event, send_raa_event) = {
6223 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6224 assert_eq!(msgs.len(), 2);
6225 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6227 let raa = match send_raa_event {
6228 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6229 _ => panic!("Unexpected event"),
6231 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6232 check_added_monitors!(nodes[1], 1);
6233 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6234 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6235 let events = nodes[1].node.get_and_clear_pending_events();
6236 assert_eq!(events.len(), 1);
6238 Event::PendingHTLCsForwardable { .. } => {},
6239 _ => panic!("Unexpected event"),
6241 nodes[1].node.process_pending_htlc_forwards();
6242 let events = nodes[1].node.get_and_clear_pending_events();
6243 assert_eq!(events.len(), 1);
6245 Event::PaymentReceived { .. } => {},
6246 _ => panic!("Unexpected event"),
6248 nodes[1].node.claim_funds(payment_preimage_1);
6249 check_added_monitors!(nodes[1], 1);
6250 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6251 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6252 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6253 expect_payment_sent!(nodes[0], payment_preimage_1);
6256 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6257 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6258 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6261 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6262 let chanmon_cfgs = create_chanmon_cfgs(3);
6263 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6264 // When this test was written, the default base fee floated based on the HTLC count.
6265 // It is now fixed, so we simply set the fee to the expected value here.
6266 let mut config = test_default_channel_config();
6267 config.channel_options.forwarding_fee_base_msat = 196;
6268 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6269 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6270 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6271 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6273 // First nodes[1] generates an update_fee, setting the channel's
6274 // pending_update_fee.
6276 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6277 *feerate_lock += 20;
6279 nodes[1].node.timer_tick_occurred();
6280 check_added_monitors!(nodes[1], 1);
6282 let events = nodes[1].node.get_and_clear_pending_msg_events();
6283 assert_eq!(events.len(), 1);
6284 let (update_msg, commitment_signed) = match events[0] {
6285 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6286 (update_fee.as_ref(), commitment_signed)
6288 _ => panic!("Unexpected event"),
6291 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6293 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6294 let channel_reserve = chan_stat.channel_reserve_msat;
6295 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6296 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6298 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6300 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6301 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6302 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6303 let payment_event = {
6304 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6305 check_added_monitors!(nodes[0], 1);
6307 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6308 assert_eq!(events.len(), 1);
6310 SendEvent::from_event(events.remove(0))
6312 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6313 check_added_monitors!(nodes[1], 0);
6314 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6315 expect_pending_htlcs_forwardable!(nodes[1]);
6317 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6318 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6320 // Flush the pending fee update.
6321 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6322 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6323 check_added_monitors!(nodes[2], 1);
6324 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6325 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6326 check_added_monitors!(nodes[1], 2);
6328 // A final RAA message is generated to finalize the fee update.
6329 let events = nodes[1].node.get_and_clear_pending_msg_events();
6330 assert_eq!(events.len(), 1);
6332 let raa_msg = match &events[0] {
6333 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6336 _ => panic!("Unexpected event"),
6339 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6340 check_added_monitors!(nodes[2], 1);
6341 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6343 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6344 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6345 assert_eq!(process_htlc_forwards_event.len(), 1);
6346 match &process_htlc_forwards_event[0] {
6347 &Event::PendingHTLCsForwardable { .. } => {},
6348 _ => panic!("Unexpected event"),
6351 // In response, we call ChannelManager's process_pending_htlc_forwards
6352 nodes[1].node.process_pending_htlc_forwards();
6353 check_added_monitors!(nodes[1], 1);
6355 // This causes the HTLC to be failed backwards.
6356 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6357 assert_eq!(fail_event.len(), 1);
6358 let (fail_msg, commitment_signed) = match &fail_event[0] {
6359 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6360 assert_eq!(updates.update_add_htlcs.len(), 0);
6361 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6362 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6363 assert_eq!(updates.update_fail_htlcs.len(), 1);
6364 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6366 _ => panic!("Unexpected event"),
6369 // Pass the failure messages back to nodes[0].
6370 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6371 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6373 // Complete the HTLC failure+removal process.
6374 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6375 check_added_monitors!(nodes[0], 1);
6376 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6377 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6378 check_added_monitors!(nodes[1], 2);
6379 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6380 assert_eq!(final_raa_event.len(), 1);
6381 let raa = match &final_raa_event[0] {
6382 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6383 _ => panic!("Unexpected event"),
6385 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6386 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6387 check_added_monitors!(nodes[0], 1);
6390 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6391 // 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.
6392 //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.
6395 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6396 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6397 let chanmon_cfgs = create_chanmon_cfgs(2);
6398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6401 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6403 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6404 route.paths[0][0].fee_msat = 100;
6406 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6407 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6408 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6409 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6413 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6414 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6415 let chanmon_cfgs = create_chanmon_cfgs(2);
6416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6418 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6419 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6421 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6422 route.paths[0][0].fee_msat = 0;
6423 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6424 assert_eq!(err, "Cannot send 0-msat HTLC"));
6426 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6427 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6431 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6432 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6433 let chanmon_cfgs = create_chanmon_cfgs(2);
6434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6436 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6437 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6439 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6440 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6441 check_added_monitors!(nodes[0], 1);
6442 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6443 updates.update_add_htlcs[0].amount_msat = 0;
6445 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6446 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6447 check_closed_broadcast!(nodes[1], true).unwrap();
6448 check_added_monitors!(nodes[1], 1);
6449 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6453 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6454 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6455 //It is enforced when constructing a route.
6456 let chanmon_cfgs = create_chanmon_cfgs(2);
6457 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6458 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6459 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6460 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6462 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 0);
6463 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6464 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6465 assert_eq!(err, &"Channel CLTV overflowed?"));
6469 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6470 //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.
6471 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6472 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6473 let chanmon_cfgs = create_chanmon_cfgs(2);
6474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6476 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6477 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6478 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6480 for i in 0..max_accepted_htlcs {
6481 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6482 let payment_event = {
6483 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6484 check_added_monitors!(nodes[0], 1);
6486 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6487 assert_eq!(events.len(), 1);
6488 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6489 assert_eq!(htlcs[0].htlc_id, i);
6493 SendEvent::from_event(events.remove(0))
6495 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6496 check_added_monitors!(nodes[1], 0);
6497 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6499 expect_pending_htlcs_forwardable!(nodes[1]);
6500 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6502 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6503 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6504 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6506 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6507 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6511 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6512 //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.
6513 let chanmon_cfgs = create_chanmon_cfgs(2);
6514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6516 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6517 let channel_value = 100000;
6518 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6519 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6521 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6523 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6524 // Manually create a route over our max in flight (which our router normally automatically
6526 route.paths[0][0].fee_msat = max_in_flight + 1;
6527 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6528 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6530 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6531 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);
6533 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6536 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6538 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6539 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6540 let chanmon_cfgs = create_chanmon_cfgs(2);
6541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6543 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6544 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6545 let htlc_minimum_msat: u64;
6547 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6548 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6549 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6552 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6553 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6554 check_added_monitors!(nodes[0], 1);
6555 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6556 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6557 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6558 assert!(nodes[1].node.list_channels().is_empty());
6559 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6560 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()));
6561 check_added_monitors!(nodes[1], 1);
6562 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6566 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6567 //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
6568 let chanmon_cfgs = create_chanmon_cfgs(2);
6569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6572 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6574 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6575 let channel_reserve = chan_stat.channel_reserve_msat;
6576 let feerate = get_feerate!(nodes[0], chan.2);
6577 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6578 // The 2* and +1 are for the fee spike reserve.
6579 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6581 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6582 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6583 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6584 check_added_monitors!(nodes[0], 1);
6585 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6587 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6588 // at this time channel-initiatee receivers are not required to enforce that senders
6589 // respect the fee_spike_reserve.
6590 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6593 assert!(nodes[1].node.list_channels().is_empty());
6594 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6595 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6596 check_added_monitors!(nodes[1], 1);
6597 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6601 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6602 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6603 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6604 let chanmon_cfgs = create_chanmon_cfgs(2);
6605 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6607 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6608 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6610 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6611 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6612 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6613 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6614 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6615 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6617 let mut msg = msgs::UpdateAddHTLC {
6621 payment_hash: our_payment_hash,
6622 cltv_expiry: htlc_cltv,
6623 onion_routing_packet: onion_packet.clone(),
6626 for i in 0..super::channel::OUR_MAX_HTLCS {
6627 msg.htlc_id = i as u64;
6628 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6630 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6633 assert!(nodes[1].node.list_channels().is_empty());
6634 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6635 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6636 check_added_monitors!(nodes[1], 1);
6637 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6641 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6642 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6643 let chanmon_cfgs = create_chanmon_cfgs(2);
6644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6649 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6650 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6651 check_added_monitors!(nodes[0], 1);
6652 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6653 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6654 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6656 assert!(nodes[1].node.list_channels().is_empty());
6657 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6658 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6659 check_added_monitors!(nodes[1], 1);
6660 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6664 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6665 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6666 let chanmon_cfgs = create_chanmon_cfgs(2);
6667 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6668 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6669 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6671 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6672 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6673 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6674 check_added_monitors!(nodes[0], 1);
6675 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6676 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6677 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6679 assert!(nodes[1].node.list_channels().is_empty());
6680 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6681 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6682 check_added_monitors!(nodes[1], 1);
6683 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6687 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6688 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6689 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6690 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6691 let chanmon_cfgs = create_chanmon_cfgs(2);
6692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6694 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6696 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6697 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6698 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6699 check_added_monitors!(nodes[0], 1);
6700 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6701 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703 //Disconnect and Reconnect
6704 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6705 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6706 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6707 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6708 assert_eq!(reestablish_1.len(), 1);
6709 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6710 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6711 assert_eq!(reestablish_2.len(), 1);
6712 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6713 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6714 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6715 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6718 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6719 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6720 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6721 check_added_monitors!(nodes[1], 1);
6722 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6724 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6726 assert!(nodes[1].node.list_channels().is_empty());
6727 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6728 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6729 check_added_monitors!(nodes[1], 1);
6730 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6734 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6735 //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.
6737 let chanmon_cfgs = create_chanmon_cfgs(2);
6738 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6739 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6740 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6741 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6742 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6743 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6745 check_added_monitors!(nodes[0], 1);
6746 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6747 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6749 let update_msg = msgs::UpdateFulfillHTLC{
6752 payment_preimage: our_payment_preimage,
6755 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6757 assert!(nodes[0].node.list_channels().is_empty());
6758 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6759 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()));
6760 check_added_monitors!(nodes[0], 1);
6761 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6765 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6766 //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.
6768 let chanmon_cfgs = create_chanmon_cfgs(2);
6769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6771 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6772 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6774 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6775 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6776 check_added_monitors!(nodes[0], 1);
6777 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6778 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6780 let update_msg = msgs::UpdateFailHTLC{
6783 reason: msgs::OnionErrorPacket { data: Vec::new()},
6786 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6788 assert!(nodes[0].node.list_channels().is_empty());
6789 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6790 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()));
6791 check_added_monitors!(nodes[0], 1);
6792 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6796 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6797 //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.
6799 let chanmon_cfgs = create_chanmon_cfgs(2);
6800 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6801 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6802 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6803 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6805 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6806 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6807 check_added_monitors!(nodes[0], 1);
6808 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6809 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6810 let update_msg = msgs::UpdateFailMalformedHTLC{
6813 sha256_of_onion: [1; 32],
6814 failure_code: 0x8000,
6817 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6819 assert!(nodes[0].node.list_channels().is_empty());
6820 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6821 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()));
6822 check_added_monitors!(nodes[0], 1);
6823 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6827 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6828 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6830 let chanmon_cfgs = create_chanmon_cfgs(2);
6831 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6833 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6834 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6836 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6838 nodes[1].node.claim_funds(our_payment_preimage);
6839 check_added_monitors!(nodes[1], 1);
6841 let events = nodes[1].node.get_and_clear_pending_msg_events();
6842 assert_eq!(events.len(), 1);
6843 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6845 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, .. } } => {
6846 assert!(update_add_htlcs.is_empty());
6847 assert_eq!(update_fulfill_htlcs.len(), 1);
6848 assert!(update_fail_htlcs.is_empty());
6849 assert!(update_fail_malformed_htlcs.is_empty());
6850 assert!(update_fee.is_none());
6851 update_fulfill_htlcs[0].clone()
6853 _ => panic!("Unexpected event"),
6857 update_fulfill_msg.htlc_id = 1;
6859 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6861 assert!(nodes[0].node.list_channels().is_empty());
6862 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6863 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6864 check_added_monitors!(nodes[0], 1);
6865 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6869 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6870 //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.
6872 let chanmon_cfgs = create_chanmon_cfgs(2);
6873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6875 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6876 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6878 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6880 nodes[1].node.claim_funds(our_payment_preimage);
6881 check_added_monitors!(nodes[1], 1);
6883 let events = nodes[1].node.get_and_clear_pending_msg_events();
6884 assert_eq!(events.len(), 1);
6885 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6887 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, .. } } => {
6888 assert!(update_add_htlcs.is_empty());
6889 assert_eq!(update_fulfill_htlcs.len(), 1);
6890 assert!(update_fail_htlcs.is_empty());
6891 assert!(update_fail_malformed_htlcs.is_empty());
6892 assert!(update_fee.is_none());
6893 update_fulfill_htlcs[0].clone()
6895 _ => panic!("Unexpected event"),
6899 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6901 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6903 assert!(nodes[0].node.list_channels().is_empty());
6904 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6905 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6906 check_added_monitors!(nodes[0], 1);
6907 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6911 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6912 //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.
6914 let chanmon_cfgs = create_chanmon_cfgs(2);
6915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6917 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6918 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6920 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6921 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6922 check_added_monitors!(nodes[0], 1);
6924 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6925 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6927 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6928 check_added_monitors!(nodes[1], 0);
6929 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6931 let events = nodes[1].node.get_and_clear_pending_msg_events();
6933 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6935 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, .. } } => {
6936 assert!(update_add_htlcs.is_empty());
6937 assert!(update_fulfill_htlcs.is_empty());
6938 assert!(update_fail_htlcs.is_empty());
6939 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6940 assert!(update_fee.is_none());
6941 update_fail_malformed_htlcs[0].clone()
6943 _ => panic!("Unexpected event"),
6946 update_msg.failure_code &= !0x8000;
6947 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6949 assert!(nodes[0].node.list_channels().is_empty());
6950 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6951 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6952 check_added_monitors!(nodes[0], 1);
6953 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6957 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6958 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6959 // * 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.
6961 let chanmon_cfgs = create_chanmon_cfgs(3);
6962 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6963 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6964 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6965 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6966 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6968 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6971 let mut payment_event = {
6972 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6973 check_added_monitors!(nodes[0], 1);
6974 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6975 assert_eq!(events.len(), 1);
6976 SendEvent::from_event(events.remove(0))
6978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6979 check_added_monitors!(nodes[1], 0);
6980 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6981 expect_pending_htlcs_forwardable!(nodes[1]);
6982 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6983 assert_eq!(events_2.len(), 1);
6984 check_added_monitors!(nodes[1], 1);
6985 payment_event = SendEvent::from_event(events_2.remove(0));
6986 assert_eq!(payment_event.msgs.len(), 1);
6989 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6990 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6991 check_added_monitors!(nodes[2], 0);
6992 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6994 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6995 assert_eq!(events_3.len(), 1);
6996 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6998 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6999 assert!(update_add_htlcs.is_empty());
7000 assert!(update_fulfill_htlcs.is_empty());
7001 assert!(update_fail_htlcs.is_empty());
7002 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7003 assert!(update_fee.is_none());
7004 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7006 _ => panic!("Unexpected event"),
7010 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7012 check_added_monitors!(nodes[1], 0);
7013 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7014 expect_pending_htlcs_forwardable!(nodes[1]);
7015 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7016 assert_eq!(events_4.len(), 1);
7018 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7020 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, .. } } => {
7021 assert!(update_add_htlcs.is_empty());
7022 assert!(update_fulfill_htlcs.is_empty());
7023 assert_eq!(update_fail_htlcs.len(), 1);
7024 assert!(update_fail_malformed_htlcs.is_empty());
7025 assert!(update_fee.is_none());
7027 _ => panic!("Unexpected event"),
7030 check_added_monitors!(nodes[1], 1);
7033 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7034 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7035 // 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
7036 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7038 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7039 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7042 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7043 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7045 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7047 // We route 2 dust-HTLCs between A and B
7048 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7049 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7050 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7052 // Cache one local commitment tx as previous
7053 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7055 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7056 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7057 check_added_monitors!(nodes[1], 0);
7058 expect_pending_htlcs_forwardable!(nodes[1]);
7059 check_added_monitors!(nodes[1], 1);
7061 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7062 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7063 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7064 check_added_monitors!(nodes[0], 1);
7066 // Cache one local commitment tx as lastest
7067 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7069 let events = nodes[0].node.get_and_clear_pending_msg_events();
7071 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7072 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7074 _ => panic!("Unexpected event"),
7077 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7078 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7080 _ => panic!("Unexpected event"),
7083 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7084 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7085 if announce_latest {
7086 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7088 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7091 check_closed_broadcast!(nodes[0], true);
7092 check_added_monitors!(nodes[0], 1);
7093 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7095 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7096 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7097 let events = nodes[0].node.get_and_clear_pending_events();
7098 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7099 assert_eq!(events.len(), 2);
7100 let mut first_failed = false;
7101 for event in events {
7103 Event::PaymentPathFailed { payment_hash, .. } => {
7104 if payment_hash == payment_hash_1 {
7105 assert!(!first_failed);
7106 first_failed = true;
7108 assert_eq!(payment_hash, payment_hash_2);
7111 _ => panic!("Unexpected event"),
7117 fn test_failure_delay_dust_htlc_local_commitment() {
7118 do_test_failure_delay_dust_htlc_local_commitment(true);
7119 do_test_failure_delay_dust_htlc_local_commitment(false);
7122 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7123 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7124 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7125 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7126 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7127 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7128 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7130 let chanmon_cfgs = create_chanmon_cfgs(3);
7131 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7132 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7133 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7134 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7136 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7138 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7139 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7141 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7142 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7144 // We revoked bs_commitment_tx
7146 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7147 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7150 let mut timeout_tx = Vec::new();
7152 // We fail dust-HTLC 1 by broadcast of local commitment tx
7153 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7154 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7155 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7156 expect_payment_failed!(nodes[0], dust_hash, true);
7158 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7159 check_closed_broadcast!(nodes[0], true);
7160 check_added_monitors!(nodes[0], 1);
7161 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7162 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7163 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7164 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7165 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7166 mine_transaction(&nodes[0], &timeout_tx[0]);
7167 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7168 expect_payment_failed!(nodes[0], non_dust_hash, true);
7170 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7171 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7172 check_closed_broadcast!(nodes[0], true);
7173 check_added_monitors!(nodes[0], 1);
7174 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7175 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7176 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7177 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7179 expect_payment_failed!(nodes[0], dust_hash, true);
7180 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7181 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7182 mine_transaction(&nodes[0], &timeout_tx[0]);
7183 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7184 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7185 expect_payment_failed!(nodes[0], non_dust_hash, true);
7187 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7189 let events = nodes[0].node.get_and_clear_pending_events();
7190 assert_eq!(events.len(), 2);
7193 Event::PaymentPathFailed { payment_hash, .. } => {
7194 if payment_hash == dust_hash { first = true; }
7195 else { first = false; }
7197 _ => panic!("Unexpected event"),
7200 Event::PaymentPathFailed { payment_hash, .. } => {
7201 if first { assert_eq!(payment_hash, non_dust_hash); }
7202 else { assert_eq!(payment_hash, dust_hash); }
7204 _ => panic!("Unexpected event"),
7211 fn test_sweep_outbound_htlc_failure_update() {
7212 do_test_sweep_outbound_htlc_failure_update(false, true);
7213 do_test_sweep_outbound_htlc_failure_update(false, false);
7214 do_test_sweep_outbound_htlc_failure_update(true, false);
7218 fn test_user_configurable_csv_delay() {
7219 // We test our channel constructors yield errors when we pass them absurd csv delay
7221 let mut low_our_to_self_config = UserConfig::default();
7222 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7223 let mut high_their_to_self_config = UserConfig::default();
7224 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7225 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7226 let chanmon_cfgs = create_chanmon_cfgs(2);
7227 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7228 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7229 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7231 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7232 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7233 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7234 &low_our_to_self_config, 0, 42)
7237 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())); },
7238 _ => panic!("Unexpected event"),
7240 } else { assert!(false) }
7242 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7243 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7244 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7245 open_channel.to_self_delay = 200;
7246 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7247 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7248 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7251 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())); },
7252 _ => panic!("Unexpected event"),
7254 } else { assert!(false); }
7256 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7257 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7258 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()));
7259 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7260 accept_channel.to_self_delay = 200;
7261 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7263 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7265 &ErrorAction::SendErrorMessage { ref msg } => {
7266 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()));
7267 reason_msg = msg.data.clone();
7271 } else { panic!(); }
7272 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7274 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7275 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7276 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7277 open_channel.to_self_delay = 200;
7278 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7279 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7280 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7283 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())); },
7284 _ => panic!("Unexpected event"),
7286 } else { assert!(false); }
7290 fn test_data_loss_protect() {
7291 // We want to be sure that :
7292 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7293 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7294 // * we close channel in case of detecting other being fallen behind
7295 // * we are able to claim our own outputs thanks to to_remote being static
7296 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7302 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7303 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7304 // during signing due to revoked tx
7305 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7306 let keys_manager = &chanmon_cfgs[0].keys_manager;
7309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7311 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7313 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7315 // Cache node A state before any channel update
7316 let previous_node_state = nodes[0].node.encode();
7317 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7318 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7320 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7321 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7323 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7324 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7326 // Restore node A from previous state
7327 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7328 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7329 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7330 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7331 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7332 persister = test_utils::TestPersister::new();
7333 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7335 let mut channel_monitors = HashMap::new();
7336 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7337 <(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 {
7338 keys_manager: keys_manager,
7339 fee_estimator: &fee_estimator,
7340 chain_monitor: &monitor,
7342 tx_broadcaster: &tx_broadcaster,
7343 default_config: UserConfig::default(),
7347 nodes[0].node = &node_state_0;
7348 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7349 nodes[0].chain_monitor = &monitor;
7350 nodes[0].chain_source = &chain_source;
7352 check_added_monitors!(nodes[0], 1);
7354 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7355 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7357 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7359 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7360 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7361 check_added_monitors!(nodes[0], 1);
7364 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7365 assert_eq!(node_txn.len(), 0);
7368 let mut reestablish_1 = Vec::with_capacity(1);
7369 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7370 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7371 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7372 reestablish_1.push(msg.clone());
7373 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7374 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7376 &ErrorAction::SendErrorMessage { ref msg } => {
7377 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");
7379 _ => panic!("Unexpected event!"),
7382 panic!("Unexpected event")
7386 // Check we close channel detecting A is fallen-behind
7387 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7388 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7389 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7390 check_added_monitors!(nodes[1], 1);
7392 // Check A is able to claim to_remote output
7393 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7394 assert_eq!(node_txn.len(), 1);
7395 check_spends!(node_txn[0], chan.3);
7396 assert_eq!(node_txn[0].output.len(), 2);
7397 mine_transaction(&nodes[0], &node_txn[0]);
7398 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7399 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { 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".to_string() });
7400 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7401 assert_eq!(spend_txn.len(), 1);
7402 check_spends!(spend_txn[0], node_txn[0]);
7406 fn test_check_htlc_underpaying() {
7407 // Send payment through A -> B but A is maliciously
7408 // sending a probe payment (i.e less than expected value0
7409 // to B, B should refuse payment.
7411 let chanmon_cfgs = create_chanmon_cfgs(2);
7412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7414 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7416 // Create some initial channels
7417 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7419 let scorer = test_utils::TestScorer::with_penalty(0);
7420 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7421 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7422 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();
7423 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7424 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7425 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7426 check_added_monitors!(nodes[0], 1);
7428 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7429 assert_eq!(events.len(), 1);
7430 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7431 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7432 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7434 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7435 // and then will wait a second random delay before failing the HTLC back:
7436 expect_pending_htlcs_forwardable!(nodes[1]);
7437 expect_pending_htlcs_forwardable!(nodes[1]);
7439 // Node 3 is expecting payment of 100_000 but received 10_000,
7440 // it should fail htlc like we didn't know the preimage.
7441 nodes[1].node.process_pending_htlc_forwards();
7443 let events = nodes[1].node.get_and_clear_pending_msg_events();
7444 assert_eq!(events.len(), 1);
7445 let (update_fail_htlc, commitment_signed) = match events[0] {
7446 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 } } => {
7447 assert!(update_add_htlcs.is_empty());
7448 assert!(update_fulfill_htlcs.is_empty());
7449 assert_eq!(update_fail_htlcs.len(), 1);
7450 assert!(update_fail_malformed_htlcs.is_empty());
7451 assert!(update_fee.is_none());
7452 (update_fail_htlcs[0].clone(), commitment_signed)
7454 _ => panic!("Unexpected event"),
7456 check_added_monitors!(nodes[1], 1);
7458 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7459 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7461 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7462 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7463 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7464 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7468 fn test_announce_disable_channels() {
7469 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7470 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7472 let chanmon_cfgs = create_chanmon_cfgs(2);
7473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7477 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7478 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7479 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7482 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7483 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7485 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7486 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7487 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7488 assert_eq!(msg_events.len(), 3);
7489 let mut chans_disabled = HashMap::new();
7490 for e in msg_events {
7492 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7493 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7494 // Check that each channel gets updated exactly once
7495 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7496 panic!("Generated ChannelUpdate for wrong chan!");
7499 _ => panic!("Unexpected event"),
7503 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7504 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7505 assert_eq!(reestablish_1.len(), 3);
7506 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7507 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7508 assert_eq!(reestablish_2.len(), 3);
7510 // Reestablish chan_1
7511 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7512 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7513 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7514 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7515 // Reestablish chan_2
7516 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7517 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7518 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7519 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7520 // Reestablish chan_3
7521 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7522 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7523 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7524 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7526 nodes[0].node.timer_tick_occurred();
7527 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7528 nodes[0].node.timer_tick_occurred();
7529 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7530 assert_eq!(msg_events.len(), 3);
7531 for e in msg_events {
7533 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7534 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7535 match chans_disabled.remove(&msg.contents.short_channel_id) {
7536 // Each update should have a higher timestamp than the previous one, replacing
7538 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7539 None => panic!("Generated ChannelUpdate for wrong chan!"),
7542 _ => panic!("Unexpected event"),
7545 // Check that each channel gets updated exactly once
7546 assert!(chans_disabled.is_empty());
7550 fn test_bump_penalty_txn_on_revoked_commitment() {
7551 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7552 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7554 let chanmon_cfgs = create_chanmon_cfgs(2);
7555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7557 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7559 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7561 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7562 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7563 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7565 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7566 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7567 assert_eq!(revoked_txn[0].output.len(), 4);
7568 assert_eq!(revoked_txn[0].input.len(), 1);
7569 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7570 let revoked_txid = revoked_txn[0].txid();
7572 let mut penalty_sum = 0;
7573 for outp in revoked_txn[0].output.iter() {
7574 if outp.script_pubkey.is_v0_p2wsh() {
7575 penalty_sum += outp.value;
7579 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7580 let header_114 = connect_blocks(&nodes[1], 14);
7582 // Actually revoke tx by claiming a HTLC
7583 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7584 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7585 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7586 check_added_monitors!(nodes[1], 1);
7588 // One or more justice tx should have been broadcast, check it
7592 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7593 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7594 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7595 assert_eq!(node_txn[0].output.len(), 1);
7596 check_spends!(node_txn[0], revoked_txn[0]);
7597 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7598 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7599 penalty_1 = node_txn[0].txid();
7603 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7604 connect_blocks(&nodes[1], 15);
7605 let mut penalty_2 = penalty_1;
7606 let mut feerate_2 = 0;
7608 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7609 assert_eq!(node_txn.len(), 1);
7610 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7611 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7612 assert_eq!(node_txn[0].output.len(), 1);
7613 check_spends!(node_txn[0], revoked_txn[0]);
7614 penalty_2 = node_txn[0].txid();
7615 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7616 assert_ne!(penalty_2, penalty_1);
7617 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7618 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7619 // Verify 25% bump heuristic
7620 assert!(feerate_2 * 100 >= feerate_1 * 125);
7624 assert_ne!(feerate_2, 0);
7626 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7627 connect_blocks(&nodes[1], 1);
7629 let mut feerate_3 = 0;
7631 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7632 assert_eq!(node_txn.len(), 1);
7633 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7634 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7635 assert_eq!(node_txn[0].output.len(), 1);
7636 check_spends!(node_txn[0], revoked_txn[0]);
7637 penalty_3 = node_txn[0].txid();
7638 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7639 assert_ne!(penalty_3, penalty_2);
7640 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7641 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7642 // Verify 25% bump heuristic
7643 assert!(feerate_3 * 100 >= feerate_2 * 125);
7647 assert_ne!(feerate_3, 0);
7649 nodes[1].node.get_and_clear_pending_events();
7650 nodes[1].node.get_and_clear_pending_msg_events();
7654 fn test_bump_penalty_txn_on_revoked_htlcs() {
7655 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7656 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7658 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7659 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7662 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7664 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7665 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7666 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7667 let scorer = test_utils::TestScorer::with_penalty(0);
7668 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7669 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7670 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7671 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7672 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7673 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7674 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7675 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7677 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7678 assert_eq!(revoked_local_txn[0].input.len(), 1);
7679 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7681 // Revoke local commitment tx
7682 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7684 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7685 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7686 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7687 check_closed_broadcast!(nodes[1], true);
7688 check_added_monitors!(nodes[1], 1);
7689 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7690 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7692 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7693 assert_eq!(revoked_htlc_txn.len(), 3);
7694 check_spends!(revoked_htlc_txn[1], chan.3);
7696 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7697 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7698 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7700 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7701 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7702 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7703 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7705 // Broadcast set of revoked txn on A
7706 let hash_128 = connect_blocks(&nodes[0], 40);
7707 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7708 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7709 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7710 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7711 let events = nodes[0].node.get_and_clear_pending_events();
7712 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7714 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7715 _ => panic!("Unexpected event"),
7721 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7722 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7723 // Verify claim tx are spending revoked HTLC txn
7725 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7726 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7727 // which are included in the same block (they are broadcasted because we scan the
7728 // transactions linearly and generate claims as we go, they likely should be removed in the
7730 assert_eq!(node_txn[0].input.len(), 1);
7731 check_spends!(node_txn[0], revoked_local_txn[0]);
7732 assert_eq!(node_txn[1].input.len(), 1);
7733 check_spends!(node_txn[1], revoked_local_txn[0]);
7734 assert_eq!(node_txn[2].input.len(), 1);
7735 check_spends!(node_txn[2], revoked_local_txn[0]);
7737 // Each of the three justice transactions claim a separate (single) output of the three
7738 // available, which we check here:
7739 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7740 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7741 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7743 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7744 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7746 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7747 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7748 // a remote commitment tx has already been confirmed).
7749 check_spends!(node_txn[3], chan.3);
7751 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7752 // output, checked above).
7753 assert_eq!(node_txn[4].input.len(), 2);
7754 assert_eq!(node_txn[4].output.len(), 1);
7755 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7757 first = node_txn[4].txid();
7758 // Store both feerates for later comparison
7759 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7760 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7761 penalty_txn = vec![node_txn[2].clone()];
7765 // Connect one more block to see if bumped penalty are issued for HTLC txn
7766 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7767 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7768 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7769 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7771 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7772 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7774 check_spends!(node_txn[0], revoked_local_txn[0]);
7775 check_spends!(node_txn[1], revoked_local_txn[0]);
7776 // Note that these are both bogus - they spend outputs already claimed in block 129:
7777 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7778 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7780 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7781 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7787 // Few more blocks to confirm penalty txn
7788 connect_blocks(&nodes[0], 4);
7789 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7790 let header_144 = connect_blocks(&nodes[0], 9);
7792 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7793 assert_eq!(node_txn.len(), 1);
7795 assert_eq!(node_txn[0].input.len(), 2);
7796 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7797 // Verify bumped tx is different and 25% bump heuristic
7798 assert_ne!(first, node_txn[0].txid());
7799 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7800 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7801 assert!(feerate_2 * 100 > feerate_1 * 125);
7802 let txn = vec![node_txn[0].clone()];
7806 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7807 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7808 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7809 connect_blocks(&nodes[0], 20);
7811 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7812 // We verify than no new transaction has been broadcast because previously
7813 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7814 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7815 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7816 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7817 // up bumped justice generation.
7818 assert_eq!(node_txn.len(), 0);
7821 check_closed_broadcast!(nodes[0], true);
7822 check_added_monitors!(nodes[0], 1);
7826 fn test_bump_penalty_txn_on_remote_commitment() {
7827 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7828 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7831 // Provide preimage for one
7832 // Check aggregation
7834 let chanmon_cfgs = create_chanmon_cfgs(2);
7835 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7836 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7837 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7839 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7840 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7841 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7843 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7844 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7845 assert_eq!(remote_txn[0].output.len(), 4);
7846 assert_eq!(remote_txn[0].input.len(), 1);
7847 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7849 // Claim a HTLC without revocation (provide B monitor with preimage)
7850 nodes[1].node.claim_funds(payment_preimage);
7851 mine_transaction(&nodes[1], &remote_txn[0]);
7852 check_added_monitors!(nodes[1], 2);
7853 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7855 // One or more claim tx should have been broadcast, check it
7859 let feerate_timeout;
7860 let feerate_preimage;
7862 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7863 // 9 transactions including:
7864 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7865 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7866 // 2 * HTLC-Success (one RBF bump we'll check later)
7868 assert_eq!(node_txn.len(), 8);
7869 assert_eq!(node_txn[0].input.len(), 1);
7870 assert_eq!(node_txn[6].input.len(), 1);
7871 check_spends!(node_txn[0], remote_txn[0]);
7872 check_spends!(node_txn[6], remote_txn[0]);
7873 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7874 preimage_bump = node_txn[3].clone();
7876 check_spends!(node_txn[1], chan.3);
7877 check_spends!(node_txn[2], node_txn[1]);
7878 assert_eq!(node_txn[1], node_txn[4]);
7879 assert_eq!(node_txn[2], node_txn[5]);
7881 timeout = node_txn[6].txid();
7882 let index = node_txn[6].input[0].previous_output.vout;
7883 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7884 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7886 preimage = node_txn[0].txid();
7887 let index = node_txn[0].input[0].previous_output.vout;
7888 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7889 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7893 assert_ne!(feerate_timeout, 0);
7894 assert_ne!(feerate_preimage, 0);
7896 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7897 connect_blocks(&nodes[1], 15);
7899 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7900 assert_eq!(node_txn.len(), 1);
7901 assert_eq!(node_txn[0].input.len(), 1);
7902 assert_eq!(preimage_bump.input.len(), 1);
7903 check_spends!(node_txn[0], remote_txn[0]);
7904 check_spends!(preimage_bump, remote_txn[0]);
7906 let index = preimage_bump.input[0].previous_output.vout;
7907 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7908 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7909 assert!(new_feerate * 100 > feerate_timeout * 125);
7910 assert_ne!(timeout, preimage_bump.txid());
7912 let index = node_txn[0].input[0].previous_output.vout;
7913 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7914 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7915 assert!(new_feerate * 100 > feerate_preimage * 125);
7916 assert_ne!(preimage, node_txn[0].txid());
7921 nodes[1].node.get_and_clear_pending_events();
7922 nodes[1].node.get_and_clear_pending_msg_events();
7926 fn test_counterparty_raa_skip_no_crash() {
7927 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7928 // commitment transaction, we would have happily carried on and provided them the next
7929 // commitment transaction based on one RAA forward. This would probably eventually have led to
7930 // channel closure, but it would not have resulted in funds loss. Still, our
7931 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7932 // check simply that the channel is closed in response to such an RAA, but don't check whether
7933 // we decide to punish our counterparty for revoking their funds (as we don't currently
7935 let chanmon_cfgs = create_chanmon_cfgs(2);
7936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7938 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7939 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7941 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7942 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7944 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7946 // Make signer believe we got a counterparty signature, so that it allows the revocation
7947 keys.get_enforcement_state().last_holder_commitment -= 1;
7948 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7950 // Must revoke without gaps
7951 keys.get_enforcement_state().last_holder_commitment -= 1;
7952 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7954 keys.get_enforcement_state().last_holder_commitment -= 1;
7955 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7956 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7959 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7960 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7961 check_added_monitors!(nodes[1], 1);
7962 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7966 fn test_bump_txn_sanitize_tracking_maps() {
7967 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7968 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7970 let chanmon_cfgs = create_chanmon_cfgs(2);
7971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7973 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7975 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7976 // Lock HTLC in both directions
7977 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7978 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7980 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7981 assert_eq!(revoked_local_txn[0].input.len(), 1);
7982 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7984 // Revoke local commitment tx
7985 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7987 // Broadcast set of revoked txn on A
7988 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7989 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7990 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7992 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7993 check_closed_broadcast!(nodes[0], true);
7994 check_added_monitors!(nodes[0], 1);
7995 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7997 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7998 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7999 check_spends!(node_txn[0], revoked_local_txn[0]);
8000 check_spends!(node_txn[1], revoked_local_txn[0]);
8001 check_spends!(node_txn[2], revoked_local_txn[0]);
8002 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8006 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8007 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8008 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8010 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8011 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8012 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8017 fn test_pending_claimed_htlc_no_balance_underflow() {
8018 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8019 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8020 let chanmon_cfgs = create_chanmon_cfgs(2);
8021 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8022 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8023 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8024 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8026 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8027 nodes[1].node.claim_funds(payment_preimage);
8028 check_added_monitors!(nodes[1], 1);
8029 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8031 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8032 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8033 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8034 check_added_monitors!(nodes[0], 1);
8035 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8037 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8038 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8039 // can get our balance.
8041 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8042 // the public key of the only hop. This works around ChannelDetails not showing the
8043 // almost-claimed HTLC as available balance.
8044 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8045 route.payment_params = None; // This is all wrong, but unnecessary
8046 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8047 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8048 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8050 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8054 fn test_channel_conf_timeout() {
8055 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8056 // confirm within 2016 blocks, as recommended by BOLT 2.
8057 let chanmon_cfgs = create_chanmon_cfgs(2);
8058 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8059 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8060 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8062 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8064 // The outbound node should wait forever for confirmation:
8065 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8066 // copied here instead of directly referencing the constant.
8067 connect_blocks(&nodes[0], 2016);
8068 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8070 // The inbound node should fail the channel after exactly 2016 blocks
8071 connect_blocks(&nodes[1], 2015);
8072 check_added_monitors!(nodes[1], 0);
8073 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8075 connect_blocks(&nodes[1], 1);
8076 check_added_monitors!(nodes[1], 1);
8077 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8078 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8079 assert_eq!(close_ev.len(), 1);
8081 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8082 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8083 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8085 _ => panic!("Unexpected event"),
8090 fn test_override_channel_config() {
8091 let chanmon_cfgs = create_chanmon_cfgs(2);
8092 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8093 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8094 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8096 // Node0 initiates a channel to node1 using the override config.
8097 let mut override_config = UserConfig::default();
8098 override_config.own_channel_config.our_to_self_delay = 200;
8100 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8102 // Assert the channel created by node0 is using the override config.
8103 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8104 assert_eq!(res.channel_flags, 0);
8105 assert_eq!(res.to_self_delay, 200);
8109 fn test_override_0msat_htlc_minimum() {
8110 let mut zero_config = UserConfig::default();
8111 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8112 let chanmon_cfgs = create_chanmon_cfgs(2);
8113 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8114 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8115 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8117 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8118 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8119 assert_eq!(res.htlc_minimum_msat, 1);
8121 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8122 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8123 assert_eq!(res.htlc_minimum_msat, 1);
8127 fn test_manually_accept_inbound_channel_request() {
8128 let mut manually_accept_conf = UserConfig::default();
8129 manually_accept_conf.manually_accept_inbound_channels = true;
8130 let chanmon_cfgs = create_chanmon_cfgs(2);
8131 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8132 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8133 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8135 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8136 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8138 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8140 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8141 // accepting the inbound channel request.
8142 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8144 let events = nodes[1].node.get_and_clear_pending_events();
8146 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8147 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8149 _ => panic!("Unexpected event"),
8152 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8153 assert_eq!(accept_msg_ev.len(), 1);
8155 match accept_msg_ev[0] {
8156 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8157 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8159 _ => panic!("Unexpected event"),
8162 nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8164 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8165 assert_eq!(close_msg_ev.len(), 1);
8167 let events = nodes[1].node.get_and_clear_pending_events();
8169 Event::ChannelClosed { user_channel_id, .. } => {
8170 assert_eq!(user_channel_id, 23);
8172 _ => panic!("Unexpected event"),
8177 fn test_manually_reject_inbound_channel_request() {
8178 let mut manually_accept_conf = UserConfig::default();
8179 manually_accept_conf.manually_accept_inbound_channels = true;
8180 let chanmon_cfgs = create_chanmon_cfgs(2);
8181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8183 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8185 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8186 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8188 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8190 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8191 // rejecting the inbound channel request.
8192 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8194 let events = nodes[1].node.get_and_clear_pending_events();
8196 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8197 nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8199 _ => panic!("Unexpected event"),
8202 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8203 assert_eq!(close_msg_ev.len(), 1);
8205 match close_msg_ev[0] {
8206 MessageSendEvent::HandleError { ref node_id, .. } => {
8207 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8209 _ => panic!("Unexpected event"),
8211 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8215 fn test_reject_funding_before_inbound_channel_accepted() {
8216 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8217 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8218 // the node operator before the counterparty sends a `FundingCreated` message. If a
8219 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8220 // and the channel should be closed.
8221 let mut manually_accept_conf = UserConfig::default();
8222 manually_accept_conf.manually_accept_inbound_channels = true;
8223 let chanmon_cfgs = create_chanmon_cfgs(2);
8224 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8225 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8226 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8228 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8229 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8230 let temp_channel_id = res.temporary_channel_id;
8232 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8234 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8235 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8237 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8238 nodes[1].node.get_and_clear_pending_events();
8240 // Get the `AcceptChannel` message of `nodes[1]` without calling
8241 // `ChannelManager::accept_inbound_channel`, which generates a
8242 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8243 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8244 // succeed when `nodes[0]` is passed to it.
8247 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8248 let accept_chan_msg = channel.get_accept_channel_message();
8249 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8252 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8254 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8255 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8257 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8258 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8260 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8261 assert_eq!(close_msg_ev.len(), 1);
8263 let expected_err = "FundingCreated message received before the channel was accepted";
8264 match close_msg_ev[0] {
8265 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8266 assert_eq!(msg.channel_id, temp_channel_id);
8267 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8268 assert_eq!(msg.data, expected_err);
8270 _ => panic!("Unexpected event"),
8273 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8277 fn test_can_not_accept_inbound_channel_twice() {
8278 let mut manually_accept_conf = UserConfig::default();
8279 manually_accept_conf.manually_accept_inbound_channels = true;
8280 let chanmon_cfgs = create_chanmon_cfgs(2);
8281 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8282 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8283 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8285 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8286 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8288 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8290 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8291 // accepting the inbound channel request.
8292 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8294 let events = nodes[1].node.get_and_clear_pending_events();
8296 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8297 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8298 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8300 Err(APIError::APIMisuseError { err }) => {
8301 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8303 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8304 Err(_) => panic!("Unexpected Error"),
8307 _ => panic!("Unexpected event"),
8310 // Ensure that the channel wasn't closed after attempting to accept it twice.
8311 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8312 assert_eq!(accept_msg_ev.len(), 1);
8314 match accept_msg_ev[0] {
8315 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8316 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8318 _ => panic!("Unexpected event"),
8323 fn test_can_not_accept_unknown_inbound_channel() {
8324 let chanmon_cfg = create_chanmon_cfgs(1);
8325 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8326 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8327 let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8329 let unknown_channel_id = [0; 32];
8330 let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8332 Err(APIError::ChannelUnavailable { err }) => {
8333 assert_eq!(err, "Can't accept a channel that doesn't exist");
8335 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8336 Err(_) => panic!("Unexpected Error"),
8341 fn test_simple_mpp() {
8342 // Simple test of sending a multi-path payment.
8343 let chanmon_cfgs = create_chanmon_cfgs(4);
8344 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8345 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8346 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8348 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8349 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8350 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8351 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8353 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8354 let path = route.paths[0].clone();
8355 route.paths.push(path);
8356 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8357 route.paths[0][0].short_channel_id = chan_1_id;
8358 route.paths[0][1].short_channel_id = chan_3_id;
8359 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8360 route.paths[1][0].short_channel_id = chan_2_id;
8361 route.paths[1][1].short_channel_id = chan_4_id;
8362 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8363 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8367 fn test_preimage_storage() {
8368 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8369 let chanmon_cfgs = create_chanmon_cfgs(2);
8370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8372 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8374 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8377 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8378 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8379 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8380 check_added_monitors!(nodes[0], 1);
8381 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8382 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8383 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8384 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8386 // Note that after leaving the above scope we have no knowledge of any arguments or return
8387 // values from previous calls.
8388 expect_pending_htlcs_forwardable!(nodes[1]);
8389 let events = nodes[1].node.get_and_clear_pending_events();
8390 assert_eq!(events.len(), 1);
8392 Event::PaymentReceived { ref purpose, .. } => {
8394 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8395 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8397 _ => panic!("expected PaymentPurpose::InvoicePayment")
8400 _ => panic!("Unexpected event"),
8405 #[allow(deprecated)]
8406 fn test_secret_timeout() {
8407 // Simple test of payment secret storage time outs. After
8408 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8409 let chanmon_cfgs = create_chanmon_cfgs(2);
8410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8414 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8416 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8418 // We should fail to register the same payment hash twice, at least until we've connected a
8419 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8420 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8421 assert_eq!(err, "Duplicate payment hash");
8422 } else { panic!(); }
8424 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8426 header: BlockHeader {
8428 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8429 merkle_root: Default::default(),
8430 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8434 connect_block(&nodes[1], &block);
8435 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8436 assert_eq!(err, "Duplicate payment hash");
8437 } else { panic!(); }
8439 // If we then connect the second block, we should be able to register the same payment hash
8440 // again (this time getting a new payment secret).
8441 block.header.prev_blockhash = block.header.block_hash();
8442 block.header.time += 1;
8443 connect_block(&nodes[1], &block);
8444 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8445 assert_ne!(payment_secret_1, our_payment_secret);
8448 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8449 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8450 check_added_monitors!(nodes[0], 1);
8451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8452 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8454 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8456 // Note that after leaving the above scope we have no knowledge of any arguments or return
8457 // values from previous calls.
8458 expect_pending_htlcs_forwardable!(nodes[1]);
8459 let events = nodes[1].node.get_and_clear_pending_events();
8460 assert_eq!(events.len(), 1);
8462 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8463 assert!(payment_preimage.is_none());
8464 assert_eq!(payment_secret, our_payment_secret);
8465 // We don't actually have the payment preimage with which to claim this payment!
8467 _ => panic!("Unexpected event"),
8472 fn test_bad_secret_hash() {
8473 // Simple test of unregistered payment hash/invalid payment secret handling
8474 let chanmon_cfgs = create_chanmon_cfgs(2);
8475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8477 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8479 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8481 let random_payment_hash = PaymentHash([42; 32]);
8482 let random_payment_secret = PaymentSecret([43; 32]);
8483 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8484 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8486 // All the below cases should end up being handled exactly identically, so we macro the
8487 // resulting events.
8488 macro_rules! handle_unknown_invalid_payment_data {
8490 check_added_monitors!(nodes[0], 1);
8491 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8492 let payment_event = SendEvent::from_event(events.pop().unwrap());
8493 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8494 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8496 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8497 // again to process the pending backwards-failure of the HTLC
8498 expect_pending_htlcs_forwardable!(nodes[1]);
8499 expect_pending_htlcs_forwardable!(nodes[1]);
8500 check_added_monitors!(nodes[1], 1);
8502 // We should fail the payment back
8503 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8504 match events.pop().unwrap() {
8505 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8506 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8507 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8509 _ => panic!("Unexpected event"),
8514 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8515 // Error data is the HTLC value (100,000) and current block height
8516 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8518 // Send a payment with the right payment hash but the wrong payment secret
8519 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8520 handle_unknown_invalid_payment_data!();
8521 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8523 // Send a payment with a random payment hash, but the right payment secret
8524 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8525 handle_unknown_invalid_payment_data!();
8526 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8528 // Send a payment with a random payment hash and random payment secret
8529 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8530 handle_unknown_invalid_payment_data!();
8531 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8535 fn test_update_err_monitor_lockdown() {
8536 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8537 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8538 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8540 // This scenario may happen in a watchtower setup, where watchtower process a block height
8541 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8542 // commitment at same time.
8544 let chanmon_cfgs = create_chanmon_cfgs(2);
8545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8547 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8549 // Create some initial channel
8550 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8551 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8553 // Rebalance the network to generate htlc in the two directions
8554 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8556 // Route a HTLC from node 0 to node 1 (but don't settle)
8557 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8559 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8560 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8561 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8562 let persister = test_utils::TestPersister::new();
8564 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8565 let mut w = test_utils::TestVecWriter(Vec::new());
8566 monitor.write(&mut w).unwrap();
8567 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8568 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8569 assert!(new_monitor == *monitor);
8570 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);
8571 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8574 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8575 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8576 // transaction lock time requirements here.
8577 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8578 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8580 // Try to update ChannelMonitor
8581 assert!(nodes[1].node.claim_funds(preimage));
8582 check_added_monitors!(nodes[1], 1);
8583 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8584 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8585 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8586 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8587 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8588 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8589 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8590 } else { assert!(false); }
8591 } else { assert!(false); };
8592 // Our local monitor is in-sync and hasn't processed yet timeout
8593 check_added_monitors!(nodes[0], 1);
8594 let events = nodes[0].node.get_and_clear_pending_events();
8595 assert_eq!(events.len(), 1);
8599 fn test_concurrent_monitor_claim() {
8600 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8601 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8602 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8603 // state N+1 confirms. Alice claims output from state N+1.
8605 let chanmon_cfgs = create_chanmon_cfgs(2);
8606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8608 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8610 // Create some initial channel
8611 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8612 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8614 // Rebalance the network to generate htlc in the two directions
8615 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8617 // Route a HTLC from node 0 to node 1 (but don't settle)
8618 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8620 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8621 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8622 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8623 let persister = test_utils::TestPersister::new();
8624 let watchtower_alice = {
8625 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8626 let mut w = test_utils::TestVecWriter(Vec::new());
8627 monitor.write(&mut w).unwrap();
8628 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8629 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8630 assert!(new_monitor == *monitor);
8631 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);
8632 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8635 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8636 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8637 // transaction lock time requirements here.
8638 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8639 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8641 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8643 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8644 assert_eq!(txn.len(), 2);
8648 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8649 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8650 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8651 let persister = test_utils::TestPersister::new();
8652 let watchtower_bob = {
8653 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8654 let mut w = test_utils::TestVecWriter(Vec::new());
8655 monitor.write(&mut w).unwrap();
8656 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8657 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8658 assert!(new_monitor == *monitor);
8659 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);
8660 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8663 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8664 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8666 // Route another payment to generate another update with still previous HTLC pending
8667 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8669 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8671 check_added_monitors!(nodes[1], 1);
8673 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8674 assert_eq!(updates.update_add_htlcs.len(), 1);
8675 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8676 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8677 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8678 // Watchtower Alice should already have seen the block and reject the update
8679 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8680 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8681 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8682 } else { assert!(false); }
8683 } else { assert!(false); };
8684 // Our local monitor is in-sync and hasn't processed yet timeout
8685 check_added_monitors!(nodes[0], 1);
8687 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8688 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8689 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8691 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8694 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8695 assert_eq!(txn.len(), 2);
8696 bob_state_y = txn[0].clone();
8700 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8701 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8702 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);
8704 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8705 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8706 // the onchain detection of the HTLC output
8707 assert_eq!(htlc_txn.len(), 2);
8708 check_spends!(htlc_txn[0], bob_state_y);
8709 check_spends!(htlc_txn[1], bob_state_y);
8714 fn test_pre_lockin_no_chan_closed_update() {
8715 // Test that if a peer closes a channel in response to a funding_created message we don't
8716 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8719 // Doing so would imply a channel monitor update before the initial channel monitor
8720 // registration, violating our API guarantees.
8722 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8723 // then opening a second channel with the same funding output as the first (which is not
8724 // rejected because the first channel does not exist in the ChannelManager) and closing it
8725 // before receiving funding_signed.
8726 let chanmon_cfgs = create_chanmon_cfgs(2);
8727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8731 // Create an initial channel
8732 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8733 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8734 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8735 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8736 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8738 // Move the first channel through the funding flow...
8739 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8741 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8742 check_added_monitors!(nodes[0], 0);
8744 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8745 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8746 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8747 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8748 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8752 fn test_htlc_no_detection() {
8753 // This test is a mutation to underscore the detection logic bug we had
8754 // before #653. HTLC value routed is above the remaining balance, thus
8755 // inverting HTLC and `to_remote` output. HTLC will come second and
8756 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8757 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8758 // outputs order detection for correct spending children filtring.
8760 let chanmon_cfgs = create_chanmon_cfgs(2);
8761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8763 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8765 // Create some initial channels
8766 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8768 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8769 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8770 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8771 assert_eq!(local_txn[0].input.len(), 1);
8772 assert_eq!(local_txn[0].output.len(), 3);
8773 check_spends!(local_txn[0], chan_1.3);
8775 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8776 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8777 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8778 // We deliberately connect the local tx twice as this should provoke a failure calling
8779 // this test before #653 fix.
8780 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);
8781 check_closed_broadcast!(nodes[0], true);
8782 check_added_monitors!(nodes[0], 1);
8783 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8784 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8786 let htlc_timeout = {
8787 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8788 assert_eq!(node_txn[1].input.len(), 1);
8789 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8790 check_spends!(node_txn[1], local_txn[0]);
8794 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8795 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8796 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8797 expect_payment_failed!(nodes[0], our_payment_hash, true);
8800 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8801 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8802 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8803 // Carol, Alice would be the upstream node, and Carol the downstream.)
8805 // Steps of the test:
8806 // 1) Alice sends a HTLC to Carol through Bob.
8807 // 2) Carol doesn't settle the HTLC.
8808 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8809 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8810 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8811 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8812 // 5) Carol release the preimage to Bob off-chain.
8813 // 6) Bob claims the offered output on the broadcasted commitment.
8814 let chanmon_cfgs = create_chanmon_cfgs(3);
8815 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8816 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8817 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8819 // Create some initial channels
8820 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8821 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8823 // Steps (1) and (2):
8824 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8825 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8827 // Check that Alice's commitment transaction now contains an output for this HTLC.
8828 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8829 check_spends!(alice_txn[0], chan_ab.3);
8830 assert_eq!(alice_txn[0].output.len(), 2);
8831 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8832 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8833 assert_eq!(alice_txn.len(), 2);
8835 // Steps (3) and (4):
8836 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8837 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8838 let mut force_closing_node = 0; // Alice force-closes
8839 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8840 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8841 check_closed_broadcast!(nodes[force_closing_node], true);
8842 check_added_monitors!(nodes[force_closing_node], 1);
8843 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8844 if go_onchain_before_fulfill {
8845 let txn_to_broadcast = match broadcast_alice {
8846 true => alice_txn.clone(),
8847 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8849 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8850 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8851 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8852 if broadcast_alice {
8853 check_closed_broadcast!(nodes[1], true);
8854 check_added_monitors!(nodes[1], 1);
8855 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8857 assert_eq!(bob_txn.len(), 1);
8858 check_spends!(bob_txn[0], chan_ab.3);
8862 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8863 // process of removing the HTLC from their commitment transactions.
8864 assert!(nodes[2].node.claim_funds(payment_preimage));
8865 check_added_monitors!(nodes[2], 1);
8866 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8867 assert!(carol_updates.update_add_htlcs.is_empty());
8868 assert!(carol_updates.update_fail_htlcs.is_empty());
8869 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8870 assert!(carol_updates.update_fee.is_none());
8871 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8873 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8874 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8875 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8876 if !go_onchain_before_fulfill && broadcast_alice {
8877 let events = nodes[1].node.get_and_clear_pending_msg_events();
8878 assert_eq!(events.len(), 1);
8880 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8881 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8883 _ => panic!("Unexpected event"),
8886 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8887 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8888 // Carol<->Bob's updated commitment transaction info.
8889 check_added_monitors!(nodes[1], 2);
8891 let events = nodes[1].node.get_and_clear_pending_msg_events();
8892 assert_eq!(events.len(), 2);
8893 let bob_revocation = match events[0] {
8894 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8895 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8898 _ => panic!("Unexpected event"),
8900 let bob_updates = match events[1] {
8901 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8902 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8905 _ => panic!("Unexpected event"),
8908 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8909 check_added_monitors!(nodes[2], 1);
8910 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8911 check_added_monitors!(nodes[2], 1);
8913 let events = nodes[2].node.get_and_clear_pending_msg_events();
8914 assert_eq!(events.len(), 1);
8915 let carol_revocation = match events[0] {
8916 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8917 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8920 _ => panic!("Unexpected event"),
8922 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8923 check_added_monitors!(nodes[1], 1);
8925 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8926 // here's where we put said channel's commitment tx on-chain.
8927 let mut txn_to_broadcast = alice_txn.clone();
8928 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8929 if !go_onchain_before_fulfill {
8930 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8931 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8932 // If Bob was the one to force-close, he will have already passed these checks earlier.
8933 if broadcast_alice {
8934 check_closed_broadcast!(nodes[1], true);
8935 check_added_monitors!(nodes[1], 1);
8936 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8938 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8939 if broadcast_alice {
8940 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8941 // new block being connected. The ChannelManager being notified triggers a monitor update,
8942 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8943 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8945 assert_eq!(bob_txn.len(), 3);
8946 check_spends!(bob_txn[1], chan_ab.3);
8948 assert_eq!(bob_txn.len(), 2);
8949 check_spends!(bob_txn[0], chan_ab.3);
8954 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8955 // broadcasted commitment transaction.
8957 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8958 if go_onchain_before_fulfill {
8959 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8960 assert_eq!(bob_txn.len(), 2);
8962 let script_weight = match broadcast_alice {
8963 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8964 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8966 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8967 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8968 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8969 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8970 if broadcast_alice && !go_onchain_before_fulfill {
8971 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8972 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8974 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8975 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8981 fn test_onchain_htlc_settlement_after_close() {
8982 do_test_onchain_htlc_settlement_after_close(true, true);
8983 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8984 do_test_onchain_htlc_settlement_after_close(true, false);
8985 do_test_onchain_htlc_settlement_after_close(false, false);
8989 fn test_duplicate_chan_id() {
8990 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8991 // already open we reject it and keep the old channel.
8993 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8994 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8995 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8996 // updating logic for the existing channel.
8997 let chanmon_cfgs = create_chanmon_cfgs(2);
8998 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8999 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9000 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9002 // Create an initial channel
9003 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9004 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9005 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9006 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()));
9008 // Try to create a second channel with the same temporary_channel_id as the first and check
9009 // that it is rejected.
9010 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9012 let events = nodes[1].node.get_and_clear_pending_msg_events();
9013 assert_eq!(events.len(), 1);
9015 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9016 // Technically, at this point, nodes[1] would be justified in thinking both the
9017 // first (valid) and second (invalid) channels are closed, given they both have
9018 // the same non-temporary channel_id. However, currently we do not, so we just
9019 // move forward with it.
9020 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9021 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9023 _ => panic!("Unexpected event"),
9027 // Move the first channel through the funding flow...
9028 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9030 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9031 check_added_monitors!(nodes[0], 0);
9033 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9034 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9036 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9037 assert_eq!(added_monitors.len(), 1);
9038 assert_eq!(added_monitors[0].0, funding_output);
9039 added_monitors.clear();
9041 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9043 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9044 let channel_id = funding_outpoint.to_channel_id();
9046 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9049 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9050 // Technically this is allowed by the spec, but we don't support it and there's little reason
9051 // to. Still, it shouldn't cause any other issues.
9052 open_chan_msg.temporary_channel_id = channel_id;
9053 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9055 let events = nodes[1].node.get_and_clear_pending_msg_events();
9056 assert_eq!(events.len(), 1);
9058 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9059 // Technically, at this point, nodes[1] would be justified in thinking both
9060 // channels are closed, but currently we do not, so we just move forward with it.
9061 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9062 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9064 _ => panic!("Unexpected event"),
9068 // Now try to create a second channel which has a duplicate funding output.
9069 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9070 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9071 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9072 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()));
9073 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9075 let funding_created = {
9076 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9077 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9078 let logger = test_utils::TestLogger::new();
9079 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9081 check_added_monitors!(nodes[0], 0);
9082 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9083 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9084 // still needs to be cleared here.
9085 check_added_monitors!(nodes[1], 1);
9087 // ...still, nodes[1] will reject the duplicate channel.
9089 let events = nodes[1].node.get_and_clear_pending_msg_events();
9090 assert_eq!(events.len(), 1);
9092 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9093 // Technically, at this point, nodes[1] would be justified in thinking both
9094 // channels are closed, but currently we do not, so we just move forward with it.
9095 assert_eq!(msg.channel_id, channel_id);
9096 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9098 _ => panic!("Unexpected event"),
9102 // finally, finish creating the original channel and send a payment over it to make sure
9103 // everything is functional.
9104 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9106 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9107 assert_eq!(added_monitors.len(), 1);
9108 assert_eq!(added_monitors[0].0, funding_output);
9109 added_monitors.clear();
9112 let events_4 = nodes[0].node.get_and_clear_pending_events();
9113 assert_eq!(events_4.len(), 0);
9114 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9115 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9117 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9118 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9119 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9120 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9124 fn test_error_chans_closed() {
9125 // Test that we properly handle error messages, closing appropriate channels.
9127 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9128 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9129 // we can test various edge cases around it to ensure we don't regress.
9130 let chanmon_cfgs = create_chanmon_cfgs(3);
9131 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9132 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9133 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9135 // Create some initial channels
9136 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9137 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9138 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9140 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9141 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9142 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9144 // Closing a channel from a different peer has no effect
9145 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9146 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9148 // Closing one channel doesn't impact others
9149 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9150 check_added_monitors!(nodes[0], 1);
9151 check_closed_broadcast!(nodes[0], false);
9152 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9153 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9154 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9155 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);
9156 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);
9158 // A null channel ID should close all channels
9159 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9160 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9161 check_added_monitors!(nodes[0], 2);
9162 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9163 let events = nodes[0].node.get_and_clear_pending_msg_events();
9164 assert_eq!(events.len(), 2);
9166 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9167 assert_eq!(msg.contents.flags & 2, 2);
9169 _ => panic!("Unexpected event"),
9172 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9173 assert_eq!(msg.contents.flags & 2, 2);
9175 _ => panic!("Unexpected event"),
9177 // Note that at this point users of a standard PeerHandler will end up calling
9178 // peer_disconnected with no_connection_possible set to false, duplicating the
9179 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9180 // users with their own peer handling logic. We duplicate the call here, however.
9181 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9182 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9184 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9185 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9186 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9190 fn test_invalid_funding_tx() {
9191 // Test that we properly handle invalid funding transactions sent to us from a peer.
9193 // Previously, all other major lightning implementations had failed to properly sanitize
9194 // funding transactions from their counterparties, leading to a multi-implementation critical
9195 // security vulnerability (though we always sanitized properly, we've previously had
9196 // un-released crashes in the sanitization process).
9197 let chanmon_cfgs = create_chanmon_cfgs(2);
9198 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9199 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9200 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9202 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9203 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()));
9204 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()));
9206 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9207 for output in tx.output.iter_mut() {
9208 // Make the confirmed funding transaction have a bogus script_pubkey
9209 output.script_pubkey = bitcoin::Script::new();
9212 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9213 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()));
9214 check_added_monitors!(nodes[1], 1);
9216 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()));
9217 check_added_monitors!(nodes[0], 1);
9219 let events_1 = nodes[0].node.get_and_clear_pending_events();
9220 assert_eq!(events_1.len(), 0);
9222 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9223 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9224 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9226 let expected_err = "funding tx had wrong script/value or output index";
9227 confirm_transaction_at(&nodes[1], &tx, 1);
9228 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9229 check_added_monitors!(nodes[1], 1);
9230 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9231 assert_eq!(events_2.len(), 1);
9232 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9233 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9234 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9235 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9236 } else { panic!(); }
9237 } else { panic!(); }
9238 assert_eq!(nodes[1].node.list_channels().len(), 0);
9241 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9242 // In the first version of the chain::Confirm interface, after a refactor was made to not
9243 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9244 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9245 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9246 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9247 // spending transaction until height N+1 (or greater). This was due to the way
9248 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9249 // spending transaction at the height the input transaction was confirmed at, not whether we
9250 // should broadcast a spending transaction at the current height.
9251 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9252 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9253 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9254 // until we learned about an additional block.
9256 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9257 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9258 let chanmon_cfgs = create_chanmon_cfgs(3);
9259 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9260 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9261 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9262 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9264 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9265 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9266 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9267 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9268 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9270 nodes[1].node.force_close_channel(&channel_id).unwrap();
9271 check_closed_broadcast!(nodes[1], true);
9272 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9273 check_added_monitors!(nodes[1], 1);
9274 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9275 assert_eq!(node_txn.len(), 1);
9277 let conf_height = nodes[1].best_block_info().1;
9278 if !test_height_before_timelock {
9279 connect_blocks(&nodes[1], 24 * 6);
9281 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9282 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9283 if test_height_before_timelock {
9284 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9285 // generate any events or broadcast any transactions
9286 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9287 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9289 // We should broadcast an HTLC transaction spending our funding transaction first
9290 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9291 assert_eq!(spending_txn.len(), 2);
9292 assert_eq!(spending_txn[0], node_txn[0]);
9293 check_spends!(spending_txn[1], node_txn[0]);
9294 // We should also generate a SpendableOutputs event with the to_self output (as its
9296 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9297 assert_eq!(descriptor_spend_txn.len(), 1);
9299 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9300 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9301 // additional block built on top of the current chain.
9302 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9303 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9304 expect_pending_htlcs_forwardable!(nodes[1]);
9305 check_added_monitors!(nodes[1], 1);
9307 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9308 assert!(updates.update_add_htlcs.is_empty());
9309 assert!(updates.update_fulfill_htlcs.is_empty());
9310 assert_eq!(updates.update_fail_htlcs.len(), 1);
9311 assert!(updates.update_fail_malformed_htlcs.is_empty());
9312 assert!(updates.update_fee.is_none());
9313 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9314 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9315 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9320 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9321 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9322 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9326 fn test_forwardable_regen() {
9327 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9328 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9330 // We test it for both payment receipt and payment forwarding.
9332 let chanmon_cfgs = create_chanmon_cfgs(3);
9333 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9334 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9335 let persister: test_utils::TestPersister;
9336 let new_chain_monitor: test_utils::TestChainMonitor;
9337 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9338 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9339 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9340 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9342 // First send a payment to nodes[1]
9343 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9344 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9345 check_added_monitors!(nodes[0], 1);
9347 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9348 assert_eq!(events.len(), 1);
9349 let payment_event = SendEvent::from_event(events.pop().unwrap());
9350 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9351 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9353 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9355 // Next send a payment which is forwarded by nodes[1]
9356 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9357 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9358 check_added_monitors!(nodes[0], 1);
9360 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9361 assert_eq!(events.len(), 1);
9362 let payment_event = SendEvent::from_event(events.pop().unwrap());
9363 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9364 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9366 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9368 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9370 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9371 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9372 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9374 let nodes_1_serialized = nodes[1].node.encode();
9375 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9376 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9377 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9378 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9380 persister = test_utils::TestPersister::new();
9381 let keys_manager = &chanmon_cfgs[1].keys_manager;
9382 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);
9383 nodes[1].chain_monitor = &new_chain_monitor;
9385 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9386 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9387 &mut chan_0_monitor_read, keys_manager).unwrap();
9388 assert!(chan_0_monitor_read.is_empty());
9389 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9390 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9391 &mut chan_1_monitor_read, keys_manager).unwrap();
9392 assert!(chan_1_monitor_read.is_empty());
9394 let mut nodes_1_read = &nodes_1_serialized[..];
9395 let (_, nodes_1_deserialized_tmp) = {
9396 let mut channel_monitors = HashMap::new();
9397 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9398 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9399 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9400 default_config: UserConfig::default(),
9402 fee_estimator: node_cfgs[1].fee_estimator,
9403 chain_monitor: nodes[1].chain_monitor,
9404 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9405 logger: nodes[1].logger,
9409 nodes_1_deserialized = nodes_1_deserialized_tmp;
9410 assert!(nodes_1_read.is_empty());
9412 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9413 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9414 nodes[1].node = &nodes_1_deserialized;
9415 check_added_monitors!(nodes[1], 2);
9417 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9418 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9419 // the commitment state.
9420 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9422 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9424 expect_pending_htlcs_forwardable!(nodes[1]);
9425 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9426 check_added_monitors!(nodes[1], 1);
9428 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9429 assert_eq!(events.len(), 1);
9430 let payment_event = SendEvent::from_event(events.pop().unwrap());
9431 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9432 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9433 expect_pending_htlcs_forwardable!(nodes[2]);
9434 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9436 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9437 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9441 fn test_dup_htlc_second_fail_panic() {
9442 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9443 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9444 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9445 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9446 let chanmon_cfgs = create_chanmon_cfgs(2);
9447 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9449 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9451 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9453 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9454 .with_features(InvoiceFeatures::known());
9455 let scorer = test_utils::TestScorer::with_penalty(0);
9456 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9457 let route = get_route(
9458 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
9459 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
9460 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9462 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9465 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9466 check_added_monitors!(nodes[0], 1);
9467 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9468 assert_eq!(events.len(), 1);
9469 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9470 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9471 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9473 expect_pending_htlcs_forwardable!(nodes[1]);
9474 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9477 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9478 check_added_monitors!(nodes[0], 1);
9479 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9480 assert_eq!(events.len(), 1);
9481 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9482 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9483 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9484 // At this point, nodes[1] would notice it has too much value for the payment. It will
9485 // assume the second is a privacy attack (no longer particularly relevant
9486 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9487 // the first HTLC delivered above.
9490 // Now we go fail back the first HTLC from the user end.
9491 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9492 nodes[1].node.process_pending_htlc_forwards();
9493 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9495 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9496 nodes[1].node.process_pending_htlc_forwards();
9498 check_added_monitors!(nodes[1], 1);
9499 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9500 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9502 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9503 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9504 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9506 let failure_events = nodes[0].node.get_and_clear_pending_events();
9507 assert_eq!(failure_events.len(), 2);
9508 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9509 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9513 fn test_keysend_payments_to_public_node() {
9514 let chanmon_cfgs = create_chanmon_cfgs(2);
9515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9519 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9520 let network_graph = nodes[0].network_graph;
9521 let payer_pubkey = nodes[0].node.get_our_node_id();
9522 let payee_pubkey = nodes[1].node.get_our_node_id();
9523 let route_params = RouteParameters {
9524 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9525 final_value_msat: 10000,
9526 final_cltv_expiry_delta: 40,
9528 let scorer = test_utils::TestScorer::with_penalty(0);
9529 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9530 let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9532 let test_preimage = PaymentPreimage([42; 32]);
9533 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9534 check_added_monitors!(nodes[0], 1);
9535 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9536 assert_eq!(events.len(), 1);
9537 let event = events.pop().unwrap();
9538 let path = vec![&nodes[1]];
9539 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9540 claim_payment(&nodes[0], &path, test_preimage);
9544 fn test_keysend_payments_to_private_node() {
9545 let chanmon_cfgs = create_chanmon_cfgs(2);
9546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9550 let payer_pubkey = nodes[0].node.get_our_node_id();
9551 let payee_pubkey = nodes[1].node.get_our_node_id();
9552 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9553 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9555 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9556 let route_params = RouteParameters {
9557 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9558 final_value_msat: 10000,
9559 final_cltv_expiry_delta: 40,
9561 let network_graph = nodes[0].network_graph;
9562 let first_hops = nodes[0].node.list_usable_channels();
9563 let scorer = test_utils::TestScorer::with_penalty(0);
9564 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9565 let route = find_route(
9566 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9567 nodes[0].logger, &scorer, &random_seed_bytes
9570 let test_preimage = PaymentPreimage([42; 32]);
9571 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9572 check_added_monitors!(nodes[0], 1);
9573 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9574 assert_eq!(events.len(), 1);
9575 let event = events.pop().unwrap();
9576 let path = vec![&nodes[1]];
9577 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9578 claim_payment(&nodes[0], &path, test_preimage);
9581 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9582 #[derive(Clone, Copy, PartialEq)]
9583 enum ExposureEvent {
9584 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9586 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9588 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9589 AtUpdateFeeOutbound,
9592 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9593 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9596 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9597 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9598 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9599 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9600 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9601 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9602 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9603 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9605 let chanmon_cfgs = create_chanmon_cfgs(2);
9606 let mut config = test_default_channel_config();
9607 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9610 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9612 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9613 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9614 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9615 open_channel.max_accepted_htlcs = 60;
9617 open_channel.dust_limit_satoshis = 546;
9619 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9620 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9621 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9623 let opt_anchors = false;
9625 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9628 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9629 chan.holder_dust_limit_satoshis = 546;
9633 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9634 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()));
9635 check_added_monitors!(nodes[1], 1);
9637 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()));
9638 check_added_monitors!(nodes[0], 1);
9640 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9641 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9642 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9644 let dust_buffer_feerate = {
9645 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9646 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9647 chan.get_dust_buffer_feerate(None) as u64
9649 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;
9650 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9652 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;
9653 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9655 let dust_htlc_on_counterparty_tx: u64 = 25;
9656 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9659 if dust_outbound_balance {
9660 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9661 // Outbound dust balance: 4372 sats
9662 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9663 for i in 0..dust_outbound_htlc_on_holder_tx {
9664 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9665 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9668 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9669 // Inbound dust balance: 4372 sats
9670 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9671 for _ in 0..dust_inbound_htlc_on_holder_tx {
9672 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9676 if dust_outbound_balance {
9677 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9678 // Outbound dust balance: 5000 sats
9679 for i in 0..dust_htlc_on_counterparty_tx {
9680 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9681 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9684 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9685 // Inbound dust balance: 5000 sats
9686 for _ in 0..dust_htlc_on_counterparty_tx {
9687 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9692 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9693 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9694 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 });
9695 let mut config = UserConfig::default();
9696 // With default dust exposure: 5000 sats
9698 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9699 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9700 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat)));
9702 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat)));
9704 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9705 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 });
9706 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9707 check_added_monitors!(nodes[1], 1);
9708 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9709 assert_eq!(events.len(), 1);
9710 let payment_event = SendEvent::from_event(events.remove(0));
9711 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9712 // With default dust exposure: 5000 sats
9714 // Outbound dust balance: 6399 sats
9715 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9716 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9717 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat), 1);
9719 // Outbound dust balance: 5200 sats
9720 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat), 1);
9722 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9723 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9724 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9726 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9727 *feerate_lock = *feerate_lock * 10;
9729 nodes[0].node.timer_tick_occurred();
9730 check_added_monitors!(nodes[0], 1);
9731 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);
9734 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9735 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9736 added_monitors.clear();
9740 fn test_max_dust_htlc_exposure() {
9741 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9742 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9743 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9744 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9745 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9746 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9747 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9748 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9749 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9750 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9751 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9752 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);