1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::chaininterface::LowerBoundedFeeEstimator;
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{BaseSign, KeysInterface};
21 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
23 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
24 use ln::channel::{Channel, ChannelError};
25 use ln::{chan_utils, onion_utils};
26 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
27 use routing::gossip::NetworkGraph;
28 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
29 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
31 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason, HTLCDestination};
35 use util::errors::APIError;
36 use util::ser::{Writeable, ReadableArgs};
37 use util::config::UserConfig;
39 use bitcoin::hash_types::BlockHash;
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use sync::{Arc, Mutex};
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
64 fn test_insane_channel_opens() {
65 // Stand up a network of 2 nodes
66 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
67 let mut cfg = UserConfig::default();
68 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
69 let chanmon_cfgs = create_chanmon_cfgs(2);
70 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
71 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
72 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
74 // Instantiate channel parameters where we push the maximum msats given our
76 let channel_value_sat = 31337; // same as funding satoshis
77 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
78 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
80 // Have node0 initiate a channel to node1 with aforementioned parameters
81 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
83 // Extract the channel open message from node0 to node1
84 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
86 // Test helper that asserts we get the correct error string given a mutator
87 // that supposedly makes the channel open message insane
88 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
89 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
90 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
91 assert_eq!(msg_events.len(), 1);
92 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
93 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
95 &ErrorAction::SendErrorMessage { .. } => {
96 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
98 _ => panic!("unexpected event!"),
100 } else { assert!(false); }
103 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105 // Test all mutations that would make the channel open message insane
106 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 });
107 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 });
109 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
111 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
113 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
115 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 });
117 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 });
119 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 fn test_funding_exceeds_no_wumbo_limit() {
126 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
128 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
129 let chanmon_cfgs = create_chanmon_cfgs(2);
130 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
131 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
132 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
133 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
135 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
136 Err(APIError::APIMisuseError { err }) => {
137 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
143 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
144 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
145 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
146 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
147 // in normal testing, we test it explicitly here.
148 let chanmon_cfgs = create_chanmon_cfgs(2);
149 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
150 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
151 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 // Have node0 initiate a channel to node1 with aforementioned parameters
154 let mut push_amt = 100_000_000;
155 let feerate_per_kw = 253;
156 let opt_anchors = false;
157 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
158 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
160 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();
161 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
162 if !send_from_initiator {
163 open_channel_message.channel_reserve_satoshis = 0;
164 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
166 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
168 // Extract the channel accept message from node1 to node0
169 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
170 if send_from_initiator {
171 accept_channel_message.channel_reserve_satoshis = 0;
172 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
174 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
177 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
178 chan.holder_selected_channel_reserve_satoshis = 0;
179 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
182 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
183 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
184 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
186 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
187 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
188 if send_from_initiator {
189 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
190 // Note that for outbound channels we have to consider the commitment tx fee and the
191 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
192 // well as an additional HTLC.
193 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
195 send_payment(&nodes[1], &[&nodes[0]], push_amt);
200 fn test_counterparty_no_reserve() {
201 do_test_counterparty_no_reserve(true);
202 do_test_counterparty_no_reserve(false);
206 fn test_async_inbound_update_fee() {
207 let chanmon_cfgs = create_chanmon_cfgs(2);
208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
210 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
211 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
214 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
218 // send (1) commitment_signed -.
219 // <- update_add_htlc/commitment_signed
220 // send (2) RAA (awaiting remote revoke) -.
221 // (1) commitment_signed is delivered ->
222 // .- send (3) RAA (awaiting remote revoke)
223 // (2) RAA is delivered ->
224 // .- send (4) commitment_signed
225 // <- (3) RAA is delivered
226 // send (5) commitment_signed -.
227 // <- (4) commitment_signed is delivered
229 // (5) commitment_signed is delivered ->
231 // (6) RAA is delivered ->
233 // First nodes[0] generates an update_fee
235 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
238 nodes[0].node.timer_tick_occurred();
239 check_added_monitors!(nodes[0], 1);
241 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
242 assert_eq!(events_0.len(), 1);
243 let (update_msg, commitment_signed) = match events_0[0] { // (1)
244 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
245 (update_fee.as_ref(), commitment_signed)
247 _ => panic!("Unexpected event"),
250 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
252 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
253 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
254 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
255 check_added_monitors!(nodes[1], 1);
257 let payment_event = {
258 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
259 assert_eq!(events_1.len(), 1);
260 SendEvent::from_event(events_1.remove(0))
262 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
263 assert_eq!(payment_event.msgs.len(), 1);
265 // ...now when the messages get delivered everyone should be happy
266 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
267 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
268 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
269 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
270 check_added_monitors!(nodes[0], 1);
272 // deliver(1), generate (3):
273 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
274 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
275 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
276 check_added_monitors!(nodes[1], 1);
278 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
279 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
280 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
281 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
282 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
283 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
284 assert!(bs_update.update_fee.is_none()); // (4)
285 check_added_monitors!(nodes[1], 1);
287 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
288 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
289 assert!(as_update.update_add_htlcs.is_empty()); // (5)
290 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
291 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
292 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
293 assert!(as_update.update_fee.is_none()); // (5)
294 check_added_monitors!(nodes[0], 1);
296 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
297 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
298 // only (6) so get_event_msg's assert(len == 1) passes
299 check_added_monitors!(nodes[0], 1);
301 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
302 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
303 check_added_monitors!(nodes[1], 1);
305 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
306 check_added_monitors!(nodes[0], 1);
308 let events_2 = nodes[0].node.get_and_clear_pending_events();
309 assert_eq!(events_2.len(), 1);
311 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
312 _ => panic!("Unexpected event"),
315 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
316 check_added_monitors!(nodes[1], 1);
320 fn test_update_fee_unordered_raa() {
321 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
322 // crash in an earlier version of the update_fee patch)
323 let chanmon_cfgs = create_chanmon_cfgs(2);
324 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
325 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
326 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
327 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
330 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
332 // First nodes[0] generates an update_fee
334 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
337 nodes[0].node.timer_tick_occurred();
338 check_added_monitors!(nodes[0], 1);
340 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
341 assert_eq!(events_0.len(), 1);
342 let update_msg = match events_0[0] { // (1)
343 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
346 _ => panic!("Unexpected event"),
349 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
351 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
352 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
353 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
354 check_added_monitors!(nodes[1], 1);
356 let payment_event = {
357 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
358 assert_eq!(events_1.len(), 1);
359 SendEvent::from_event(events_1.remove(0))
361 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
362 assert_eq!(payment_event.msgs.len(), 1);
364 // ...now when the messages get delivered everyone should be happy
365 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
366 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
367 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
368 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
369 check_added_monitors!(nodes[0], 1);
371 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
372 check_added_monitors!(nodes[1], 1);
374 // We can't continue, sadly, because our (1) now has a bogus signature
378 fn test_multi_flight_update_fee() {
379 let chanmon_cfgs = create_chanmon_cfgs(2);
380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
382 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
383 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
386 // update_fee/commitment_signed ->
387 // .- send (1) RAA and (2) commitment_signed
388 // update_fee (never committed) ->
390 // We have to manually generate the above update_fee, it is allowed by the protocol but we
391 // don't track which updates correspond to which revoke_and_ack responses so we're in
392 // AwaitingRAA mode and will not generate the update_fee yet.
393 // <- (1) RAA delivered
394 // (3) is generated and send (4) CS -.
395 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
396 // know the per_commitment_point to use for it.
397 // <- (2) commitment_signed delivered
399 // B should send no response here
400 // (4) commitment_signed delivered ->
401 // <- RAA/commitment_signed delivered
404 // First nodes[0] generates an update_fee
407 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
408 initial_feerate = *feerate_lock;
409 *feerate_lock = initial_feerate + 20;
411 nodes[0].node.timer_tick_occurred();
412 check_added_monitors!(nodes[0], 1);
414 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
415 assert_eq!(events_0.len(), 1);
416 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
417 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
418 (update_fee.as_ref().unwrap(), commitment_signed)
420 _ => panic!("Unexpected event"),
423 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
424 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
425 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
426 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
427 check_added_monitors!(nodes[1], 1);
429 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
432 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
433 *feerate_lock = initial_feerate + 40;
435 nodes[0].node.timer_tick_occurred();
436 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
437 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
439 // Create the (3) update_fee message that nodes[0] will generate before it does...
440 let mut update_msg_2 = msgs::UpdateFee {
441 channel_id: update_msg_1.channel_id.clone(),
442 feerate_per_kw: (initial_feerate + 30) as u32,
445 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
447 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
449 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
451 // Deliver (1), generating (3) and (4)
452 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
453 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
454 check_added_monitors!(nodes[0], 1);
455 assert!(as_second_update.update_add_htlcs.is_empty());
456 assert!(as_second_update.update_fulfill_htlcs.is_empty());
457 assert!(as_second_update.update_fail_htlcs.is_empty());
458 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
459 // Check that the update_fee newly generated matches what we delivered:
460 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
461 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
463 // Deliver (2) commitment_signed
464 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
465 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
466 check_added_monitors!(nodes[0], 1);
467 // No commitment_signed so get_event_msg's assert(len == 1) passes
469 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
470 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
471 check_added_monitors!(nodes[1], 1);
474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
475 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
476 check_added_monitors!(nodes[1], 1);
478 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
479 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
480 check_added_monitors!(nodes[0], 1);
482 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
483 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
484 // No commitment_signed so get_event_msg's assert(len == 1) passes
485 check_added_monitors!(nodes[0], 1);
487 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
488 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
489 check_added_monitors!(nodes[1], 1);
492 fn do_test_sanity_on_in_flight_opens(steps: u8) {
493 // Previously, we had issues deserializing channels when we hadn't connected the first block
494 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
495 // serialization round-trips and simply do steps towards opening a channel and then drop the
498 let chanmon_cfgs = create_chanmon_cfgs(2);
499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
503 if steps & 0b1000_0000 != 0{
505 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
508 connect_block(&nodes[0], &block);
509 connect_block(&nodes[1], &block);
512 if steps & 0x0f == 0 { return; }
513 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
514 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
516 if steps & 0x0f == 1 { return; }
517 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
518 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
520 if steps & 0x0f == 2 { return; }
521 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
523 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
525 if steps & 0x0f == 3 { return; }
526 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
527 check_added_monitors!(nodes[0], 0);
528 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
530 if steps & 0x0f == 4 { return; }
531 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
533 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
534 assert_eq!(added_monitors.len(), 1);
535 assert_eq!(added_monitors[0].0, funding_output);
536 added_monitors.clear();
538 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
540 if steps & 0x0f == 5 { return; }
541 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
543 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
544 assert_eq!(added_monitors.len(), 1);
545 assert_eq!(added_monitors[0].0, funding_output);
546 added_monitors.clear();
549 let events_4 = nodes[0].node.get_and_clear_pending_events();
550 assert_eq!(events_4.len(), 0);
552 if steps & 0x0f == 6 { return; }
553 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
555 if steps & 0x0f == 7 { return; }
556 confirm_transaction_at(&nodes[0], &tx, 2);
557 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
558 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
562 fn test_sanity_on_in_flight_opens() {
563 do_test_sanity_on_in_flight_opens(0);
564 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
565 do_test_sanity_on_in_flight_opens(1);
566 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
567 do_test_sanity_on_in_flight_opens(2);
568 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
569 do_test_sanity_on_in_flight_opens(3);
570 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
571 do_test_sanity_on_in_flight_opens(4);
572 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(5);
574 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(6);
576 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(7);
578 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(8);
580 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
584 fn test_update_fee_vanilla() {
585 let chanmon_cfgs = create_chanmon_cfgs(2);
586 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
587 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
588 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
589 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
592 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
595 nodes[0].node.timer_tick_occurred();
596 check_added_monitors!(nodes[0], 1);
598 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
599 assert_eq!(events_0.len(), 1);
600 let (update_msg, commitment_signed) = match events_0[0] {
601 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 } } => {
602 (update_fee.as_ref(), commitment_signed)
604 _ => panic!("Unexpected event"),
606 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
608 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
609 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
610 check_added_monitors!(nodes[1], 1);
612 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
613 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
614 check_added_monitors!(nodes[0], 1);
616 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
617 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
618 // No commitment_signed so get_event_msg's assert(len == 1) passes
619 check_added_monitors!(nodes[0], 1);
621 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
622 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
623 check_added_monitors!(nodes[1], 1);
627 fn test_update_fee_that_funder_cannot_afford() {
628 let chanmon_cfgs = create_chanmon_cfgs(2);
629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
632 let channel_value = 5000;
634 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
635 let channel_id = chan.2;
636 let secp_ctx = Secp256k1::new();
637 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
639 let opt_anchors = false;
641 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
642 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
643 // calculate two different feerates here - the expected local limit as well as the expected
645 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;
646 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
648 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
649 *feerate_lock = feerate;
651 nodes[0].node.timer_tick_occurred();
652 check_added_monitors!(nodes[0], 1);
653 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
655 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
657 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
659 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
661 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
663 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
664 assert_eq!(commitment_tx.output.len(), 2);
665 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
666 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
667 actual_fee = channel_value - actual_fee;
668 assert_eq!(total_fee, actual_fee);
672 // Increment the feerate by a small constant, accounting for rounding errors
673 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
676 nodes[0].node.timer_tick_occurred();
677 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
678 check_added_monitors!(nodes[0], 0);
680 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
682 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
683 // needed to sign the new commitment tx and (2) sign the new commitment tx.
684 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
685 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
686 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
687 let chan_signer = local_chan.get_signer();
688 let pubkeys = chan_signer.pubkeys();
689 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
690 pubkeys.funding_pubkey)
692 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
693 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
694 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
695 let chan_signer = remote_chan.get_signer();
696 let pubkeys = chan_signer.pubkeys();
697 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
698 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
699 pubkeys.funding_pubkey)
702 // Assemble the set of keys we can use for signatures for our commitment_signed message.
703 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
704 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
707 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
708 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
709 let local_chan_signer = local_chan.get_signer();
710 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
711 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
712 INITIAL_COMMITMENT_NUMBER - 1,
714 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
715 opt_anchors, local_funding, remote_funding,
716 commit_tx_keys.clone(),
717 non_buffer_feerate + 4,
719 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
721 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
724 let commit_signed_msg = msgs::CommitmentSigned {
727 htlc_signatures: res.1
730 let update_fee = msgs::UpdateFee {
732 feerate_per_kw: non_buffer_feerate + 4,
735 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
737 //While producing the commitment_signed response after handling a received update_fee request the
738 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
739 //Should produce and error.
740 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
741 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
742 check_added_monitors!(nodes[1], 1);
743 check_closed_broadcast!(nodes[1], true);
744 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
748 fn test_update_fee_with_fundee_update_add_htlc() {
749 let chanmon_cfgs = create_chanmon_cfgs(2);
750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
752 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
753 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
756 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
759 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
762 nodes[0].node.timer_tick_occurred();
763 check_added_monitors!(nodes[0], 1);
765 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
766 assert_eq!(events_0.len(), 1);
767 let (update_msg, commitment_signed) = match events_0[0] {
768 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 } } => {
769 (update_fee.as_ref(), commitment_signed)
771 _ => panic!("Unexpected event"),
773 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
774 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
775 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
776 check_added_monitors!(nodes[1], 1);
778 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
780 // nothing happens since node[1] is in AwaitingRemoteRevoke
781 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
783 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
784 assert_eq!(added_monitors.len(), 0);
785 added_monitors.clear();
787 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
788 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
789 // node[1] has nothing to do
791 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
792 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793 check_added_monitors!(nodes[0], 1);
795 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
796 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
797 // No commitment_signed so get_event_msg's assert(len == 1) passes
798 check_added_monitors!(nodes[0], 1);
799 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
800 check_added_monitors!(nodes[1], 1);
801 // AwaitingRemoteRevoke ends here
803 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
804 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
805 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
806 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
807 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
808 assert_eq!(commitment_update.update_fee.is_none(), true);
810 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
811 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
812 check_added_monitors!(nodes[0], 1);
813 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
815 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
816 check_added_monitors!(nodes[1], 1);
817 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
819 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
820 check_added_monitors!(nodes[1], 1);
821 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
822 // No commitment_signed so get_event_msg's assert(len == 1) passes
824 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
825 check_added_monitors!(nodes[0], 1);
826 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
828 expect_pending_htlcs_forwardable!(nodes[0]);
830 let events = nodes[0].node.get_and_clear_pending_events();
831 assert_eq!(events.len(), 1);
833 Event::PaymentReceived { .. } => { },
834 _ => panic!("Unexpected event"),
837 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
839 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
840 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
841 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
842 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
843 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
847 fn test_update_fee() {
848 let chanmon_cfgs = create_chanmon_cfgs(2);
849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
851 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
852 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
853 let channel_id = chan.2;
856 // (1) update_fee/commitment_signed ->
857 // <- (2) revoke_and_ack
858 // .- send (3) commitment_signed
859 // (4) update_fee/commitment_signed ->
860 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
861 // <- (3) commitment_signed delivered
862 // send (6) revoke_and_ack -.
863 // <- (5) deliver revoke_and_ack
864 // (6) deliver revoke_and_ack ->
865 // .- send (7) commitment_signed in response to (4)
866 // <- (7) deliver commitment_signed
869 // Create and deliver (1)...
872 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
873 feerate = *feerate_lock;
874 *feerate_lock = feerate + 20;
876 nodes[0].node.timer_tick_occurred();
877 check_added_monitors!(nodes[0], 1);
879 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
880 assert_eq!(events_0.len(), 1);
881 let (update_msg, commitment_signed) = match events_0[0] {
882 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 } } => {
883 (update_fee.as_ref(), commitment_signed)
885 _ => panic!("Unexpected event"),
887 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
889 // Generate (2) and (3):
890 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
891 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892 check_added_monitors!(nodes[1], 1);
895 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
896 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
897 check_added_monitors!(nodes[0], 1);
899 // Create and deliver (4)...
901 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
902 *feerate_lock = feerate + 30;
904 nodes[0].node.timer_tick_occurred();
905 check_added_monitors!(nodes[0], 1);
906 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
907 assert_eq!(events_0.len(), 1);
908 let (update_msg, commitment_signed) = match events_0[0] {
909 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 } } => {
910 (update_fee.as_ref(), commitment_signed)
912 _ => panic!("Unexpected event"),
915 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
916 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
917 check_added_monitors!(nodes[1], 1);
919 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
920 // No commitment_signed so get_event_msg's assert(len == 1) passes
922 // Handle (3), creating (6):
923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
924 check_added_monitors!(nodes[0], 1);
925 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
926 // No commitment_signed so get_event_msg's assert(len == 1) passes
929 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
930 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
931 check_added_monitors!(nodes[0], 1);
933 // Deliver (6), creating (7):
934 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
935 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
936 assert!(commitment_update.update_add_htlcs.is_empty());
937 assert!(commitment_update.update_fulfill_htlcs.is_empty());
938 assert!(commitment_update.update_fail_htlcs.is_empty());
939 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
940 assert!(commitment_update.update_fee.is_none());
941 check_added_monitors!(nodes[1], 1);
944 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
945 check_added_monitors!(nodes[0], 1);
946 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
947 // No commitment_signed so get_event_msg's assert(len == 1) passes
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
950 check_added_monitors!(nodes[1], 1);
951 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
953 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
954 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
955 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
956 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
957 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
961 fn fake_network_test() {
962 // Simple test which builds a network of ChannelManagers, connects them to each other, and
963 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
964 let chanmon_cfgs = create_chanmon_cfgs(4);
965 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
966 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
967 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
969 // Create some initial channels
970 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
971 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
972 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
974 // Rebalance the network a bit by relaying one payment through all the channels...
975 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
976 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
977 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
978 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
980 // Send some more payments
981 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
982 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
983 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
985 // Test failure packets
986 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
987 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
989 // Add a new channel that skips 3
990 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
993 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
994 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
995 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
996 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
997 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
998 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1000 // Do some rebalance loop payments, simultaneously
1001 let mut hops = Vec::with_capacity(3);
1002 hops.push(RouteHop {
1003 pubkey: nodes[2].node.get_our_node_id(),
1004 node_features: NodeFeatures::empty(),
1005 short_channel_id: chan_2.0.contents.short_channel_id,
1006 channel_features: ChannelFeatures::empty(),
1008 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1010 hops.push(RouteHop {
1011 pubkey: nodes[3].node.get_our_node_id(),
1012 node_features: NodeFeatures::empty(),
1013 short_channel_id: chan_3.0.contents.short_channel_id,
1014 channel_features: ChannelFeatures::empty(),
1016 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1018 hops.push(RouteHop {
1019 pubkey: nodes[1].node.get_our_node_id(),
1020 node_features: NodeFeatures::known(),
1021 short_channel_id: chan_4.0.contents.short_channel_id,
1022 channel_features: ChannelFeatures::known(),
1024 cltv_expiry_delta: TEST_FINAL_CLTV,
1026 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;
1027 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;
1028 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;
1030 let mut hops = Vec::with_capacity(3);
1031 hops.push(RouteHop {
1032 pubkey: nodes[3].node.get_our_node_id(),
1033 node_features: NodeFeatures::empty(),
1034 short_channel_id: chan_4.0.contents.short_channel_id,
1035 channel_features: ChannelFeatures::empty(),
1037 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1039 hops.push(RouteHop {
1040 pubkey: nodes[2].node.get_our_node_id(),
1041 node_features: NodeFeatures::empty(),
1042 short_channel_id: chan_3.0.contents.short_channel_id,
1043 channel_features: ChannelFeatures::empty(),
1045 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1047 hops.push(RouteHop {
1048 pubkey: nodes[1].node.get_our_node_id(),
1049 node_features: NodeFeatures::known(),
1050 short_channel_id: chan_2.0.contents.short_channel_id,
1051 channel_features: ChannelFeatures::known(),
1053 cltv_expiry_delta: TEST_FINAL_CLTV,
1055 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;
1056 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;
1057 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;
1059 // Claim the rebalances...
1060 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1061 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1063 // Close down the channels...
1064 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1065 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1066 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1067 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1068 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1069 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1070 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1071 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1072 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1073 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1074 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1075 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1079 fn holding_cell_htlc_counting() {
1080 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1081 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1082 // commitment dance rounds.
1083 let chanmon_cfgs = create_chanmon_cfgs(3);
1084 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1085 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1086 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1087 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1088 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1090 let mut payments = Vec::new();
1091 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1092 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1093 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1094 payments.push((payment_preimage, payment_hash));
1096 check_added_monitors!(nodes[1], 1);
1098 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1099 assert_eq!(events.len(), 1);
1100 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1101 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1103 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1104 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1106 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1109 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1110 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1111 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1114 // This should also be true if we try to forward a payment.
1115 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1117 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1118 check_added_monitors!(nodes[0], 1);
1121 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1122 assert_eq!(events.len(), 1);
1123 let payment_event = SendEvent::from_event(events.pop().unwrap());
1124 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1126 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1127 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1128 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1129 // fails), the second will process the resulting failure and fail the HTLC backward.
1130 expect_pending_htlcs_forwardable!(nodes[1]);
1131 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1132 check_added_monitors!(nodes[1], 1);
1134 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1135 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1136 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1138 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1140 // Now forward all the pending HTLCs and claim them back
1141 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1142 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1143 check_added_monitors!(nodes[2], 1);
1145 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1146 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1147 check_added_monitors!(nodes[1], 1);
1148 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1150 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1151 check_added_monitors!(nodes[1], 1);
1152 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1154 for ref update in as_updates.update_add_htlcs.iter() {
1155 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1157 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1158 check_added_monitors!(nodes[2], 1);
1159 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1160 check_added_monitors!(nodes[2], 1);
1161 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1163 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1164 check_added_monitors!(nodes[1], 1);
1165 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1169 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1170 check_added_monitors!(nodes[2], 1);
1172 expect_pending_htlcs_forwardable!(nodes[2]);
1174 let events = nodes[2].node.get_and_clear_pending_events();
1175 assert_eq!(events.len(), payments.len());
1176 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1178 &Event::PaymentReceived { ref payment_hash, .. } => {
1179 assert_eq!(*payment_hash, *hash);
1181 _ => panic!("Unexpected event"),
1185 for (preimage, _) in payments.drain(..) {
1186 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1189 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1193 fn duplicate_htlc_test() {
1194 // Test that we accept duplicate payment_hash HTLCs across the network and that
1195 // claiming/failing them are all separate and don't affect each other
1196 let chanmon_cfgs = create_chanmon_cfgs(6);
1197 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1198 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1199 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1201 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1202 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1203 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1204 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1205 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1206 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1208 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1210 *nodes[0].network_payment_count.borrow_mut() -= 1;
1211 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1213 *nodes[0].network_payment_count.borrow_mut() -= 1;
1214 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1216 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1217 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1218 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1222 fn test_duplicate_htlc_different_direction_onchain() {
1223 // Test that ChannelMonitor doesn't generate 2 preimage txn
1224 // when we have 2 HTLCs with same preimage that go across a node
1225 // in opposite directions, even with the same payment secret.
1226 let chanmon_cfgs = create_chanmon_cfgs(2);
1227 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1228 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1229 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1231 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1234 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1236 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1238 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1239 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1240 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1242 // Provide preimage to node 0 by claiming payment
1243 nodes[0].node.claim_funds(payment_preimage);
1244 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1245 check_added_monitors!(nodes[0], 1);
1247 // Broadcast node 1 commitment txn
1248 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1250 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1251 let mut has_both_htlcs = 0; // check htlcs match ones committed
1252 for outp in remote_txn[0].output.iter() {
1253 if outp.value == 800_000 / 1000 {
1254 has_both_htlcs += 1;
1255 } else if outp.value == 900_000 / 1000 {
1256 has_both_htlcs += 1;
1259 assert_eq!(has_both_htlcs, 2);
1261 mine_transaction(&nodes[0], &remote_txn[0]);
1262 check_added_monitors!(nodes[0], 1);
1263 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1264 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1266 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1267 assert_eq!(claim_txn.len(), 8);
1269 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1271 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1272 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1274 let bump_tx = if claim_txn[1] == claim_txn[4] {
1275 assert_eq!(claim_txn[1], claim_txn[4]);
1276 assert_eq!(claim_txn[2], claim_txn[5]);
1278 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1280 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1283 assert_eq!(claim_txn[1], claim_txn[3]);
1284 assert_eq!(claim_txn[2], claim_txn[4]);
1286 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1288 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1293 assert_eq!(claim_txn[0].input.len(), 1);
1294 assert_eq!(bump_tx.input.len(), 1);
1295 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1297 assert_eq!(claim_txn[0].input.len(), 1);
1298 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1299 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1301 assert_eq!(claim_txn[6].input.len(), 1);
1302 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1303 check_spends!(claim_txn[6], remote_txn[0]);
1304 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1306 let events = nodes[0].node.get_and_clear_pending_msg_events();
1307 assert_eq!(events.len(), 3);
1310 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1311 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1312 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1313 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1315 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, .. } } => {
1316 assert!(update_add_htlcs.is_empty());
1317 assert!(update_fail_htlcs.is_empty());
1318 assert_eq!(update_fulfill_htlcs.len(), 1);
1319 assert!(update_fail_malformed_htlcs.is_empty());
1320 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1322 _ => panic!("Unexpected event"),
1328 fn test_basic_channel_reserve() {
1329 let chanmon_cfgs = create_chanmon_cfgs(2);
1330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1335 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1336 let channel_reserve = chan_stat.channel_reserve_msat;
1338 // The 2* and +1 are for the fee spike reserve.
1339 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1340 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1341 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1342 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1344 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1346 &APIError::ChannelUnavailable{ref err} =>
1347 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1348 _ => panic!("Unexpected error variant"),
1351 _ => panic!("Unexpected error variant"),
1353 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1354 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);
1356 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1360 fn test_fee_spike_violation_fails_htlc() {
1361 let chanmon_cfgs = create_chanmon_cfgs(2);
1362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1364 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1365 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1367 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1368 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1369 let secp_ctx = Secp256k1::new();
1370 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1372 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1374 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1375 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1376 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1377 let msg = msgs::UpdateAddHTLC {
1380 amount_msat: htlc_msat,
1381 payment_hash: payment_hash,
1382 cltv_expiry: htlc_cltv,
1383 onion_routing_packet: onion_packet,
1386 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1388 // Now manually create the commitment_signed message corresponding to the update_add
1389 // nodes[0] just sent. In the code for construction of this message, "local" refers
1390 // to the sender of the message, and "remote" refers to the receiver.
1392 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1394 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1396 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1397 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1398 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1399 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1400 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1401 let chan_signer = local_chan.get_signer();
1402 // Make the signer believe we validated another commitment, so we can release the secret
1403 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1405 let pubkeys = chan_signer.pubkeys();
1406 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1407 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1408 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1409 chan_signer.pubkeys().funding_pubkey)
1411 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1412 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1413 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1414 let chan_signer = remote_chan.get_signer();
1415 let pubkeys = chan_signer.pubkeys();
1416 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1417 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1418 chan_signer.pubkeys().funding_pubkey)
1421 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1422 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1423 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1425 // Build the remote commitment transaction so we can sign it, and then later use the
1426 // signature for the commitment_signed message.
1427 let local_chan_balance = 1313;
1429 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1431 amount_msat: 3460001,
1432 cltv_expiry: htlc_cltv,
1434 transaction_output_index: Some(1),
1437 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1440 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1441 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1442 let local_chan_signer = local_chan.get_signer();
1443 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1447 local_chan.opt_anchors(), local_funding, remote_funding,
1448 commit_tx_keys.clone(),
1450 &mut vec![(accepted_htlc_info, ())],
1451 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1453 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1456 let commit_signed_msg = msgs::CommitmentSigned {
1459 htlc_signatures: res.1
1462 // Send the commitment_signed message to the nodes[1].
1463 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1464 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1466 // Send the RAA to nodes[1].
1467 let raa_msg = msgs::RevokeAndACK {
1469 per_commitment_secret: local_secret,
1470 next_per_commitment_point: next_local_point
1472 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1474 let events = nodes[1].node.get_and_clear_pending_msg_events();
1475 assert_eq!(events.len(), 1);
1476 // Make sure the HTLC failed in the way we expect.
1478 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1479 assert_eq!(update_fail_htlcs.len(), 1);
1480 update_fail_htlcs[0].clone()
1482 _ => panic!("Unexpected event"),
1484 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1485 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1487 check_added_monitors!(nodes[1], 2);
1491 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1492 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1493 // Set the fee rate for the channel very high, to the point where the fundee
1494 // sending any above-dust amount would result in a channel reserve violation.
1495 // In this test we check that we would be prevented from sending an HTLC in
1497 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1498 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1499 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1500 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1502 let opt_anchors = false;
1504 let mut push_amt = 100_000_000;
1505 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1506 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1508 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1510 // Sending exactly enough to hit the reserve amount should be accepted
1511 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1512 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1515 // However one more HTLC should be significantly over the reserve amount and fail.
1516 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1517 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1518 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1519 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1520 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);
1524 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1525 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1526 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1529 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1531 let opt_anchors = false;
1533 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1534 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1535 // transaction fee with 0 HTLCs (183 sats)).
1536 let mut push_amt = 100_000_000;
1537 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1538 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1539 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1541 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1542 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1543 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1546 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1547 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1548 let secp_ctx = Secp256k1::new();
1549 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1550 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1551 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1552 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1553 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1554 let msg = msgs::UpdateAddHTLC {
1556 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1557 amount_msat: htlc_msat,
1558 payment_hash: payment_hash,
1559 cltv_expiry: htlc_cltv,
1560 onion_routing_packet: onion_packet,
1563 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1564 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1565 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);
1566 assert_eq!(nodes[0].node.list_channels().len(), 0);
1567 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1568 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1569 check_added_monitors!(nodes[0], 1);
1570 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() });
1574 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1575 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1576 // calculating our commitment transaction fee (this was previously broken).
1577 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1578 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1584 let opt_anchors = false;
1586 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1587 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1588 // transaction fee with 0 HTLCs (183 sats)).
1589 let mut push_amt = 100_000_000;
1590 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1591 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1592 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1594 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1595 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1596 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1597 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1598 // commitment transaction fee.
1599 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1601 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1602 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1603 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1606 // One more than the dust amt should fail, however.
1607 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1608 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1609 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1613 fn test_chan_init_feerate_unaffordability() {
1614 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1615 // channel reserve and feerate requirements.
1616 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1617 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1620 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1622 let opt_anchors = false;
1624 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1626 let mut push_amt = 100_000_000;
1627 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1628 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1629 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1631 // During open, we don't have a "counterparty channel reserve" to check against, so that
1632 // requirement only comes into play on the open_channel handling side.
1633 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1634 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1635 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1636 open_channel_msg.push_msat += 1;
1637 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1639 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1640 assert_eq!(msg_events.len(), 1);
1641 match msg_events[0] {
1642 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1643 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1645 _ => panic!("Unexpected event"),
1650 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1651 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1652 // calculating our counterparty's commitment transaction fee (this was previously broken).
1653 let chanmon_cfgs = create_chanmon_cfgs(2);
1654 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1655 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1656 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1657 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1659 let payment_amt = 46000; // Dust amount
1660 // In the previous code, these first four payments would succeed.
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);
1664 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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);
1671 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1674 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1675 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1676 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1681 let chanmon_cfgs = create_chanmon_cfgs(3);
1682 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1683 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1684 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1685 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1686 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1689 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1690 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1691 let feerate = get_feerate!(nodes[0], chan.2);
1692 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1694 // Add a 2* and +1 for the fee spike reserve.
1695 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1696 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;
1697 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1699 // Add a pending HTLC.
1700 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1701 let payment_event_1 = {
1702 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1703 check_added_monitors!(nodes[0], 1);
1705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706 assert_eq!(events.len(), 1);
1707 SendEvent::from_event(events.remove(0))
1709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1711 // Attempt to trigger a channel reserve violation --> payment failure.
1712 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1713 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;
1714 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1715 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1717 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1718 let secp_ctx = Secp256k1::new();
1719 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1720 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1721 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1722 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1723 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1724 let msg = msgs::UpdateAddHTLC {
1727 amount_msat: htlc_msat + 1,
1728 payment_hash: our_payment_hash_1,
1729 cltv_expiry: htlc_cltv,
1730 onion_routing_packet: onion_packet,
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1734 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1735 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1736 assert_eq!(nodes[1].node.list_channels().len(), 1);
1737 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1738 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1739 check_added_monitors!(nodes[1], 1);
1740 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1744 fn test_inbound_outbound_capacity_is_not_zero() {
1745 let chanmon_cfgs = create_chanmon_cfgs(2);
1746 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1747 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1748 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1749 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1750 let channels0 = node_chanmgrs[0].list_channels();
1751 let channels1 = node_chanmgrs[1].list_channels();
1752 assert_eq!(channels0.len(), 1);
1753 assert_eq!(channels1.len(), 1);
1755 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1756 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1757 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1759 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1760 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1763 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1764 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1768 fn test_channel_reserve_holding_cell_htlcs() {
1769 let chanmon_cfgs = create_chanmon_cfgs(3);
1770 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1771 // When this test was written, the default base fee floated based on the HTLC count.
1772 // It is now fixed, so we simply set the fee to the expected value here.
1773 let mut config = test_default_channel_config();
1774 config.channel_config.forwarding_fee_base_msat = 239;
1775 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1776 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1777 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1778 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1780 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1781 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1783 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1784 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1786 macro_rules! expect_forward {
1788 let mut events = $node.node.get_and_clear_pending_msg_events();
1789 assert_eq!(events.len(), 1);
1790 check_added_monitors!($node, 1);
1791 let payment_event = SendEvent::from_event(events.remove(0));
1796 let feemsat = 239; // set above
1797 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1798 let feerate = get_feerate!(nodes[0], chan_1.2);
1799 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1801 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1803 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1805 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1806 .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1807 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1808 route.paths[0].last_mut().unwrap().fee_msat += 1;
1809 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1811 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1812 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)));
1813 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1814 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);
1817 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1818 // nodes[0]'s wealth
1820 let amt_msat = recv_value_0 + total_fee_msat;
1821 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1822 // Also, ensure that each payment has enough to be over the dust limit to
1823 // ensure it'll be included in each commit tx fee calculation.
1824 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1825 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1826 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1830 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1831 .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1832 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1833 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1834 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1836 let (stat01_, stat11_, stat12_, stat22_) = (
1837 get_channel_value_stat!(nodes[0], chan_1.2),
1838 get_channel_value_stat!(nodes[1], chan_1.2),
1839 get_channel_value_stat!(nodes[1], chan_2.2),
1840 get_channel_value_stat!(nodes[2], chan_2.2),
1843 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1844 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1845 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1846 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1847 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1850 // adding pending output.
1851 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1852 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1853 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1854 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1855 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1856 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1857 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1858 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1859 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1861 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1862 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1863 let amt_msat_1 = recv_value_1 + total_fee_msat;
1865 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);
1866 let payment_event_1 = {
1867 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1868 check_added_monitors!(nodes[0], 1);
1870 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1871 assert_eq!(events.len(), 1);
1872 SendEvent::from_event(events.remove(0))
1874 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1876 // channel reserve test with htlc pending output > 0
1877 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1879 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1880 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1881 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1882 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1885 // split the rest to test holding cell
1886 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1887 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1888 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1889 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1891 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1892 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);
1895 // now see if they go through on both sides
1896 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);
1897 // but this will stuck in the holding cell
1898 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1899 check_added_monitors!(nodes[0], 0);
1900 let events = nodes[0].node.get_and_clear_pending_events();
1901 assert_eq!(events.len(), 0);
1903 // test with outbound holding cell amount > 0
1905 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1906 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1907 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1908 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1909 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);
1912 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);
1913 // this will also stuck in the holding cell
1914 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1915 check_added_monitors!(nodes[0], 0);
1916 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1917 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919 // flush the pending htlc
1920 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1921 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1922 check_added_monitors!(nodes[1], 1);
1924 // the pending htlc should be promoted to committed
1925 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1926 check_added_monitors!(nodes[0], 1);
1927 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1929 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1930 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1931 // No commitment_signed so get_event_msg's assert(len == 1) passes
1932 check_added_monitors!(nodes[0], 1);
1934 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1935 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1936 check_added_monitors!(nodes[1], 1);
1938 expect_pending_htlcs_forwardable!(nodes[1]);
1940 let ref payment_event_11 = expect_forward!(nodes[1]);
1941 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1942 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1944 expect_pending_htlcs_forwardable!(nodes[2]);
1945 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1947 // flush the htlcs in the holding cell
1948 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1949 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1951 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1952 expect_pending_htlcs_forwardable!(nodes[1]);
1954 let ref payment_event_3 = expect_forward!(nodes[1]);
1955 assert_eq!(payment_event_3.msgs.len(), 2);
1956 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1957 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1959 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1960 expect_pending_htlcs_forwardable!(nodes[2]);
1962 let events = nodes[2].node.get_and_clear_pending_events();
1963 assert_eq!(events.len(), 2);
1965 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1966 assert_eq!(our_payment_hash_21, *payment_hash);
1967 assert_eq!(recv_value_21, amount_msat);
1969 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1970 assert!(payment_preimage.is_none());
1971 assert_eq!(our_payment_secret_21, *payment_secret);
1973 _ => panic!("expected PaymentPurpose::InvoicePayment")
1976 _ => panic!("Unexpected event"),
1979 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1980 assert_eq!(our_payment_hash_22, *payment_hash);
1981 assert_eq!(recv_value_22, amount_msat);
1983 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1984 assert!(payment_preimage.is_none());
1985 assert_eq!(our_payment_secret_22, *payment_secret);
1987 _ => panic!("expected PaymentPurpose::InvoicePayment")
1990 _ => panic!("Unexpected event"),
1993 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1994 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1995 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1997 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1998 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1999 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2001 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2002 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);
2003 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2004 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2005 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2007 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2008 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2012 fn channel_reserve_in_flight_removes() {
2013 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2014 // can send to its counterparty, but due to update ordering, the other side may not yet have
2015 // considered those HTLCs fully removed.
2016 // This tests that we don't count HTLCs which will not be included in the next remote
2017 // commitment transaction towards the reserve value (as it implies no commitment transaction
2018 // will be generated which violates the remote reserve value).
2019 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2021 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2022 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2023 // you only consider the value of the first HTLC, it may not),
2024 // * start routing a third HTLC from A to B,
2025 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2026 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2027 // * deliver the first fulfill from B
2028 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2030 // * deliver A's response CS and RAA.
2031 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2032 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2033 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2034 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2035 let chanmon_cfgs = create_chanmon_cfgs(2);
2036 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2037 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2038 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2039 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2041 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2042 // Route the first two HTLCs.
2043 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2044 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2045 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2047 // Start routing the third HTLC (this is just used to get everyone in the right state).
2048 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2050 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2051 check_added_monitors!(nodes[0], 1);
2052 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2053 assert_eq!(events.len(), 1);
2054 SendEvent::from_event(events.remove(0))
2057 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2058 // initial fulfill/CS.
2059 nodes[1].node.claim_funds(payment_preimage_1);
2060 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2061 check_added_monitors!(nodes[1], 1);
2062 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2064 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2065 // remove the second HTLC when we send the HTLC back from B to A.
2066 nodes[1].node.claim_funds(payment_preimage_2);
2067 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2068 check_added_monitors!(nodes[1], 1);
2069 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2071 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2072 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2073 check_added_monitors!(nodes[0], 1);
2074 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2075 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2077 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2078 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2079 check_added_monitors!(nodes[1], 1);
2080 // B is already AwaitingRAA, so cant generate a CS here
2081 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2083 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2084 check_added_monitors!(nodes[1], 1);
2085 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2087 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2088 check_added_monitors!(nodes[0], 1);
2089 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2091 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2092 check_added_monitors!(nodes[1], 1);
2093 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2095 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2096 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2097 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2098 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2099 // on-chain as necessary).
2100 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2101 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2102 check_added_monitors!(nodes[0], 1);
2103 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2104 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2106 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2107 check_added_monitors!(nodes[1], 1);
2108 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2110 expect_pending_htlcs_forwardable!(nodes[1]);
2111 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2113 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2114 // resolve the second HTLC from A's point of view.
2115 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2116 check_added_monitors!(nodes[0], 1);
2117 expect_payment_path_successful!(nodes[0]);
2118 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2120 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2121 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2122 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2124 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2125 check_added_monitors!(nodes[1], 1);
2126 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2127 assert_eq!(events.len(), 1);
2128 SendEvent::from_event(events.remove(0))
2131 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2132 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2133 check_added_monitors!(nodes[0], 1);
2134 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2136 // Now just resolve all the outstanding messages/HTLCs for completeness...
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[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2143 check_added_monitors!(nodes[1], 1);
2145 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2146 check_added_monitors!(nodes[0], 1);
2147 expect_payment_path_successful!(nodes[0]);
2148 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2150 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2151 check_added_monitors!(nodes[1], 1);
2152 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2154 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2155 check_added_monitors!(nodes[0], 1);
2157 expect_pending_htlcs_forwardable!(nodes[0]);
2158 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2160 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2161 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2165 fn channel_monitor_network_test() {
2166 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2167 // tests that ChannelMonitor is able to recover from various states.
2168 let chanmon_cfgs = create_chanmon_cfgs(5);
2169 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2170 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2171 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2173 // Create some initial channels
2174 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2175 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2176 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2177 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2179 // Make sure all nodes are at the same starting height
2180 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2181 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2182 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2183 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2184 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2186 // Rebalance the network a bit by relaying one payment through all the channels...
2187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2189 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2190 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2192 // Simple case with no pending HTLCs:
2193 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2194 check_added_monitors!(nodes[1], 1);
2195 check_closed_broadcast!(nodes[1], true);
2197 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2198 assert_eq!(node_txn.len(), 1);
2199 mine_transaction(&nodes[0], &node_txn[0]);
2200 check_added_monitors!(nodes[0], 1);
2201 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2203 check_closed_broadcast!(nodes[0], true);
2204 assert_eq!(nodes[0].node.list_channels().len(), 0);
2205 assert_eq!(nodes[1].node.list_channels().len(), 1);
2206 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2207 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2209 // One pending HTLC is discarded by the force-close:
2210 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2212 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2213 // broadcasted until we reach the timelock time).
2214 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2215 check_closed_broadcast!(nodes[1], true);
2216 check_added_monitors!(nodes[1], 1);
2218 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2219 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2220 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2221 mine_transaction(&nodes[2], &node_txn[0]);
2222 check_added_monitors!(nodes[2], 1);
2223 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2225 check_closed_broadcast!(nodes[2], true);
2226 assert_eq!(nodes[1].node.list_channels().len(), 0);
2227 assert_eq!(nodes[2].node.list_channels().len(), 1);
2228 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2229 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2231 macro_rules! claim_funds {
2232 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2234 $node.node.claim_funds($preimage);
2235 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2236 check_added_monitors!($node, 1);
2238 let events = $node.node.get_and_clear_pending_msg_events();
2239 assert_eq!(events.len(), 1);
2241 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2242 assert!(update_add_htlcs.is_empty());
2243 assert!(update_fail_htlcs.is_empty());
2244 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2246 _ => panic!("Unexpected event"),
2252 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2253 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2254 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2255 check_added_monitors!(nodes[2], 1);
2256 check_closed_broadcast!(nodes[2], true);
2257 let node2_commitment_txid;
2259 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2260 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2261 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2262 node2_commitment_txid = node_txn[0].txid();
2264 // Claim the payment on nodes[3], giving it knowledge of the preimage
2265 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2266 mine_transaction(&nodes[3], &node_txn[0]);
2267 check_added_monitors!(nodes[3], 1);
2268 check_preimage_claim(&nodes[3], &node_txn);
2270 check_closed_broadcast!(nodes[3], true);
2271 assert_eq!(nodes[2].node.list_channels().len(), 0);
2272 assert_eq!(nodes[3].node.list_channels().len(), 1);
2273 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2274 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2276 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2277 // confusing us in the following tests.
2278 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2280 // One pending HTLC to time out:
2281 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2282 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2285 let (close_chan_update_1, close_chan_update_2) = {
2286 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2287 let events = nodes[3].node.get_and_clear_pending_msg_events();
2288 assert_eq!(events.len(), 2);
2289 let close_chan_update_1 = match events[0] {
2290 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2293 _ => panic!("Unexpected event"),
2296 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2297 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2299 _ => panic!("Unexpected event"),
2301 check_added_monitors!(nodes[3], 1);
2303 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2305 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2306 node_txn.retain(|tx| {
2307 if tx.input[0].previous_output.txid == node2_commitment_txid {
2313 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2315 // Claim the payment on nodes[4], giving it knowledge of the preimage
2316 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2318 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2319 let events = nodes[4].node.get_and_clear_pending_msg_events();
2320 assert_eq!(events.len(), 2);
2321 let close_chan_update_2 = match events[0] {
2322 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2325 _ => panic!("Unexpected event"),
2328 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2329 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2331 _ => panic!("Unexpected event"),
2333 check_added_monitors!(nodes[4], 1);
2334 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2336 mine_transaction(&nodes[4], &node_txn[0]);
2337 check_preimage_claim(&nodes[4], &node_txn);
2338 (close_chan_update_1, close_chan_update_2)
2340 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2341 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2342 assert_eq!(nodes[3].node.list_channels().len(), 0);
2343 assert_eq!(nodes[4].node.list_channels().len(), 0);
2345 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2346 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2347 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2351 fn test_justice_tx() {
2352 // Test justice txn built on revoked HTLC-Success tx, against both sides
2353 let mut alice_config = UserConfig::default();
2354 alice_config.channel_handshake_config.announced_channel = true;
2355 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2356 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2357 let mut bob_config = UserConfig::default();
2358 bob_config.channel_handshake_config.announced_channel = true;
2359 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2360 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2361 let user_cfgs = [Some(alice_config), Some(bob_config)];
2362 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2363 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2364 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2367 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2368 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2369 // Create some new channels:
2370 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2372 // A pending HTLC which will be revoked:
2373 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2374 // Get the will-be-revoked local txn from nodes[0]
2375 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2376 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2377 assert_eq!(revoked_local_txn[0].input.len(), 1);
2378 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2379 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2380 assert_eq!(revoked_local_txn[1].input.len(), 1);
2381 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2382 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2383 // Revoke the old state
2384 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2387 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2389 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2390 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2391 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2393 check_spends!(node_txn[0], revoked_local_txn[0]);
2394 node_txn.swap_remove(0);
2395 node_txn.truncate(1);
2397 check_added_monitors!(nodes[1], 1);
2398 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2399 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2401 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2402 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2403 // Verify broadcast of revoked HTLC-timeout
2404 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2405 check_added_monitors!(nodes[0], 1);
2406 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2407 // Broadcast revoked HTLC-timeout on node 1
2408 mine_transaction(&nodes[1], &node_txn[1]);
2409 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2411 get_announce_close_broadcast_events(&nodes, 0, 1);
2413 assert_eq!(nodes[0].node.list_channels().len(), 0);
2414 assert_eq!(nodes[1].node.list_channels().len(), 0);
2416 // We test justice_tx build by A on B's revoked HTLC-Success tx
2417 // Create some new channels:
2418 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2420 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2424 // A pending HTLC which will be revoked:
2425 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2426 // Get the will-be-revoked local txn from B
2427 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2428 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2429 assert_eq!(revoked_local_txn[0].input.len(), 1);
2430 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2431 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2432 // Revoke the old state
2433 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2435 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2437 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2438 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2439 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2441 check_spends!(node_txn[0], revoked_local_txn[0]);
2442 node_txn.swap_remove(0);
2444 check_added_monitors!(nodes[0], 1);
2445 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2447 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2448 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2449 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2450 check_added_monitors!(nodes[1], 1);
2451 mine_transaction(&nodes[0], &node_txn[1]);
2452 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2453 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2455 get_announce_close_broadcast_events(&nodes, 0, 1);
2456 assert_eq!(nodes[0].node.list_channels().len(), 0);
2457 assert_eq!(nodes[1].node.list_channels().len(), 0);
2461 fn revoked_output_claim() {
2462 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2463 // transaction is broadcast by its counterparty
2464 let chanmon_cfgs = create_chanmon_cfgs(2);
2465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2467 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2469 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2470 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2471 assert_eq!(revoked_local_txn.len(), 1);
2472 // Only output is the full channel value back to nodes[0]:
2473 assert_eq!(revoked_local_txn[0].output.len(), 1);
2474 // Send a payment through, updating everyone's latest commitment txn
2475 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2477 // Inform nodes[1] that nodes[0] broadcast a stale tx
2478 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2479 check_added_monitors!(nodes[1], 1);
2480 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2481 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2482 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2484 check_spends!(node_txn[0], revoked_local_txn[0]);
2485 check_spends!(node_txn[1], chan_1.3);
2487 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2488 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2489 get_announce_close_broadcast_events(&nodes, 0, 1);
2490 check_added_monitors!(nodes[0], 1);
2491 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2495 fn claim_htlc_outputs_shared_tx() {
2496 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2497 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2498 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2503 // Create some new channel:
2504 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2506 // Rebalance the network to generate htlc in the two directions
2507 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2508 // 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
2509 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2510 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2512 // Get the will-be-revoked local txn from node[0]
2513 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2514 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2515 assert_eq!(revoked_local_txn[0].input.len(), 1);
2516 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2517 assert_eq!(revoked_local_txn[1].input.len(), 1);
2518 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2519 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2520 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2522 //Revoke the old state
2523 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2526 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2527 check_added_monitors!(nodes[0], 1);
2528 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2529 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2530 check_added_monitors!(nodes[1], 1);
2531 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2532 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2533 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2535 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2536 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2538 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2539 check_spends!(node_txn[0], revoked_local_txn[0]);
2541 let mut witness_lens = BTreeSet::new();
2542 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2543 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2544 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2545 assert_eq!(witness_lens.len(), 3);
2546 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2547 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2548 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2550 // Next nodes[1] broadcasts its current local tx state:
2551 assert_eq!(node_txn[1].input.len(), 1);
2552 check_spends!(node_txn[1], chan_1.3);
2554 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2555 // ANTI_REORG_DELAY confirmations.
2556 mine_transaction(&nodes[1], &node_txn[0]);
2557 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2558 expect_payment_failed!(nodes[1], payment_hash_2, true);
2560 get_announce_close_broadcast_events(&nodes, 0, 1);
2561 assert_eq!(nodes[0].node.list_channels().len(), 0);
2562 assert_eq!(nodes[1].node.list_channels().len(), 0);
2566 fn claim_htlc_outputs_single_tx() {
2567 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2568 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2569 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2572 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2574 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2576 // Rebalance the network to generate htlc in the two directions
2577 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2578 // 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
2579 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2580 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2581 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2583 // Get the will-be-revoked local txn from node[0]
2584 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2586 //Revoke the old state
2587 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2590 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2591 check_added_monitors!(nodes[0], 1);
2592 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2593 check_added_monitors!(nodes[1], 1);
2594 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2595 let mut events = nodes[0].node.get_and_clear_pending_events();
2596 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2597 match events.last().unwrap() {
2598 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2599 _ => panic!("Unexpected event"),
2602 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2605 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2606 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2608 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2609 assert_eq!(node_txn[0].input.len(), 1);
2610 check_spends!(node_txn[0], chan_1.3);
2611 assert_eq!(node_txn[1].input.len(), 1);
2612 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2613 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2614 check_spends!(node_txn[1], node_txn[0]);
2616 // Justice transactions are indices 1-2-4
2617 assert_eq!(node_txn[2].input.len(), 1);
2618 assert_eq!(node_txn[3].input.len(), 1);
2619 assert_eq!(node_txn[4].input.len(), 1);
2621 check_spends!(node_txn[2], revoked_local_txn[0]);
2622 check_spends!(node_txn[3], revoked_local_txn[0]);
2623 check_spends!(node_txn[4], revoked_local_txn[0]);
2625 let mut witness_lens = BTreeSet::new();
2626 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2627 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2628 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2629 assert_eq!(witness_lens.len(), 3);
2630 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2631 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2632 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2634 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2635 // ANTI_REORG_DELAY confirmations.
2636 mine_transaction(&nodes[1], &node_txn[2]);
2637 mine_transaction(&nodes[1], &node_txn[3]);
2638 mine_transaction(&nodes[1], &node_txn[4]);
2639 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2640 expect_payment_failed!(nodes[1], payment_hash_2, true);
2642 get_announce_close_broadcast_events(&nodes, 0, 1);
2643 assert_eq!(nodes[0].node.list_channels().len(), 0);
2644 assert_eq!(nodes[1].node.list_channels().len(), 0);
2648 fn test_htlc_on_chain_success() {
2649 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2650 // the preimage backward accordingly. So here we test that ChannelManager is
2651 // broadcasting the right event to other nodes in payment path.
2652 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2653 // A --------------------> B ----------------------> C (preimage)
2654 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2655 // commitment transaction was broadcast.
2656 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2658 // B should be able to claim via preimage if A then broadcasts its local tx.
2659 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2660 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2661 // PaymentSent event).
2663 let chanmon_cfgs = create_chanmon_cfgs(3);
2664 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2665 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2666 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2668 // Create some initial channels
2669 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2670 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2672 // Ensure all nodes are at the same height
2673 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2674 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2675 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2676 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2678 // Rebalance the network a bit by relaying one payment through all the channels...
2679 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2682 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2685 // Broadcast legit commitment tx from C on B's chain
2686 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2687 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2688 assert_eq!(commitment_tx.len(), 1);
2689 check_spends!(commitment_tx[0], chan_2.3);
2690 nodes[2].node.claim_funds(our_payment_preimage);
2691 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2692 nodes[2].node.claim_funds(our_payment_preimage_2);
2693 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2694 check_added_monitors!(nodes[2], 2);
2695 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2696 assert!(updates.update_add_htlcs.is_empty());
2697 assert!(updates.update_fail_htlcs.is_empty());
2698 assert!(updates.update_fail_malformed_htlcs.is_empty());
2699 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2701 mine_transaction(&nodes[2], &commitment_tx[0]);
2702 check_closed_broadcast!(nodes[2], true);
2703 check_added_monitors!(nodes[2], 1);
2704 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2705 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)
2706 assert_eq!(node_txn.len(), 5);
2707 assert_eq!(node_txn[0], node_txn[3]);
2708 assert_eq!(node_txn[1], node_txn[4]);
2709 assert_eq!(node_txn[2], commitment_tx[0]);
2710 check_spends!(node_txn[0], commitment_tx[0]);
2711 check_spends!(node_txn[1], commitment_tx[0]);
2712 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2713 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2714 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2715 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2716 assert_eq!(node_txn[0].lock_time, 0);
2717 assert_eq!(node_txn[1].lock_time, 0);
2719 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2720 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2721 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2722 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2724 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2725 assert_eq!(added_monitors.len(), 1);
2726 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2727 added_monitors.clear();
2729 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2730 assert_eq!(forwarded_events.len(), 3);
2731 match forwarded_events[0] {
2732 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2733 _ => panic!("Unexpected event"),
2735 let chan_id = Some(chan_1.2);
2736 match forwarded_events[1] {
2737 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2738 assert_eq!(fee_earned_msat, Some(1000));
2739 assert_eq!(prev_channel_id, chan_id);
2740 assert_eq!(claim_from_onchain_tx, true);
2741 assert_eq!(next_channel_id, Some(chan_2.2));
2745 match forwarded_events[2] {
2746 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2747 assert_eq!(fee_earned_msat, Some(1000));
2748 assert_eq!(prev_channel_id, chan_id);
2749 assert_eq!(claim_from_onchain_tx, true);
2750 assert_eq!(next_channel_id, Some(chan_2.2));
2754 let events = nodes[1].node.get_and_clear_pending_msg_events();
2756 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2757 assert_eq!(added_monitors.len(), 2);
2758 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2759 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2760 added_monitors.clear();
2762 assert_eq!(events.len(), 3);
2764 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2765 _ => panic!("Unexpected event"),
2768 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2769 _ => panic!("Unexpected event"),
2773 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, .. } } => {
2774 assert!(update_add_htlcs.is_empty());
2775 assert!(update_fail_htlcs.is_empty());
2776 assert_eq!(update_fulfill_htlcs.len(), 1);
2777 assert!(update_fail_malformed_htlcs.is_empty());
2778 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2780 _ => panic!("Unexpected event"),
2782 macro_rules! check_tx_local_broadcast {
2783 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2784 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2785 assert_eq!(node_txn.len(), 3);
2786 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2787 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2788 check_spends!(node_txn[1], $commitment_tx);
2789 check_spends!(node_txn[2], $commitment_tx);
2790 assert_ne!(node_txn[1].lock_time, 0);
2791 assert_ne!(node_txn[2].lock_time, 0);
2793 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2794 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2795 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2796 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2798 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2799 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2800 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2801 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2803 check_spends!(node_txn[0], $chan_tx);
2804 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2808 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2809 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2810 // timeout-claim of the output that nodes[2] just claimed via success.
2811 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2813 // Broadcast legit commitment tx from A on B's chain
2814 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2815 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2816 check_spends!(node_a_commitment_tx[0], chan_1.3);
2817 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2818 check_closed_broadcast!(nodes[1], true);
2819 check_added_monitors!(nodes[1], 1);
2820 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2821 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2822 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2823 let commitment_spend =
2824 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2825 check_spends!(node_txn[1], commitment_tx[0]);
2826 check_spends!(node_txn[2], commitment_tx[0]);
2827 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2830 check_spends!(node_txn[0], commitment_tx[0]);
2831 check_spends!(node_txn[1], commitment_tx[0]);
2832 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2836 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2837 assert_eq!(commitment_spend.input.len(), 2);
2838 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2839 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2840 assert_eq!(commitment_spend.lock_time, 0);
2841 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2842 check_spends!(node_txn[3], chan_1.3);
2843 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2844 check_spends!(node_txn[4], node_txn[3]);
2845 check_spends!(node_txn[5], node_txn[3]);
2846 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2847 // we already checked the same situation with A.
2849 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2850 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2851 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2852 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2853 check_closed_broadcast!(nodes[0], true);
2854 check_added_monitors!(nodes[0], 1);
2855 let events = nodes[0].node.get_and_clear_pending_events();
2856 assert_eq!(events.len(), 5);
2857 let mut first_claimed = false;
2858 for event in events {
2860 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2861 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2862 assert!(!first_claimed);
2863 first_claimed = true;
2865 assert_eq!(payment_preimage, our_payment_preimage_2);
2866 assert_eq!(payment_hash, payment_hash_2);
2869 Event::PaymentPathSuccessful { .. } => {},
2870 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2871 _ => panic!("Unexpected event"),
2874 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2877 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2878 // Test that in case of a unilateral close onchain, we detect the state of output and
2879 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2880 // broadcasting the right event to other nodes in payment path.
2881 // A ------------------> B ----------------------> C (timeout)
2882 // B's commitment tx C's commitment tx
2884 // B's HTLC timeout tx B's timeout tx
2886 let chanmon_cfgs = create_chanmon_cfgs(3);
2887 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2888 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2889 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2890 *nodes[0].connect_style.borrow_mut() = connect_style;
2891 *nodes[1].connect_style.borrow_mut() = connect_style;
2892 *nodes[2].connect_style.borrow_mut() = connect_style;
2894 // Create some intial channels
2895 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2896 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2898 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2899 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2900 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2902 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2904 // Broadcast legit commitment tx from C on B's chain
2905 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2906 check_spends!(commitment_tx[0], chan_2.3);
2907 nodes[2].node.fail_htlc_backwards(&payment_hash);
2908 check_added_monitors!(nodes[2], 0);
2909 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2910 check_added_monitors!(nodes[2], 1);
2912 let events = nodes[2].node.get_and_clear_pending_msg_events();
2913 assert_eq!(events.len(), 1);
2915 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, .. } } => {
2916 assert!(update_add_htlcs.is_empty());
2917 assert!(!update_fail_htlcs.is_empty());
2918 assert!(update_fulfill_htlcs.is_empty());
2919 assert!(update_fail_malformed_htlcs.is_empty());
2920 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2922 _ => panic!("Unexpected event"),
2924 mine_transaction(&nodes[2], &commitment_tx[0]);
2925 check_closed_broadcast!(nodes[2], true);
2926 check_added_monitors!(nodes[2], 1);
2927 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2928 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2929 assert_eq!(node_txn.len(), 1);
2930 check_spends!(node_txn[0], chan_2.3);
2931 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2933 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2934 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2935 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2936 mine_transaction(&nodes[1], &commitment_tx[0]);
2937 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2940 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2941 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2942 assert_eq!(node_txn[0], node_txn[3]);
2943 assert_eq!(node_txn[1], node_txn[4]);
2945 check_spends!(node_txn[2], commitment_tx[0]);
2946 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2948 check_spends!(node_txn[0], chan_2.3);
2949 check_spends!(node_txn[1], node_txn[0]);
2950 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2951 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2953 timeout_tx = node_txn[2].clone();
2957 mine_transaction(&nodes[1], &timeout_tx);
2958 check_added_monitors!(nodes[1], 1);
2959 check_closed_broadcast!(nodes[1], true);
2961 // B will rebroadcast a fee-bumped timeout transaction here.
2962 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2963 assert_eq!(node_txn.len(), 1);
2964 check_spends!(node_txn[0], commitment_tx[0]);
2967 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2969 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2970 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2971 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2972 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2973 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2974 if node_txn.len() == 1 {
2975 check_spends!(node_txn[0], chan_2.3);
2977 assert_eq!(node_txn.len(), 0);
2981 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
2982 check_added_monitors!(nodes[1], 1);
2983 let events = nodes[1].node.get_and_clear_pending_msg_events();
2984 assert_eq!(events.len(), 1);
2986 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, .. } } => {
2987 assert!(update_add_htlcs.is_empty());
2988 assert!(!update_fail_htlcs.is_empty());
2989 assert!(update_fulfill_htlcs.is_empty());
2990 assert!(update_fail_malformed_htlcs.is_empty());
2991 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2993 _ => panic!("Unexpected event"),
2996 // Broadcast legit commitment tx from B on A's chain
2997 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2998 check_spends!(commitment_tx[0], chan_1.3);
3000 mine_transaction(&nodes[0], &commitment_tx[0]);
3001 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3003 check_closed_broadcast!(nodes[0], true);
3004 check_added_monitors!(nodes[0], 1);
3005 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3006 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3007 assert_eq!(node_txn.len(), 2);
3008 check_spends!(node_txn[0], chan_1.3);
3009 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3010 check_spends!(node_txn[1], commitment_tx[0]);
3011 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3015 fn test_htlc_on_chain_timeout() {
3016 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3017 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3018 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3022 fn test_simple_commitment_revoked_fail_backward() {
3023 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3024 // and fail backward accordingly.
3026 let chanmon_cfgs = create_chanmon_cfgs(3);
3027 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3028 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3029 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3031 // Create some initial channels
3032 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3033 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3035 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3036 // Get the will-be-revoked local txn from nodes[2]
3037 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3038 // Revoke the old state
3039 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3041 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3043 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3044 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3045 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3046 check_added_monitors!(nodes[1], 1);
3047 check_closed_broadcast!(nodes[1], true);
3049 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3050 check_added_monitors!(nodes[1], 1);
3051 let events = nodes[1].node.get_and_clear_pending_msg_events();
3052 assert_eq!(events.len(), 1);
3054 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, .. } } => {
3055 assert!(update_add_htlcs.is_empty());
3056 assert_eq!(update_fail_htlcs.len(), 1);
3057 assert!(update_fulfill_htlcs.is_empty());
3058 assert!(update_fail_malformed_htlcs.is_empty());
3059 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3061 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3062 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3063 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3065 _ => panic!("Unexpected event"),
3069 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3070 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3071 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3072 // commitment transaction anymore.
3073 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3074 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3075 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3076 // technically disallowed and we should probably handle it reasonably.
3077 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3078 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3080 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3081 // commitment_signed (implying it will be in the latest remote commitment transaction).
3082 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3083 // and once they revoke the previous commitment transaction (allowing us to send a new
3084 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3085 let chanmon_cfgs = create_chanmon_cfgs(3);
3086 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3087 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3088 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3090 // Create some initial channels
3091 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3092 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3094 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 });
3095 // Get the will-be-revoked local txn from nodes[2]
3096 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3097 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3098 // Revoke the old state
3099 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3101 let value = if use_dust {
3102 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3103 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3104 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3107 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3108 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3109 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3111 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3112 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3113 check_added_monitors!(nodes[2], 1);
3114 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3115 assert!(updates.update_add_htlcs.is_empty());
3116 assert!(updates.update_fulfill_htlcs.is_empty());
3117 assert!(updates.update_fail_malformed_htlcs.is_empty());
3118 assert_eq!(updates.update_fail_htlcs.len(), 1);
3119 assert!(updates.update_fee.is_none());
3120 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3121 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3122 // Drop the last RAA from 3 -> 2
3124 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3125 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3126 check_added_monitors!(nodes[2], 1);
3127 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3128 assert!(updates.update_add_htlcs.is_empty());
3129 assert!(updates.update_fulfill_htlcs.is_empty());
3130 assert!(updates.update_fail_malformed_htlcs.is_empty());
3131 assert_eq!(updates.update_fail_htlcs.len(), 1);
3132 assert!(updates.update_fee.is_none());
3133 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3134 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3135 check_added_monitors!(nodes[1], 1);
3136 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3137 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3138 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3139 check_added_monitors!(nodes[2], 1);
3141 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3142 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3143 check_added_monitors!(nodes[2], 1);
3144 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3145 assert!(updates.update_add_htlcs.is_empty());
3146 assert!(updates.update_fulfill_htlcs.is_empty());
3147 assert!(updates.update_fail_malformed_htlcs.is_empty());
3148 assert_eq!(updates.update_fail_htlcs.len(), 1);
3149 assert!(updates.update_fee.is_none());
3150 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3151 // At this point first_payment_hash has dropped out of the latest two commitment
3152 // transactions that nodes[1] is tracking...
3153 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3154 check_added_monitors!(nodes[1], 1);
3155 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3156 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3157 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3158 check_added_monitors!(nodes[2], 1);
3160 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3161 // on nodes[2]'s RAA.
3162 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3163 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3164 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3165 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3166 check_added_monitors!(nodes[1], 0);
3169 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3170 // One monitor for the new revocation preimage, no second on as we won't generate a new
3171 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3172 check_added_monitors!(nodes[1], 1);
3173 let events = nodes[1].node.get_and_clear_pending_events();
3174 assert_eq!(events.len(), 2);
3176 Event::PendingHTLCsForwardable { .. } => { },
3177 _ => panic!("Unexpected event"),
3180 Event::HTLCHandlingFailed { .. } => { },
3181 _ => panic!("Unexpected event"),
3183 // Deliberately don't process the pending fail-back so they all fail back at once after
3184 // block connection just like the !deliver_bs_raa case
3187 let mut failed_htlcs = HashSet::new();
3188 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3190 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3191 check_added_monitors!(nodes[1], 1);
3192 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3193 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3195 let events = nodes[1].node.get_and_clear_pending_events();
3196 assert_eq!(events.len(), if deliver_bs_raa { 2 + (nodes.len() - 1) } else { 4 + nodes.len() });
3198 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3199 _ => panic!("Unexepected event"),
3202 Event::PaymentPathFailed { ref payment_hash, .. } => {
3203 assert_eq!(*payment_hash, fourth_payment_hash);
3205 _ => panic!("Unexpected event"),
3207 if !deliver_bs_raa {
3209 Event::PaymentFailed { ref payment_hash, .. } => {
3210 assert_eq!(*payment_hash, fourth_payment_hash);
3212 _ => panic!("Unexpected event"),
3215 Event::PendingHTLCsForwardable { .. } => { },
3216 _ => panic!("Unexpected event"),
3219 nodes[1].node.process_pending_htlc_forwards();
3220 check_added_monitors!(nodes[1], 1);
3222 let events = nodes[1].node.get_and_clear_pending_msg_events();
3223 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3224 match events[if deliver_bs_raa { 1 } else { 0 }] {
3225 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3226 _ => panic!("Unexpected event"),
3228 match events[if deliver_bs_raa { 2 } else { 1 }] {
3229 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3230 assert_eq!(channel_id, chan_2.2);
3231 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3233 _ => panic!("Unexpected event"),
3237 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, .. } } => {
3238 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3239 assert_eq!(update_add_htlcs.len(), 1);
3240 assert!(update_fulfill_htlcs.is_empty());
3241 assert!(update_fail_htlcs.is_empty());
3242 assert!(update_fail_malformed_htlcs.is_empty());
3244 _ => panic!("Unexpected event"),
3247 match events[if deliver_bs_raa { 3 } else { 2 }] {
3248 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, .. } } => {
3249 assert!(update_add_htlcs.is_empty());
3250 assert_eq!(update_fail_htlcs.len(), 3);
3251 assert!(update_fulfill_htlcs.is_empty());
3252 assert!(update_fail_malformed_htlcs.is_empty());
3253 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3255 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3256 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3257 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3259 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3261 let events = nodes[0].node.get_and_clear_pending_events();
3262 assert_eq!(events.len(), 3);
3264 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3265 assert!(failed_htlcs.insert(payment_hash.0));
3266 // If we delivered B's RAA we got an unknown preimage error, not something
3267 // that we should update our routing table for.
3268 if !deliver_bs_raa {
3269 assert!(network_update.is_some());
3272 _ => panic!("Unexpected event"),
3275 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3276 assert!(failed_htlcs.insert(payment_hash.0));
3277 assert!(network_update.is_some());
3279 _ => panic!("Unexpected event"),
3282 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3283 assert!(failed_htlcs.insert(payment_hash.0));
3284 assert!(network_update.is_some());
3286 _ => panic!("Unexpected event"),
3289 _ => panic!("Unexpected event"),
3292 assert!(failed_htlcs.contains(&first_payment_hash.0));
3293 assert!(failed_htlcs.contains(&second_payment_hash.0));
3294 assert!(failed_htlcs.contains(&third_payment_hash.0));
3298 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3299 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3300 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3301 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3302 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3306 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3307 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3308 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3309 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3310 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3314 fn fail_backward_pending_htlc_upon_channel_failure() {
3315 let chanmon_cfgs = create_chanmon_cfgs(2);
3316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3318 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3319 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3321 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3323 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3324 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3325 check_added_monitors!(nodes[0], 1);
3327 let payment_event = {
3328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3329 assert_eq!(events.len(), 1);
3330 SendEvent::from_event(events.remove(0))
3332 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3333 assert_eq!(payment_event.msgs.len(), 1);
3336 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3337 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3339 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3340 check_added_monitors!(nodes[0], 0);
3342 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3345 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3347 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3349 let secp_ctx = Secp256k1::new();
3350 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3351 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3352 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3353 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3354 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3356 // Send a 0-msat update_add_htlc to fail the channel.
3357 let update_add_htlc = msgs::UpdateAddHTLC {
3363 onion_routing_packet,
3365 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3367 let events = nodes[0].node.get_and_clear_pending_events();
3368 assert_eq!(events.len(), 2);
3369 // Check that Alice fails backward the pending HTLC from the second payment.
3371 Event::PaymentPathFailed { payment_hash, .. } => {
3372 assert_eq!(payment_hash, failed_payment_hash);
3374 _ => panic!("Unexpected event"),
3377 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3378 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3380 _ => panic!("Unexpected event {:?}", events[1]),
3382 check_closed_broadcast!(nodes[0], true);
3383 check_added_monitors!(nodes[0], 1);
3387 fn test_htlc_ignore_latest_remote_commitment() {
3388 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3389 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3390 let chanmon_cfgs = create_chanmon_cfgs(2);
3391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3393 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3394 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3396 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3397 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3398 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3399 check_closed_broadcast!(nodes[0], true);
3400 check_added_monitors!(nodes[0], 1);
3401 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3403 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3404 assert_eq!(node_txn.len(), 3);
3405 assert_eq!(node_txn[0], node_txn[1]);
3407 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3408 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3409 check_closed_broadcast!(nodes[1], true);
3410 check_added_monitors!(nodes[1], 1);
3411 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3413 // Duplicate the connect_block call since this may happen due to other listeners
3414 // registering new transactions
3415 header.prev_blockhash = header.block_hash();
3416 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3420 fn test_force_close_fail_back() {
3421 // Check which HTLCs are failed-backwards on channel force-closure
3422 let chanmon_cfgs = create_chanmon_cfgs(3);
3423 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3424 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3425 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3426 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3427 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3429 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3431 let mut payment_event = {
3432 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3433 check_added_monitors!(nodes[0], 1);
3435 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3436 assert_eq!(events.len(), 1);
3437 SendEvent::from_event(events.remove(0))
3440 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3441 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3443 expect_pending_htlcs_forwardable!(nodes[1]);
3445 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3446 assert_eq!(events_2.len(), 1);
3447 payment_event = SendEvent::from_event(events_2.remove(0));
3448 assert_eq!(payment_event.msgs.len(), 1);
3450 check_added_monitors!(nodes[1], 1);
3451 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3452 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3453 check_added_monitors!(nodes[2], 1);
3454 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3456 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3457 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3458 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3460 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3461 check_closed_broadcast!(nodes[2], true);
3462 check_added_monitors!(nodes[2], 1);
3463 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3465 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3466 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3467 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3468 // back to nodes[1] upon timeout otherwise.
3469 assert_eq!(node_txn.len(), 1);
3473 mine_transaction(&nodes[1], &tx);
3475 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3476 check_closed_broadcast!(nodes[1], true);
3477 check_added_monitors!(nodes[1], 1);
3478 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3480 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3482 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3483 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3485 mine_transaction(&nodes[2], &tx);
3486 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3487 assert_eq!(node_txn.len(), 1);
3488 assert_eq!(node_txn[0].input.len(), 1);
3489 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3490 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3491 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3493 check_spends!(node_txn[0], tx);
3497 fn test_dup_events_on_peer_disconnect() {
3498 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3499 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3500 // as we used to generate the event immediately upon receipt of the payment preimage in the
3501 // update_fulfill_htlc message.
3503 let chanmon_cfgs = create_chanmon_cfgs(2);
3504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3507 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3509 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3511 nodes[1].node.claim_funds(payment_preimage);
3512 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3513 check_added_monitors!(nodes[1], 1);
3514 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3515 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3516 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3518 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3519 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3521 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3522 expect_payment_path_successful!(nodes[0]);
3526 fn test_peer_disconnected_before_funding_broadcasted() {
3527 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3528 // before the funding transaction has been broadcasted.
3529 let chanmon_cfgs = create_chanmon_cfgs(2);
3530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3532 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3534 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3535 // broadcasted, even though it's created by `nodes[0]`.
3536 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3537 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3538 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3539 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3540 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3542 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3543 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3545 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3547 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3548 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3550 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3551 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3554 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3557 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3558 // disconnected before the funding transaction was broadcasted.
3559 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3560 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3562 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3563 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3567 fn test_simple_peer_disconnect() {
3568 // Test that we can reconnect when there are no lost messages
3569 let chanmon_cfgs = create_chanmon_cfgs(3);
3570 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3571 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3572 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3573 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3574 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3576 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3580 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3581 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3582 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3583 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3585 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3586 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3587 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3590 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3591 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3592 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3594 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3595 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3597 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3598 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3600 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3602 let events = nodes[0].node.get_and_clear_pending_events();
3603 assert_eq!(events.len(), 3);
3605 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3606 assert_eq!(payment_preimage, payment_preimage_3);
3607 assert_eq!(payment_hash, payment_hash_3);
3609 _ => panic!("Unexpected event"),
3612 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3613 assert_eq!(payment_hash, payment_hash_5);
3614 assert!(rejected_by_dest);
3616 _ => panic!("Unexpected event"),
3619 Event::PaymentPathSuccessful { .. } => {},
3620 _ => panic!("Unexpected event"),
3624 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3625 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3628 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3629 // Test that we can reconnect when in-flight HTLC updates get dropped
3630 let chanmon_cfgs = create_chanmon_cfgs(2);
3631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3633 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3635 let mut as_channel_ready = None;
3636 if messages_delivered == 0 {
3637 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3638 as_channel_ready = Some(channel_ready);
3639 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3640 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3641 // it before the channel_reestablish message.
3643 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3646 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3648 let payment_event = {
3649 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3650 check_added_monitors!(nodes[0], 1);
3652 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3653 assert_eq!(events.len(), 1);
3654 SendEvent::from_event(events.remove(0))
3656 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3658 if messages_delivered < 2 {
3659 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3661 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3662 if messages_delivered >= 3 {
3663 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3664 check_added_monitors!(nodes[1], 1);
3665 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3667 if messages_delivered >= 4 {
3668 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3669 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3670 check_added_monitors!(nodes[0], 1);
3672 if messages_delivered >= 5 {
3673 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3674 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3675 // No commitment_signed so get_event_msg's assert(len == 1) passes
3676 check_added_monitors!(nodes[0], 1);
3678 if messages_delivered >= 6 {
3679 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3680 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3681 check_added_monitors!(nodes[1], 1);
3688 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3689 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3690 if messages_delivered < 3 {
3691 if simulate_broken_lnd {
3692 // lnd has a long-standing bug where they send a channel_ready prior to a
3693 // channel_reestablish if you reconnect prior to channel_ready time.
3695 // Here we simulate that behavior, delivering a channel_ready immediately on
3696 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3697 // in `reconnect_nodes` but we currently don't fail based on that.
3699 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3700 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3702 // Even if the channel_ready messages get exchanged, as long as nothing further was
3703 // received on either side, both sides will need to resend them.
3704 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3705 } else if messages_delivered == 3 {
3706 // nodes[0] still wants its RAA + commitment_signed
3707 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3708 } else if messages_delivered == 4 {
3709 // nodes[0] still wants its commitment_signed
3710 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3711 } else if messages_delivered == 5 {
3712 // nodes[1] still wants its final RAA
3713 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3714 } else if messages_delivered == 6 {
3715 // Everything was delivered...
3716 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3719 let events_1 = nodes[1].node.get_and_clear_pending_events();
3720 assert_eq!(events_1.len(), 1);
3722 Event::PendingHTLCsForwardable { .. } => { },
3723 _ => panic!("Unexpected event"),
3726 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3727 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3728 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3730 nodes[1].node.process_pending_htlc_forwards();
3732 let events_2 = nodes[1].node.get_and_clear_pending_events();
3733 assert_eq!(events_2.len(), 1);
3735 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3736 assert_eq!(payment_hash_1, *payment_hash);
3737 assert_eq!(amount_msat, 1_000_000);
3739 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3740 assert!(payment_preimage.is_none());
3741 assert_eq!(payment_secret_1, *payment_secret);
3743 _ => panic!("expected PaymentPurpose::InvoicePayment")
3746 _ => panic!("Unexpected event"),
3749 nodes[1].node.claim_funds(payment_preimage_1);
3750 check_added_monitors!(nodes[1], 1);
3751 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3753 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3754 assert_eq!(events_3.len(), 1);
3755 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3756 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3757 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3758 assert!(updates.update_add_htlcs.is_empty());
3759 assert!(updates.update_fail_htlcs.is_empty());
3760 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3761 assert!(updates.update_fail_malformed_htlcs.is_empty());
3762 assert!(updates.update_fee.is_none());
3763 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3765 _ => panic!("Unexpected event"),
3768 if messages_delivered >= 1 {
3769 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3771 let events_4 = nodes[0].node.get_and_clear_pending_events();
3772 assert_eq!(events_4.len(), 1);
3774 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3775 assert_eq!(payment_preimage_1, *payment_preimage);
3776 assert_eq!(payment_hash_1, *payment_hash);
3778 _ => panic!("Unexpected event"),
3781 if messages_delivered >= 2 {
3782 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3783 check_added_monitors!(nodes[0], 1);
3784 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3786 if messages_delivered >= 3 {
3787 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3788 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3789 check_added_monitors!(nodes[1], 1);
3791 if messages_delivered >= 4 {
3792 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3793 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3794 // No commitment_signed so get_event_msg's assert(len == 1) passes
3795 check_added_monitors!(nodes[1], 1);
3797 if messages_delivered >= 5 {
3798 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3799 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3800 check_added_monitors!(nodes[0], 1);
3807 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3808 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3809 if messages_delivered < 2 {
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3811 if messages_delivered < 1 {
3812 expect_payment_sent!(nodes[0], payment_preimage_1);
3814 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3816 } else if messages_delivered == 2 {
3817 // nodes[0] still wants its RAA + commitment_signed
3818 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3819 } else if messages_delivered == 3 {
3820 // nodes[0] still wants its commitment_signed
3821 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3822 } else if messages_delivered == 4 {
3823 // nodes[1] still wants its final RAA
3824 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3825 } else if messages_delivered == 5 {
3826 // Everything was delivered...
3827 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3830 if messages_delivered == 1 || messages_delivered == 2 {
3831 expect_payment_path_successful!(nodes[0]);
3834 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3835 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3836 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3838 if messages_delivered > 2 {
3839 expect_payment_path_successful!(nodes[0]);
3842 // Channel should still work fine...
3843 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3844 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3845 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3849 fn test_drop_messages_peer_disconnect_a() {
3850 do_test_drop_messages_peer_disconnect(0, true);
3851 do_test_drop_messages_peer_disconnect(0, false);
3852 do_test_drop_messages_peer_disconnect(1, false);
3853 do_test_drop_messages_peer_disconnect(2, false);
3857 fn test_drop_messages_peer_disconnect_b() {
3858 do_test_drop_messages_peer_disconnect(3, false);
3859 do_test_drop_messages_peer_disconnect(4, false);
3860 do_test_drop_messages_peer_disconnect(5, false);
3861 do_test_drop_messages_peer_disconnect(6, false);
3865 fn test_funding_peer_disconnect() {
3866 // Test that we can lock in our funding tx while disconnected
3867 let chanmon_cfgs = create_chanmon_cfgs(2);
3868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3870 let persister: test_utils::TestPersister;
3871 let new_chain_monitor: test_utils::TestChainMonitor;
3872 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3873 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3874 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3876 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3877 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3879 confirm_transaction(&nodes[0], &tx);
3880 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3881 assert!(events_1.is_empty());
3883 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3885 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3886 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3888 confirm_transaction(&nodes[1], &tx);
3889 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3890 assert!(events_2.is_empty());
3892 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3893 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3894 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3895 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3897 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3898 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3899 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3900 assert_eq!(events_3.len(), 1);
3901 let as_channel_ready = match events_3[0] {
3902 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3903 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3906 _ => panic!("Unexpected event {:?}", events_3[0]),
3909 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3910 // announcement_signatures as well as channel_update.
3911 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3912 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3913 assert_eq!(events_4.len(), 3);
3915 let bs_channel_ready = match events_4[0] {
3916 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3917 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3918 chan_id = msg.channel_id;
3921 _ => panic!("Unexpected event {:?}", events_4[0]),
3923 let bs_announcement_sigs = match events_4[1] {
3924 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3925 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3928 _ => panic!("Unexpected event {:?}", events_4[1]),
3931 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3932 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3934 _ => panic!("Unexpected event {:?}", events_4[2]),
3937 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3938 // generates a duplicative private channel_update
3939 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3940 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3941 assert_eq!(events_5.len(), 1);
3943 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3944 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3946 _ => panic!("Unexpected event {:?}", events_5[0]),
3949 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3950 // announcement_signatures.
3951 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3952 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3953 assert_eq!(events_6.len(), 1);
3954 let as_announcement_sigs = match events_6[0] {
3955 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3956 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3959 _ => panic!("Unexpected event {:?}", events_6[0]),
3962 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3963 // broadcast the channel announcement globally, as well as re-send its (now-public)
3965 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3966 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3967 assert_eq!(events_7.len(), 1);
3968 let (chan_announcement, as_update) = match events_7[0] {
3969 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3970 (msg.clone(), update_msg.clone())
3972 _ => panic!("Unexpected event {:?}", events_7[0]),
3975 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3976 // same channel_announcement.
3977 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3978 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3979 assert_eq!(events_8.len(), 1);
3980 let bs_update = match events_8[0] {
3981 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3982 assert_eq!(*msg, chan_announcement);
3985 _ => panic!("Unexpected event {:?}", events_8[0]),
3988 // Provide the channel announcement and public updates to the network graph
3989 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
3990 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
3991 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
3993 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3994 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3995 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3997 // Check that after deserialization and reconnection we can still generate an identical
3998 // channel_announcement from the cached signatures.
3999 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4001 let nodes_0_serialized = nodes[0].node.encode();
4002 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4003 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4005 persister = test_utils::TestPersister::new();
4006 let keys_manager = &chanmon_cfgs[0].keys_manager;
4007 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);
4008 nodes[0].chain_monitor = &new_chain_monitor;
4009 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4010 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4011 &mut chan_0_monitor_read, keys_manager).unwrap();
4012 assert!(chan_0_monitor_read.is_empty());
4014 let mut nodes_0_read = &nodes_0_serialized[..];
4015 let (_, nodes_0_deserialized_tmp) = {
4016 let mut channel_monitors = HashMap::new();
4017 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4018 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4019 default_config: UserConfig::default(),
4021 fee_estimator: node_cfgs[0].fee_estimator,
4022 chain_monitor: nodes[0].chain_monitor,
4023 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4024 logger: nodes[0].logger,
4028 nodes_0_deserialized = nodes_0_deserialized_tmp;
4029 assert!(nodes_0_read.is_empty());
4031 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4032 nodes[0].node = &nodes_0_deserialized;
4033 check_added_monitors!(nodes[0], 1);
4035 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4037 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4038 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4039 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4040 let mut found_announcement = false;
4041 for event in msgs.iter() {
4043 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4044 if *msg == chan_announcement { found_announcement = true; }
4046 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4047 _ => panic!("Unexpected event"),
4050 assert!(found_announcement);
4054 fn test_channel_ready_without_best_block_updated() {
4055 // Previously, if we were offline when a funding transaction was locked in, and then we came
4056 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4057 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4058 // channel_ready immediately instead.
4059 let chanmon_cfgs = create_chanmon_cfgs(2);
4060 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4061 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4062 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4063 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4065 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4067 let conf_height = nodes[0].best_block_info().1 + 1;
4068 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4069 let block_txn = [funding_tx];
4070 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4071 let conf_block_header = nodes[0].get_block_header(conf_height);
4072 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4074 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4075 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4076 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4080 fn test_drop_messages_peer_disconnect_dual_htlc() {
4081 // Test that we can handle reconnecting when both sides of a channel have pending
4082 // commitment_updates when we disconnect.
4083 let chanmon_cfgs = create_chanmon_cfgs(2);
4084 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4085 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4086 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4087 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4089 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4091 // Now try to send a second payment which will fail to send
4092 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4093 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4094 check_added_monitors!(nodes[0], 1);
4096 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4097 assert_eq!(events_1.len(), 1);
4099 MessageSendEvent::UpdateHTLCs { .. } => {},
4100 _ => panic!("Unexpected event"),
4103 nodes[1].node.claim_funds(payment_preimage_1);
4104 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4105 check_added_monitors!(nodes[1], 1);
4107 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4108 assert_eq!(events_2.len(), 1);
4110 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 } } => {
4111 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4112 assert!(update_add_htlcs.is_empty());
4113 assert_eq!(update_fulfill_htlcs.len(), 1);
4114 assert!(update_fail_htlcs.is_empty());
4115 assert!(update_fail_malformed_htlcs.is_empty());
4116 assert!(update_fee.is_none());
4118 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4119 let events_3 = nodes[0].node.get_and_clear_pending_events();
4120 assert_eq!(events_3.len(), 1);
4122 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4123 assert_eq!(*payment_preimage, payment_preimage_1);
4124 assert_eq!(*payment_hash, payment_hash_1);
4126 _ => panic!("Unexpected event"),
4129 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4130 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4131 // No commitment_signed so get_event_msg's assert(len == 1) passes
4132 check_added_monitors!(nodes[0], 1);
4134 _ => panic!("Unexpected event"),
4137 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4138 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4140 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4141 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4142 assert_eq!(reestablish_1.len(), 1);
4143 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4144 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4145 assert_eq!(reestablish_2.len(), 1);
4147 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4148 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4149 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4150 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4152 assert!(as_resp.0.is_none());
4153 assert!(bs_resp.0.is_none());
4155 assert!(bs_resp.1.is_none());
4156 assert!(bs_resp.2.is_none());
4158 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4160 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4161 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4162 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4163 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4164 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4165 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4166 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4167 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4168 // No commitment_signed so get_event_msg's assert(len == 1) passes
4169 check_added_monitors!(nodes[1], 1);
4171 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4172 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4173 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4174 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4175 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4176 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4177 assert!(bs_second_commitment_signed.update_fee.is_none());
4178 check_added_monitors!(nodes[1], 1);
4180 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4181 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4182 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4183 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4184 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4185 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4186 assert!(as_commitment_signed.update_fee.is_none());
4187 check_added_monitors!(nodes[0], 1);
4189 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4190 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4191 // No commitment_signed so get_event_msg's assert(len == 1) passes
4192 check_added_monitors!(nodes[0], 1);
4194 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4195 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4196 // No commitment_signed so get_event_msg's assert(len == 1) passes
4197 check_added_monitors!(nodes[1], 1);
4199 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4200 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4201 check_added_monitors!(nodes[1], 1);
4203 expect_pending_htlcs_forwardable!(nodes[1]);
4205 let events_5 = nodes[1].node.get_and_clear_pending_events();
4206 assert_eq!(events_5.len(), 1);
4208 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4209 assert_eq!(payment_hash_2, *payment_hash);
4211 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4212 assert!(payment_preimage.is_none());
4213 assert_eq!(payment_secret_2, *payment_secret);
4215 _ => panic!("expected PaymentPurpose::InvoicePayment")
4218 _ => panic!("Unexpected event"),
4221 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4222 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4223 check_added_monitors!(nodes[0], 1);
4225 expect_payment_path_successful!(nodes[0]);
4226 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4229 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4230 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4231 // to avoid our counterparty failing the channel.
4232 let chanmon_cfgs = create_chanmon_cfgs(2);
4233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4237 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4239 let our_payment_hash = if send_partial_mpp {
4240 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4241 // Use the utility function send_payment_along_path to send the payment with MPP data which
4242 // indicates there are more HTLCs coming.
4243 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.
4244 let payment_id = PaymentId([42; 32]);
4245 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();
4246 check_added_monitors!(nodes[0], 1);
4247 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4248 assert_eq!(events.len(), 1);
4249 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4250 // hop should *not* yet generate any PaymentReceived event(s).
4251 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4254 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4257 let mut block = Block {
4258 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4261 connect_block(&nodes[0], &block);
4262 connect_block(&nodes[1], &block);
4263 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4264 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4265 block.header.prev_blockhash = block.block_hash();
4266 connect_block(&nodes[0], &block);
4267 connect_block(&nodes[1], &block);
4270 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4272 check_added_monitors!(nodes[1], 1);
4273 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4274 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4275 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4276 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4277 assert!(htlc_timeout_updates.update_fee.is_none());
4279 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4280 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4281 // 100_000 msat as u64, followed by the height at which we failed back above
4282 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4283 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4284 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4288 fn test_htlc_timeout() {
4289 do_test_htlc_timeout(true);
4290 do_test_htlc_timeout(false);
4293 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4294 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4295 let chanmon_cfgs = create_chanmon_cfgs(3);
4296 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4297 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4298 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4299 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4300 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4302 // Make sure all nodes are at the same starting height
4303 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4304 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4305 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4307 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4308 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4310 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4312 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4313 check_added_monitors!(nodes[1], 1);
4315 // Now attempt to route a second payment, which should be placed in the holding cell
4316 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4317 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4318 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4320 check_added_monitors!(nodes[0], 1);
4321 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4323 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4324 expect_pending_htlcs_forwardable!(nodes[1]);
4326 check_added_monitors!(nodes[1], 0);
4328 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4329 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4330 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4331 connect_blocks(&nodes[1], 1);
4334 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4335 check_added_monitors!(nodes[1], 1);
4336 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4337 assert_eq!(fail_commit.len(), 1);
4338 match fail_commit[0] {
4339 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4340 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4341 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4343 _ => unreachable!(),
4345 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4347 let events = nodes[1].node.get_and_clear_pending_events();
4348 assert_eq!(events.len(), 2);
4349 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4350 assert_eq!(*payment_hash, second_payment_hash);
4351 } else { panic!("Unexpected event"); }
4352 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4353 assert_eq!(*payment_hash, second_payment_hash);
4354 } else { panic!("Unexpected event"); }
4359 fn test_holding_cell_htlc_add_timeouts() {
4360 do_test_holding_cell_htlc_add_timeouts(false);
4361 do_test_holding_cell_htlc_add_timeouts(true);
4365 fn test_no_txn_manager_serialize_deserialize() {
4366 let chanmon_cfgs = create_chanmon_cfgs(2);
4367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4369 let logger: test_utils::TestLogger;
4370 let fee_estimator: test_utils::TestFeeEstimator;
4371 let persister: test_utils::TestPersister;
4372 let new_chain_monitor: test_utils::TestChainMonitor;
4373 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4374 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4376 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4378 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4380 let nodes_0_serialized = nodes[0].node.encode();
4381 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4382 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4383 .write(&mut chan_0_monitor_serialized).unwrap();
4385 logger = test_utils::TestLogger::new();
4386 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4387 persister = test_utils::TestPersister::new();
4388 let keys_manager = &chanmon_cfgs[0].keys_manager;
4389 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4390 nodes[0].chain_monitor = &new_chain_monitor;
4391 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4392 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4393 &mut chan_0_monitor_read, keys_manager).unwrap();
4394 assert!(chan_0_monitor_read.is_empty());
4396 let mut nodes_0_read = &nodes_0_serialized[..];
4397 let config = UserConfig::default();
4398 let (_, nodes_0_deserialized_tmp) = {
4399 let mut channel_monitors = HashMap::new();
4400 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4401 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4402 default_config: config,
4404 fee_estimator: &fee_estimator,
4405 chain_monitor: nodes[0].chain_monitor,
4406 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4411 nodes_0_deserialized = nodes_0_deserialized_tmp;
4412 assert!(nodes_0_read.is_empty());
4414 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4415 nodes[0].node = &nodes_0_deserialized;
4416 assert_eq!(nodes[0].node.list_channels().len(), 1);
4417 check_added_monitors!(nodes[0], 1);
4419 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4420 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4421 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4422 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4424 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4425 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4426 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4427 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4429 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4430 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4431 for node in nodes.iter() {
4432 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4433 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4434 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4437 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4441 fn test_manager_serialize_deserialize_events() {
4442 // This test makes sure the events field in ChannelManager survives de/serialization
4443 let chanmon_cfgs = create_chanmon_cfgs(2);
4444 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4445 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4446 let fee_estimator: test_utils::TestFeeEstimator;
4447 let persister: test_utils::TestPersister;
4448 let logger: test_utils::TestLogger;
4449 let new_chain_monitor: test_utils::TestChainMonitor;
4450 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4451 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4453 // Start creating a channel, but stop right before broadcasting the funding transaction
4454 let channel_value = 100000;
4455 let push_msat = 10001;
4456 let a_flags = InitFeatures::known();
4457 let b_flags = InitFeatures::known();
4458 let node_a = nodes.remove(0);
4459 let node_b = nodes.remove(0);
4460 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4461 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()));
4462 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()));
4464 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4466 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4467 check_added_monitors!(node_a, 0);
4469 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()));
4471 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4472 assert_eq!(added_monitors.len(), 1);
4473 assert_eq!(added_monitors[0].0, funding_output);
4474 added_monitors.clear();
4477 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4478 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4480 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4481 assert_eq!(added_monitors.len(), 1);
4482 assert_eq!(added_monitors[0].0, funding_output);
4483 added_monitors.clear();
4485 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4490 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4491 let nodes_0_serialized = nodes[0].node.encode();
4492 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4493 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4495 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4496 logger = test_utils::TestLogger::new();
4497 persister = test_utils::TestPersister::new();
4498 let keys_manager = &chanmon_cfgs[0].keys_manager;
4499 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4500 nodes[0].chain_monitor = &new_chain_monitor;
4501 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4502 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4503 &mut chan_0_monitor_read, keys_manager).unwrap();
4504 assert!(chan_0_monitor_read.is_empty());
4506 let mut nodes_0_read = &nodes_0_serialized[..];
4507 let config = UserConfig::default();
4508 let (_, nodes_0_deserialized_tmp) = {
4509 let mut channel_monitors = HashMap::new();
4510 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4511 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4512 default_config: config,
4514 fee_estimator: &fee_estimator,
4515 chain_monitor: nodes[0].chain_monitor,
4516 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4521 nodes_0_deserialized = nodes_0_deserialized_tmp;
4522 assert!(nodes_0_read.is_empty());
4524 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4526 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4527 nodes[0].node = &nodes_0_deserialized;
4529 // After deserializing, make sure the funding_transaction is still held by the channel manager
4530 let events_4 = nodes[0].node.get_and_clear_pending_events();
4531 assert_eq!(events_4.len(), 0);
4532 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4533 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4535 // Make sure the channel is functioning as though the de/serialization never happened
4536 assert_eq!(nodes[0].node.list_channels().len(), 1);
4537 check_added_monitors!(nodes[0], 1);
4539 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4540 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4541 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4542 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4544 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4545 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4546 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4547 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4549 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4550 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4551 for node in nodes.iter() {
4552 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4553 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4554 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4557 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4561 fn test_simple_manager_serialize_deserialize() {
4562 let chanmon_cfgs = create_chanmon_cfgs(2);
4563 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4564 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4565 let logger: test_utils::TestLogger;
4566 let fee_estimator: test_utils::TestFeeEstimator;
4567 let persister: test_utils::TestPersister;
4568 let new_chain_monitor: test_utils::TestChainMonitor;
4569 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4570 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4571 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4573 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4574 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4576 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4578 let nodes_0_serialized = nodes[0].node.encode();
4579 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4580 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4582 logger = test_utils::TestLogger::new();
4583 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4584 persister = test_utils::TestPersister::new();
4585 let keys_manager = &chanmon_cfgs[0].keys_manager;
4586 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4587 nodes[0].chain_monitor = &new_chain_monitor;
4588 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4589 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4590 &mut chan_0_monitor_read, keys_manager).unwrap();
4591 assert!(chan_0_monitor_read.is_empty());
4593 let mut nodes_0_read = &nodes_0_serialized[..];
4594 let (_, nodes_0_deserialized_tmp) = {
4595 let mut channel_monitors = HashMap::new();
4596 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4597 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4598 default_config: UserConfig::default(),
4600 fee_estimator: &fee_estimator,
4601 chain_monitor: nodes[0].chain_monitor,
4602 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4607 nodes_0_deserialized = nodes_0_deserialized_tmp;
4608 assert!(nodes_0_read.is_empty());
4610 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4611 nodes[0].node = &nodes_0_deserialized;
4612 check_added_monitors!(nodes[0], 1);
4614 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4616 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4617 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4621 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4622 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4623 let chanmon_cfgs = create_chanmon_cfgs(4);
4624 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4625 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4626 let logger: test_utils::TestLogger;
4627 let fee_estimator: test_utils::TestFeeEstimator;
4628 let persister: test_utils::TestPersister;
4629 let new_chain_monitor: test_utils::TestChainMonitor;
4630 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4631 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4632 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4633 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4634 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4636 let mut node_0_stale_monitors_serialized = Vec::new();
4637 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4638 let mut writer = test_utils::TestVecWriter(Vec::new());
4639 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4640 node_0_stale_monitors_serialized.push(writer.0);
4643 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4645 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4646 let nodes_0_serialized = nodes[0].node.encode();
4648 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4649 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4650 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4651 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4653 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4655 let mut node_0_monitors_serialized = Vec::new();
4656 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4657 let mut writer = test_utils::TestVecWriter(Vec::new());
4658 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4659 node_0_monitors_serialized.push(writer.0);
4662 logger = test_utils::TestLogger::new();
4663 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4664 persister = test_utils::TestPersister::new();
4665 let keys_manager = &chanmon_cfgs[0].keys_manager;
4666 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4667 nodes[0].chain_monitor = &new_chain_monitor;
4670 let mut node_0_stale_monitors = Vec::new();
4671 for serialized in node_0_stale_monitors_serialized.iter() {
4672 let mut read = &serialized[..];
4673 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4674 assert!(read.is_empty());
4675 node_0_stale_monitors.push(monitor);
4678 let mut node_0_monitors = Vec::new();
4679 for serialized in node_0_monitors_serialized.iter() {
4680 let mut read = &serialized[..];
4681 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4682 assert!(read.is_empty());
4683 node_0_monitors.push(monitor);
4686 let mut nodes_0_read = &nodes_0_serialized[..];
4687 if let Err(msgs::DecodeError::InvalidValue) =
4688 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4689 default_config: UserConfig::default(),
4691 fee_estimator: &fee_estimator,
4692 chain_monitor: nodes[0].chain_monitor,
4693 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4695 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4697 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4700 let mut nodes_0_read = &nodes_0_serialized[..];
4701 let (_, nodes_0_deserialized_tmp) =
4702 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4703 default_config: UserConfig::default(),
4705 fee_estimator: &fee_estimator,
4706 chain_monitor: nodes[0].chain_monitor,
4707 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4709 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4711 nodes_0_deserialized = nodes_0_deserialized_tmp;
4712 assert!(nodes_0_read.is_empty());
4714 { // Channel close should result in a commitment tx
4715 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4716 assert_eq!(txn.len(), 1);
4717 check_spends!(txn[0], funding_tx);
4718 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4721 for monitor in node_0_monitors.drain(..) {
4722 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4723 check_added_monitors!(nodes[0], 1);
4725 nodes[0].node = &nodes_0_deserialized;
4726 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4728 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4729 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4730 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4731 //... and we can even still claim the payment!
4732 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4734 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4735 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4736 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4737 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4738 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4739 assert_eq!(msg_events.len(), 1);
4740 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4742 &ErrorAction::SendErrorMessage { ref msg } => {
4743 assert_eq!(msg.channel_id, channel_id);
4745 _ => panic!("Unexpected event!"),
4750 macro_rules! check_spendable_outputs {
4751 ($node: expr, $keysinterface: expr) => {
4753 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4754 let mut txn = Vec::new();
4755 let mut all_outputs = Vec::new();
4756 let secp_ctx = Secp256k1::new();
4757 for event in events.drain(..) {
4759 Event::SpendableOutputs { mut outputs } => {
4760 for outp in outputs.drain(..) {
4761 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4762 all_outputs.push(outp);
4765 _ => panic!("Unexpected event"),
4768 if all_outputs.len() > 1 {
4769 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) {
4779 fn test_claim_sizeable_push_msat() {
4780 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4781 let chanmon_cfgs = create_chanmon_cfgs(2);
4782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4784 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4786 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4787 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4788 check_closed_broadcast!(nodes[1], true);
4789 check_added_monitors!(nodes[1], 1);
4790 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4791 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4792 assert_eq!(node_txn.len(), 1);
4793 check_spends!(node_txn[0], chan.3);
4794 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
4796 mine_transaction(&nodes[1], &node_txn[0]);
4797 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4799 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4800 assert_eq!(spend_txn.len(), 1);
4801 assert_eq!(spend_txn[0].input.len(), 1);
4802 check_spends!(spend_txn[0], node_txn[0]);
4803 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4807 fn test_claim_on_remote_sizeable_push_msat() {
4808 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4809 // to_remote output is encumbered by a P2WPKH
4810 let chanmon_cfgs = create_chanmon_cfgs(2);
4811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4813 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4815 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4816 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4817 check_closed_broadcast!(nodes[0], true);
4818 check_added_monitors!(nodes[0], 1);
4819 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4821 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4822 assert_eq!(node_txn.len(), 1);
4823 check_spends!(node_txn[0], chan.3);
4824 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
4826 mine_transaction(&nodes[1], &node_txn[0]);
4827 check_closed_broadcast!(nodes[1], true);
4828 check_added_monitors!(nodes[1], 1);
4829 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4830 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4832 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4833 assert_eq!(spend_txn.len(), 1);
4834 check_spends!(spend_txn[0], node_txn[0]);
4838 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4839 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4840 // to_remote output is encumbered by a P2WPKH
4842 let chanmon_cfgs = create_chanmon_cfgs(2);
4843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4847 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4848 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4849 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4850 assert_eq!(revoked_local_txn[0].input.len(), 1);
4851 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4853 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4854 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4855 check_closed_broadcast!(nodes[1], true);
4856 check_added_monitors!(nodes[1], 1);
4857 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4859 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4860 mine_transaction(&nodes[1], &node_txn[0]);
4861 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4863 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4864 assert_eq!(spend_txn.len(), 3);
4865 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4866 check_spends!(spend_txn[1], node_txn[0]);
4867 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4871 fn test_static_spendable_outputs_preimage_tx() {
4872 let chanmon_cfgs = create_chanmon_cfgs(2);
4873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4875 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4877 // Create some initial channels
4878 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4880 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4882 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4883 assert_eq!(commitment_tx[0].input.len(), 1);
4884 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4886 // Settle A's commitment tx on B's chain
4887 nodes[1].node.claim_funds(payment_preimage);
4888 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4889 check_added_monitors!(nodes[1], 1);
4890 mine_transaction(&nodes[1], &commitment_tx[0]);
4891 check_added_monitors!(nodes[1], 1);
4892 let events = nodes[1].node.get_and_clear_pending_msg_events();
4894 MessageSendEvent::UpdateHTLCs { .. } => {},
4895 _ => panic!("Unexpected event"),
4898 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4899 _ => panic!("Unexepected event"),
4902 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4903 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4904 assert_eq!(node_txn.len(), 3);
4905 check_spends!(node_txn[0], commitment_tx[0]);
4906 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4907 check_spends!(node_txn[1], chan_1.3);
4908 check_spends!(node_txn[2], node_txn[1]);
4910 mine_transaction(&nodes[1], &node_txn[0]);
4911 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4912 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4914 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4915 assert_eq!(spend_txn.len(), 1);
4916 check_spends!(spend_txn[0], node_txn[0]);
4920 fn test_static_spendable_outputs_timeout_tx() {
4921 let chanmon_cfgs = create_chanmon_cfgs(2);
4922 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4923 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4924 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4926 // Create some initial channels
4927 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4929 // Rebalance the network a bit by relaying one payment through all the channels ...
4930 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4932 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4934 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4935 assert_eq!(commitment_tx[0].input.len(), 1);
4936 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4938 // Settle A's commitment tx on B' chain
4939 mine_transaction(&nodes[1], &commitment_tx[0]);
4940 check_added_monitors!(nodes[1], 1);
4941 let events = nodes[1].node.get_and_clear_pending_msg_events();
4943 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4944 _ => panic!("Unexpected event"),
4946 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4948 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4949 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4950 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4951 check_spends!(node_txn[0], chan_1.3.clone());
4952 check_spends!(node_txn[1], commitment_tx[0].clone());
4953 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4955 mine_transaction(&nodes[1], &node_txn[1]);
4956 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4957 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4958 expect_payment_failed!(nodes[1], our_payment_hash, true);
4960 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4961 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4962 check_spends!(spend_txn[0], commitment_tx[0]);
4963 check_spends!(spend_txn[1], node_txn[1]);
4964 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4968 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4969 let chanmon_cfgs = create_chanmon_cfgs(2);
4970 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4971 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4972 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4974 // Create some initial channels
4975 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4977 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4978 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4979 assert_eq!(revoked_local_txn[0].input.len(), 1);
4980 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4982 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4984 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4985 check_closed_broadcast!(nodes[1], true);
4986 check_added_monitors!(nodes[1], 1);
4987 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4989 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4990 assert_eq!(node_txn.len(), 2);
4991 assert_eq!(node_txn[0].input.len(), 2);
4992 check_spends!(node_txn[0], revoked_local_txn[0]);
4994 mine_transaction(&nodes[1], &node_txn[0]);
4995 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4997 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4998 assert_eq!(spend_txn.len(), 1);
4999 check_spends!(spend_txn[0], node_txn[0]);
5003 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5004 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5005 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5008 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5010 // Create some initial channels
5011 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5013 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5014 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5015 assert_eq!(revoked_local_txn[0].input.len(), 1);
5016 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5018 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5020 // A will generate HTLC-Timeout from revoked commitment tx
5021 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5022 check_closed_broadcast!(nodes[0], true);
5023 check_added_monitors!(nodes[0], 1);
5024 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5025 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5027 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5028 assert_eq!(revoked_htlc_txn.len(), 2);
5029 check_spends!(revoked_htlc_txn[0], chan_1.3);
5030 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5031 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5032 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5033 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5035 // B will generate justice tx from A's revoked commitment/HTLC tx
5036 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5037 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5038 check_closed_broadcast!(nodes[1], true);
5039 check_added_monitors!(nodes[1], 1);
5040 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5042 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5043 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5044 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5045 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5046 // transactions next...
5047 assert_eq!(node_txn[0].input.len(), 3);
5048 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5050 assert_eq!(node_txn[1].input.len(), 2);
5051 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5052 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5053 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5055 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5056 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5059 assert_eq!(node_txn[2].input.len(), 1);
5060 check_spends!(node_txn[2], chan_1.3);
5062 mine_transaction(&nodes[1], &node_txn[1]);
5063 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5065 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5066 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5067 assert_eq!(spend_txn.len(), 1);
5068 assert_eq!(spend_txn[0].input.len(), 1);
5069 check_spends!(spend_txn[0], node_txn[1]);
5073 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5074 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5075 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5076 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5077 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5078 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5080 // Create some initial channels
5081 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5083 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5084 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5085 assert_eq!(revoked_local_txn[0].input.len(), 1);
5086 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5088 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5089 assert_eq!(revoked_local_txn[0].output.len(), 2);
5091 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5093 // B will generate HTLC-Success from revoked commitment tx
5094 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5095 check_closed_broadcast!(nodes[1], true);
5096 check_added_monitors!(nodes[1], 1);
5097 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5098 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5100 assert_eq!(revoked_htlc_txn.len(), 2);
5101 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5102 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5103 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5105 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5106 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5107 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5109 // A will generate justice tx from B's revoked commitment/HTLC tx
5110 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5111 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5112 check_closed_broadcast!(nodes[0], true);
5113 check_added_monitors!(nodes[0], 1);
5114 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5116 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5117 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5119 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5120 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5121 // transactions next...
5122 assert_eq!(node_txn[0].input.len(), 2);
5123 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5124 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5125 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5127 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5128 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5131 assert_eq!(node_txn[1].input.len(), 1);
5132 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5134 check_spends!(node_txn[2], chan_1.3);
5136 mine_transaction(&nodes[0], &node_txn[1]);
5137 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5139 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5140 // didn't try to generate any new transactions.
5142 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5143 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5144 assert_eq!(spend_txn.len(), 3);
5145 assert_eq!(spend_txn[0].input.len(), 1);
5146 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5147 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5148 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5149 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5153 fn test_onchain_to_onchain_claim() {
5154 // Test that in case of channel closure, we detect the state of output and claim HTLC
5155 // on downstream peer's remote commitment tx.
5156 // First, have C claim an HTLC against its own latest commitment transaction.
5157 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5159 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5162 let chanmon_cfgs = create_chanmon_cfgs(3);
5163 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5164 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5165 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5167 // Create some initial channels
5168 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5169 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5171 // Ensure all nodes are at the same height
5172 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5173 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5174 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5175 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5177 // Rebalance the network a bit by relaying one payment through all the channels ...
5178 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5179 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5181 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5182 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5183 check_spends!(commitment_tx[0], chan_2.3);
5184 nodes[2].node.claim_funds(payment_preimage);
5185 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5186 check_added_monitors!(nodes[2], 1);
5187 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5188 assert!(updates.update_add_htlcs.is_empty());
5189 assert!(updates.update_fail_htlcs.is_empty());
5190 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5191 assert!(updates.update_fail_malformed_htlcs.is_empty());
5193 mine_transaction(&nodes[2], &commitment_tx[0]);
5194 check_closed_broadcast!(nodes[2], true);
5195 check_added_monitors!(nodes[2], 1);
5196 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5198 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5199 assert_eq!(c_txn.len(), 3);
5200 assert_eq!(c_txn[0], c_txn[2]);
5201 assert_eq!(commitment_tx[0], c_txn[1]);
5202 check_spends!(c_txn[1], chan_2.3);
5203 check_spends!(c_txn[2], c_txn[1]);
5204 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5205 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5206 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5207 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5209 // 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
5210 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5211 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5212 check_added_monitors!(nodes[1], 1);
5213 let events = nodes[1].node.get_and_clear_pending_events();
5214 assert_eq!(events.len(), 2);
5216 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5217 _ => panic!("Unexpected event"),
5220 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5221 assert_eq!(fee_earned_msat, Some(1000));
5222 assert_eq!(prev_channel_id, Some(chan_1.2));
5223 assert_eq!(claim_from_onchain_tx, true);
5224 assert_eq!(next_channel_id, Some(chan_2.2));
5226 _ => panic!("Unexpected event"),
5229 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5230 // ChannelMonitor: claim tx
5231 assert_eq!(b_txn.len(), 1);
5232 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5235 check_added_monitors!(nodes[1], 1);
5236 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5237 assert_eq!(msg_events.len(), 3);
5238 match msg_events[0] {
5239 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5240 _ => panic!("Unexpected event"),
5242 match msg_events[1] {
5243 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5244 _ => panic!("Unexpected event"),
5246 match msg_events[2] {
5247 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, .. } } => {
5248 assert!(update_add_htlcs.is_empty());
5249 assert!(update_fail_htlcs.is_empty());
5250 assert_eq!(update_fulfill_htlcs.len(), 1);
5251 assert!(update_fail_malformed_htlcs.is_empty());
5252 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5254 _ => panic!("Unexpected event"),
5256 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5257 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5258 mine_transaction(&nodes[1], &commitment_tx[0]);
5259 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5260 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5261 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5262 assert_eq!(b_txn.len(), 3);
5263 check_spends!(b_txn[1], chan_1.3);
5264 check_spends!(b_txn[2], b_txn[1]);
5265 check_spends!(b_txn[0], commitment_tx[0]);
5266 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5267 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5268 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5270 check_closed_broadcast!(nodes[1], true);
5271 check_added_monitors!(nodes[1], 1);
5275 fn test_duplicate_payment_hash_one_failure_one_success() {
5276 // Topology : A --> B --> C --> D
5277 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5278 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5279 // we forward one of the payments onwards to D.
5280 let chanmon_cfgs = create_chanmon_cfgs(4);
5281 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5282 // When this test was written, the default base fee floated based on the HTLC count.
5283 // It is now fixed, so we simply set the fee to the expected value here.
5284 let mut config = test_default_channel_config();
5285 config.channel_config.forwarding_fee_base_msat = 196;
5286 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5287 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5288 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5290 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5291 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5292 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5294 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5295 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5296 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5297 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5298 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5300 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5302 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5303 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5304 // script push size limit so that the below script length checks match
5305 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5306 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5307 .with_features(InvoiceFeatures::known());
5308 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5309 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5311 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5312 assert_eq!(commitment_txn[0].input.len(), 1);
5313 check_spends!(commitment_txn[0], chan_2.3);
5315 mine_transaction(&nodes[1], &commitment_txn[0]);
5316 check_closed_broadcast!(nodes[1], true);
5317 check_added_monitors!(nodes[1], 1);
5318 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5319 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5321 let htlc_timeout_tx;
5322 { // Extract one of the two HTLC-Timeout transaction
5323 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5324 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5325 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5326 check_spends!(node_txn[0], chan_2.3);
5328 check_spends!(node_txn[1], commitment_txn[0]);
5329 assert_eq!(node_txn[1].input.len(), 1);
5331 if node_txn.len() > 3 {
5332 check_spends!(node_txn[2], commitment_txn[0]);
5333 assert_eq!(node_txn[2].input.len(), 1);
5334 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5336 check_spends!(node_txn[3], commitment_txn[0]);
5337 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5339 check_spends!(node_txn[2], commitment_txn[0]);
5340 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5343 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5344 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5345 if node_txn.len() > 3 {
5346 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5348 htlc_timeout_tx = node_txn[1].clone();
5351 nodes[2].node.claim_funds(our_payment_preimage);
5352 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5354 mine_transaction(&nodes[2], &commitment_txn[0]);
5355 check_added_monitors!(nodes[2], 2);
5356 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5357 let events = nodes[2].node.get_and_clear_pending_msg_events();
5359 MessageSendEvent::UpdateHTLCs { .. } => {},
5360 _ => panic!("Unexpected event"),
5363 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5364 _ => panic!("Unexepected event"),
5366 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5367 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)
5368 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5369 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5370 assert_eq!(htlc_success_txn[0].input.len(), 1);
5371 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5372 assert_eq!(htlc_success_txn[1].input.len(), 1);
5373 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5374 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5375 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5376 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5377 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5378 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5380 mine_transaction(&nodes[1], &htlc_timeout_tx);
5381 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5382 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
5383 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5384 assert!(htlc_updates.update_add_htlcs.is_empty());
5385 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5386 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5387 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5388 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5389 check_added_monitors!(nodes[1], 1);
5391 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5392 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5394 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5396 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5398 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5399 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5400 // and nodes[2] fee) is rounded down and then claimed in full.
5401 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5402 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5403 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5404 assert!(updates.update_add_htlcs.is_empty());
5405 assert!(updates.update_fail_htlcs.is_empty());
5406 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5407 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5408 assert!(updates.update_fail_malformed_htlcs.is_empty());
5409 check_added_monitors!(nodes[1], 1);
5411 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5412 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5414 let events = nodes[0].node.get_and_clear_pending_events();
5416 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5417 assert_eq!(*payment_preimage, our_payment_preimage);
5418 assert_eq!(*payment_hash, duplicate_payment_hash);
5420 _ => panic!("Unexpected event"),
5425 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5426 let chanmon_cfgs = create_chanmon_cfgs(2);
5427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5431 // Create some initial channels
5432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5434 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5435 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5436 assert_eq!(local_txn.len(), 1);
5437 assert_eq!(local_txn[0].input.len(), 1);
5438 check_spends!(local_txn[0], chan_1.3);
5440 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5441 nodes[1].node.claim_funds(payment_preimage);
5442 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5443 check_added_monitors!(nodes[1], 1);
5445 mine_transaction(&nodes[1], &local_txn[0]);
5446 check_added_monitors!(nodes[1], 1);
5447 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5448 let events = nodes[1].node.get_and_clear_pending_msg_events();
5450 MessageSendEvent::UpdateHTLCs { .. } => {},
5451 _ => panic!("Unexpected event"),
5454 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5455 _ => panic!("Unexepected event"),
5458 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5459 assert_eq!(node_txn.len(), 3);
5460 assert_eq!(node_txn[0], node_txn[2]);
5461 assert_eq!(node_txn[1], local_txn[0]);
5462 assert_eq!(node_txn[0].input.len(), 1);
5463 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5464 check_spends!(node_txn[0], local_txn[0]);
5468 mine_transaction(&nodes[1], &node_tx);
5469 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5471 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5472 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5473 assert_eq!(spend_txn.len(), 1);
5474 assert_eq!(spend_txn[0].input.len(), 1);
5475 check_spends!(spend_txn[0], node_tx);
5476 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5479 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5480 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5481 // unrevoked commitment transaction.
5482 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5483 // a remote RAA before they could be failed backwards (and combinations thereof).
5484 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5485 // use the same payment hashes.
5486 // Thus, we use a six-node network:
5491 // And test where C fails back to A/B when D announces its latest commitment transaction
5492 let chanmon_cfgs = create_chanmon_cfgs(6);
5493 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5494 // When this test was written, the default base fee floated based on the HTLC count.
5495 // It is now fixed, so we simply set the fee to the expected value here.
5496 let mut config = test_default_channel_config();
5497 config.channel_config.forwarding_fee_base_msat = 196;
5498 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5499 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5500 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5502 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5503 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5504 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5505 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5506 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5508 // Rebalance and check output sanity...
5509 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5510 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5511 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5513 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5515 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
5517 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
5518 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5520 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
5522 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
5524 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5526 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5527 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5529 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());
5531 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());
5534 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5536 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5537 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
5540 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
5542 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5543 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());
5545 // Double-check that six of the new HTLC were added
5546 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5547 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5548 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5549 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5551 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5552 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5553 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5554 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5555 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5556 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5557 check_added_monitors!(nodes[4], 0);
5559 let failed_destinations = vec![
5560 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5561 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5562 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5563 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5565 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5566 check_added_monitors!(nodes[4], 1);
5568 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5569 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5570 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5571 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5572 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5573 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5575 // Fail 3rd below-dust and 7th above-dust HTLCs
5576 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5577 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5578 check_added_monitors!(nodes[5], 0);
5580 let failed_destinations_2 = vec![
5581 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5582 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5584 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5585 check_added_monitors!(nodes[5], 1);
5587 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5588 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5589 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5590 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5592 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5594 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5595 let failed_destinations_3 = vec![
5596 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5597 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5598 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5599 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5600 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5601 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5603 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5604 check_added_monitors!(nodes[3], 1);
5605 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5606 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5607 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5608 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5609 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5610 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5611 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5612 if deliver_last_raa {
5613 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5615 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5618 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5619 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5620 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5621 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5623 // We now broadcast the latest commitment transaction, which *should* result in failures for
5624 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5625 // the non-broadcast above-dust HTLCs.
5627 // Alternatively, we may broadcast the previous commitment transaction, which should only
5628 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5629 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5631 if announce_latest {
5632 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5634 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5636 let events = nodes[2].node.get_and_clear_pending_events();
5637 let close_event = if deliver_last_raa {
5638 assert_eq!(events.len(), 2 + 6);
5639 events.last().clone().unwrap()
5641 assert_eq!(events.len(), 1);
5642 events.last().clone().unwrap()
5645 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5646 _ => panic!("Unexpected event"),
5649 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5650 check_closed_broadcast!(nodes[2], true);
5651 if deliver_last_raa {
5652 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5654 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5655 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5657 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5658 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5660 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5663 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5665 check_added_monitors!(nodes[2], 3);
5667 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5668 assert_eq!(cs_msgs.len(), 2);
5669 let mut a_done = false;
5670 for msg in cs_msgs {
5672 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5673 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5674 // should be failed-backwards here.
5675 let target = if *node_id == nodes[0].node.get_our_node_id() {
5676 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5677 for htlc in &updates.update_fail_htlcs {
5678 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 });
5680 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5685 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5686 for htlc in &updates.update_fail_htlcs {
5687 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5689 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5690 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5693 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5694 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5695 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5696 if announce_latest {
5697 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5698 if *node_id == nodes[0].node.get_our_node_id() {
5699 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5702 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5704 _ => panic!("Unexpected event"),
5708 let as_events = nodes[0].node.get_and_clear_pending_events();
5709 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5710 let mut as_failds = HashSet::new();
5711 let mut as_updates = 0;
5712 for event in as_events.iter() {
5713 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5714 assert!(as_failds.insert(*payment_hash));
5715 if *payment_hash != payment_hash_2 {
5716 assert_eq!(*rejected_by_dest, deliver_last_raa);
5718 assert!(!rejected_by_dest);
5720 if network_update.is_some() {
5723 } else { panic!("Unexpected event"); }
5725 assert!(as_failds.contains(&payment_hash_1));
5726 assert!(as_failds.contains(&payment_hash_2));
5727 if announce_latest {
5728 assert!(as_failds.contains(&payment_hash_3));
5729 assert!(as_failds.contains(&payment_hash_5));
5731 assert!(as_failds.contains(&payment_hash_6));
5733 let bs_events = nodes[1].node.get_and_clear_pending_events();
5734 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5735 let mut bs_failds = HashSet::new();
5736 let mut bs_updates = 0;
5737 for event in bs_events.iter() {
5738 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5739 assert!(bs_failds.insert(*payment_hash));
5740 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5741 assert_eq!(*rejected_by_dest, deliver_last_raa);
5743 assert!(!rejected_by_dest);
5745 if network_update.is_some() {
5748 } else { panic!("Unexpected event"); }
5750 assert!(bs_failds.contains(&payment_hash_1));
5751 assert!(bs_failds.contains(&payment_hash_2));
5752 if announce_latest {
5753 assert!(bs_failds.contains(&payment_hash_4));
5755 assert!(bs_failds.contains(&payment_hash_5));
5757 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5758 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5759 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5760 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5761 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5762 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5766 fn test_fail_backwards_latest_remote_announce_a() {
5767 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5771 fn test_fail_backwards_latest_remote_announce_b() {
5772 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5776 fn test_fail_backwards_previous_remote_announce() {
5777 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5778 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5779 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5783 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5784 let chanmon_cfgs = create_chanmon_cfgs(2);
5785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5789 // Create some initial channels
5790 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5792 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5793 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5794 assert_eq!(local_txn[0].input.len(), 1);
5795 check_spends!(local_txn[0], chan_1.3);
5797 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5798 mine_transaction(&nodes[0], &local_txn[0]);
5799 check_closed_broadcast!(nodes[0], true);
5800 check_added_monitors!(nodes[0], 1);
5801 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5802 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5804 let htlc_timeout = {
5805 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5806 assert_eq!(node_txn.len(), 2);
5807 check_spends!(node_txn[0], chan_1.3);
5808 assert_eq!(node_txn[1].input.len(), 1);
5809 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5810 check_spends!(node_txn[1], local_txn[0]);
5814 mine_transaction(&nodes[0], &htlc_timeout);
5815 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5816 expect_payment_failed!(nodes[0], our_payment_hash, true);
5818 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5819 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5820 assert_eq!(spend_txn.len(), 3);
5821 check_spends!(spend_txn[0], local_txn[0]);
5822 assert_eq!(spend_txn[1].input.len(), 1);
5823 check_spends!(spend_txn[1], htlc_timeout);
5824 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5825 assert_eq!(spend_txn[2].input.len(), 2);
5826 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5827 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5828 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5832 fn test_key_derivation_params() {
5833 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5834 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5835 // let us re-derive the channel key set to then derive a delayed_payment_key.
5837 let chanmon_cfgs = create_chanmon_cfgs(3);
5839 // We manually create the node configuration to backup the seed.
5840 let seed = [42; 32];
5841 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5842 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);
5843 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5844 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, features: InitFeatures::known() };
5845 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5846 node_cfgs.remove(0);
5847 node_cfgs.insert(0, node);
5849 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5850 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5852 // Create some initial channels
5853 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5855 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5856 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5857 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5859 // Ensure all nodes are at the same height
5860 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5861 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5862 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5863 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5865 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5866 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5867 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5868 assert_eq!(local_txn_1[0].input.len(), 1);
5869 check_spends!(local_txn_1[0], chan_1.3);
5871 // We check funding pubkey are unique
5872 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5873 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5874 if from_0_funding_key_0 == from_1_funding_key_0
5875 || from_0_funding_key_0 == from_1_funding_key_1
5876 || from_0_funding_key_1 == from_1_funding_key_0
5877 || from_0_funding_key_1 == from_1_funding_key_1 {
5878 panic!("Funding pubkeys aren't unique");
5881 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5882 mine_transaction(&nodes[0], &local_txn_1[0]);
5883 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5884 check_closed_broadcast!(nodes[0], true);
5885 check_added_monitors!(nodes[0], 1);
5886 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5888 let htlc_timeout = {
5889 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5890 assert_eq!(node_txn[1].input.len(), 1);
5891 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5892 check_spends!(node_txn[1], local_txn_1[0]);
5896 mine_transaction(&nodes[0], &htlc_timeout);
5897 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5898 expect_payment_failed!(nodes[0], our_payment_hash, true);
5900 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5901 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5902 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5903 assert_eq!(spend_txn.len(), 3);
5904 check_spends!(spend_txn[0], local_txn_1[0]);
5905 assert_eq!(spend_txn[1].input.len(), 1);
5906 check_spends!(spend_txn[1], htlc_timeout);
5907 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5908 assert_eq!(spend_txn[2].input.len(), 2);
5909 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5910 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5911 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5915 fn test_static_output_closing_tx() {
5916 let chanmon_cfgs = create_chanmon_cfgs(2);
5917 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5918 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5919 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5921 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5923 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5924 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5926 mine_transaction(&nodes[0], &closing_tx);
5927 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5928 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5930 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5931 assert_eq!(spend_txn.len(), 1);
5932 check_spends!(spend_txn[0], closing_tx);
5934 mine_transaction(&nodes[1], &closing_tx);
5935 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5936 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5938 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5939 assert_eq!(spend_txn.len(), 1);
5940 check_spends!(spend_txn[0], closing_tx);
5943 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5944 let chanmon_cfgs = create_chanmon_cfgs(2);
5945 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5946 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5947 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5948 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5950 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5952 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5953 // present in B's local commitment transaction, but none of A's commitment transactions.
5954 nodes[1].node.claim_funds(payment_preimage);
5955 check_added_monitors!(nodes[1], 1);
5956 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5958 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5959 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5960 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5962 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5963 check_added_monitors!(nodes[0], 1);
5964 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5966 check_added_monitors!(nodes[1], 1);
5968 let starting_block = nodes[1].best_block_info();
5969 let mut block = Block {
5970 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5973 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5974 connect_block(&nodes[1], &block);
5975 block.header.prev_blockhash = block.block_hash();
5977 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5978 check_closed_broadcast!(nodes[1], true);
5979 check_added_monitors!(nodes[1], 1);
5980 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5983 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5984 let chanmon_cfgs = create_chanmon_cfgs(2);
5985 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5986 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5987 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5988 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5990 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5991 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5992 check_added_monitors!(nodes[0], 1);
5994 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5996 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5997 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5998 // to "time out" the HTLC.
6000 let starting_block = nodes[1].best_block_info();
6001 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6003 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6004 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6005 header.prev_blockhash = header.block_hash();
6007 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6008 check_closed_broadcast!(nodes[0], true);
6009 check_added_monitors!(nodes[0], 1);
6010 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6013 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6014 let chanmon_cfgs = create_chanmon_cfgs(3);
6015 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6016 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6017 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6018 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6020 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6021 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6022 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6023 // actually revoked.
6024 let htlc_value = if use_dust { 50000 } else { 3000000 };
6025 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6026 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6027 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6028 check_added_monitors!(nodes[1], 1);
6030 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6031 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6032 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6033 check_added_monitors!(nodes[0], 1);
6034 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6035 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6036 check_added_monitors!(nodes[1], 1);
6037 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6038 check_added_monitors!(nodes[1], 1);
6039 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6041 if check_revoke_no_close {
6042 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6043 check_added_monitors!(nodes[0], 1);
6046 let starting_block = nodes[1].best_block_info();
6047 let mut block = Block {
6048 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6051 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6052 connect_block(&nodes[0], &block);
6053 block.header.prev_blockhash = block.block_hash();
6055 if !check_revoke_no_close {
6056 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6057 check_closed_broadcast!(nodes[0], true);
6058 check_added_monitors!(nodes[0], 1);
6059 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6061 let events = nodes[0].node.get_and_clear_pending_events();
6062 assert_eq!(events.len(), 2);
6063 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6064 assert_eq!(*payment_hash, our_payment_hash);
6065 } else { panic!("Unexpected event"); }
6066 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6067 assert_eq!(*payment_hash, our_payment_hash);
6068 } else { panic!("Unexpected event"); }
6072 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6073 // There are only a few cases to test here:
6074 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6075 // broadcastable commitment transactions result in channel closure,
6076 // * its included in an unrevoked-but-previous remote commitment transaction,
6077 // * its included in the latest remote or local commitment transactions.
6078 // We test each of the three possible commitment transactions individually and use both dust and
6080 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6081 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6082 // tested for at least one of the cases in other tests.
6084 fn htlc_claim_single_commitment_only_a() {
6085 do_htlc_claim_local_commitment_only(true);
6086 do_htlc_claim_local_commitment_only(false);
6088 do_htlc_claim_current_remote_commitment_only(true);
6089 do_htlc_claim_current_remote_commitment_only(false);
6093 fn htlc_claim_single_commitment_only_b() {
6094 do_htlc_claim_previous_remote_commitment_only(true, false);
6095 do_htlc_claim_previous_remote_commitment_only(false, false);
6096 do_htlc_claim_previous_remote_commitment_only(true, true);
6097 do_htlc_claim_previous_remote_commitment_only(false, true);
6102 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6103 let chanmon_cfgs = create_chanmon_cfgs(2);
6104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6106 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6107 // Force duplicate randomness for every get-random call
6108 for node in nodes.iter() {
6109 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6112 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6113 let channel_value_satoshis=10000;
6114 let push_msat=10001;
6115 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6116 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6117 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6118 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6120 // Create a second channel with the same random values. This used to panic due to a colliding
6121 // channel_id, but now panics due to a colliding outbound SCID alias.
6122 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6126 fn bolt2_open_channel_sending_node_checks_part2() {
6127 let chanmon_cfgs = create_chanmon_cfgs(2);
6128 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6129 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6130 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6132 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6133 let channel_value_satoshis=2^24;
6134 let push_msat=10001;
6135 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6137 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6138 let channel_value_satoshis=10000;
6139 // Test when push_msat is equal to 1000 * funding_satoshis.
6140 let push_msat=1000*channel_value_satoshis+1;
6141 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6143 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6144 let channel_value_satoshis=10000;
6145 let push_msat=10001;
6146 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
6147 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6148 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6150 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6151 // 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
6152 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6154 // 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.
6155 assert!(BREAKDOWN_TIMEOUT>0);
6156 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6158 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6159 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6160 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6162 // 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.
6163 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6164 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6165 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6166 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6167 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6171 fn bolt2_open_channel_sane_dust_limit() {
6172 let chanmon_cfgs = create_chanmon_cfgs(2);
6173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6177 let channel_value_satoshis=1000000;
6178 let push_msat=10001;
6179 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6180 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6181 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6182 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6184 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6185 let events = nodes[1].node.get_and_clear_pending_msg_events();
6186 let err_msg = match events[0] {
6187 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6190 _ => panic!("Unexpected event"),
6192 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6195 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6196 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6197 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6198 // is no longer affordable once it's freed.
6200 fn test_fail_holding_cell_htlc_upon_free() {
6201 let chanmon_cfgs = create_chanmon_cfgs(2);
6202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6204 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6205 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6207 // First nodes[0] generates an update_fee, setting the channel's
6208 // pending_update_fee.
6210 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6211 *feerate_lock += 20;
6213 nodes[0].node.timer_tick_occurred();
6214 check_added_monitors!(nodes[0], 1);
6216 let events = nodes[0].node.get_and_clear_pending_msg_events();
6217 assert_eq!(events.len(), 1);
6218 let (update_msg, commitment_signed) = match events[0] {
6219 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6220 (update_fee.as_ref(), commitment_signed)
6222 _ => panic!("Unexpected event"),
6225 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6227 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6228 let channel_reserve = chan_stat.channel_reserve_msat;
6229 let feerate = get_feerate!(nodes[0], chan.2);
6230 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6232 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6233 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6234 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6236 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6237 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6238 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6239 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6241 // Flush the pending fee update.
6242 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6243 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6244 check_added_monitors!(nodes[1], 1);
6245 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6246 check_added_monitors!(nodes[0], 1);
6248 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6249 // HTLC, but now that the fee has been raised the payment will now fail, causing
6250 // us to surface its failure to the user.
6251 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6252 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6253 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);
6254 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 {}",
6255 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6256 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6258 // Check that the payment failed to be sent out.
6259 let events = nodes[0].node.get_and_clear_pending_events();
6260 assert_eq!(events.len(), 1);
6262 &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, .. } => {
6263 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6264 assert_eq!(our_payment_hash.clone(), *payment_hash);
6265 assert_eq!(*rejected_by_dest, false);
6266 assert_eq!(*all_paths_failed, true);
6267 assert_eq!(*network_update, None);
6268 assert_eq!(*short_channel_id, None);
6269 assert_eq!(*error_code, None);
6270 assert_eq!(*error_data, None);
6272 _ => panic!("Unexpected event"),
6276 // Test that if multiple HTLCs are released from the holding cell and one is
6277 // valid but the other is no longer valid upon release, the valid HTLC can be
6278 // successfully completed while the other one fails as expected.
6280 fn test_free_and_fail_holding_cell_htlcs() {
6281 let chanmon_cfgs = create_chanmon_cfgs(2);
6282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6284 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6285 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6287 // First nodes[0] generates an update_fee, setting the channel's
6288 // pending_update_fee.
6290 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6291 *feerate_lock += 200;
6293 nodes[0].node.timer_tick_occurred();
6294 check_added_monitors!(nodes[0], 1);
6296 let events = nodes[0].node.get_and_clear_pending_msg_events();
6297 assert_eq!(events.len(), 1);
6298 let (update_msg, commitment_signed) = match events[0] {
6299 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6300 (update_fee.as_ref(), commitment_signed)
6302 _ => panic!("Unexpected event"),
6305 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6307 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6308 let channel_reserve = chan_stat.channel_reserve_msat;
6309 let feerate = get_feerate!(nodes[0], chan.2);
6310 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6312 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6314 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6315 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6316 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6318 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6319 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6320 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6321 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6322 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6323 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6324 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6326 // Flush the pending fee update.
6327 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6328 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6329 check_added_monitors!(nodes[1], 1);
6330 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6331 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6332 check_added_monitors!(nodes[0], 2);
6334 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6335 // but now that the fee has been raised the second payment will now fail, causing us
6336 // to surface its failure to the user. The first payment should succeed.
6337 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6338 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6339 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);
6340 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 {}",
6341 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6342 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6344 // Check that the second payment failed to be sent out.
6345 let events = nodes[0].node.get_and_clear_pending_events();
6346 assert_eq!(events.len(), 1);
6348 &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, .. } => {
6349 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6350 assert_eq!(payment_hash_2.clone(), *payment_hash);
6351 assert_eq!(*rejected_by_dest, false);
6352 assert_eq!(*all_paths_failed, true);
6353 assert_eq!(*network_update, None);
6354 assert_eq!(*short_channel_id, None);
6355 assert_eq!(*error_code, None);
6356 assert_eq!(*error_data, None);
6358 _ => panic!("Unexpected event"),
6361 // Complete the first payment and the RAA from the fee update.
6362 let (payment_event, send_raa_event) = {
6363 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6364 assert_eq!(msgs.len(), 2);
6365 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6367 let raa = match send_raa_event {
6368 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6369 _ => panic!("Unexpected event"),
6371 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6372 check_added_monitors!(nodes[1], 1);
6373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6374 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6375 let events = nodes[1].node.get_and_clear_pending_events();
6376 assert_eq!(events.len(), 1);
6378 Event::PendingHTLCsForwardable { .. } => {},
6379 _ => panic!("Unexpected event"),
6381 nodes[1].node.process_pending_htlc_forwards();
6382 let events = nodes[1].node.get_and_clear_pending_events();
6383 assert_eq!(events.len(), 1);
6385 Event::PaymentReceived { .. } => {},
6386 _ => panic!("Unexpected event"),
6388 nodes[1].node.claim_funds(payment_preimage_1);
6389 check_added_monitors!(nodes[1], 1);
6390 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6392 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6393 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6394 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6395 expect_payment_sent!(nodes[0], payment_preimage_1);
6398 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6399 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6400 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6403 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6404 let chanmon_cfgs = create_chanmon_cfgs(3);
6405 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6406 // When this test was written, the default base fee floated based on the HTLC count.
6407 // It is now fixed, so we simply set the fee to the expected value here.
6408 let mut config = test_default_channel_config();
6409 config.channel_config.forwarding_fee_base_msat = 196;
6410 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6411 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6412 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6413 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6415 // First nodes[1] generates an update_fee, setting the channel's
6416 // pending_update_fee.
6418 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6419 *feerate_lock += 20;
6421 nodes[1].node.timer_tick_occurred();
6422 check_added_monitors!(nodes[1], 1);
6424 let events = nodes[1].node.get_and_clear_pending_msg_events();
6425 assert_eq!(events.len(), 1);
6426 let (update_msg, commitment_signed) = match events[0] {
6427 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6428 (update_fee.as_ref(), commitment_signed)
6430 _ => panic!("Unexpected event"),
6433 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6435 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6436 let channel_reserve = chan_stat.channel_reserve_msat;
6437 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6438 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6440 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6442 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6443 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6444 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6445 let payment_event = {
6446 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6447 check_added_monitors!(nodes[0], 1);
6449 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6450 assert_eq!(events.len(), 1);
6452 SendEvent::from_event(events.remove(0))
6454 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6455 check_added_monitors!(nodes[1], 0);
6456 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6457 expect_pending_htlcs_forwardable!(nodes[1]);
6459 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6460 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6462 // Flush the pending fee update.
6463 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6464 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6465 check_added_monitors!(nodes[2], 1);
6466 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6467 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6468 check_added_monitors!(nodes[1], 2);
6470 // A final RAA message is generated to finalize the fee update.
6471 let events = nodes[1].node.get_and_clear_pending_msg_events();
6472 assert_eq!(events.len(), 1);
6474 let raa_msg = match &events[0] {
6475 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6478 _ => panic!("Unexpected event"),
6481 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6482 check_added_monitors!(nodes[2], 1);
6483 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6485 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6486 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6487 assert_eq!(process_htlc_forwards_event.len(), 2);
6488 match &process_htlc_forwards_event[0] {
6489 &Event::PendingHTLCsForwardable { .. } => {},
6490 _ => panic!("Unexpected event"),
6493 // In response, we call ChannelManager's process_pending_htlc_forwards
6494 nodes[1].node.process_pending_htlc_forwards();
6495 check_added_monitors!(nodes[1], 1);
6497 // This causes the HTLC to be failed backwards.
6498 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6499 assert_eq!(fail_event.len(), 1);
6500 let (fail_msg, commitment_signed) = match &fail_event[0] {
6501 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6502 assert_eq!(updates.update_add_htlcs.len(), 0);
6503 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6504 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6505 assert_eq!(updates.update_fail_htlcs.len(), 1);
6506 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6508 _ => panic!("Unexpected event"),
6511 // Pass the failure messages back to nodes[0].
6512 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6513 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6515 // Complete the HTLC failure+removal process.
6516 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6517 check_added_monitors!(nodes[0], 1);
6518 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6519 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6520 check_added_monitors!(nodes[1], 2);
6521 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6522 assert_eq!(final_raa_event.len(), 1);
6523 let raa = match &final_raa_event[0] {
6524 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6525 _ => panic!("Unexpected event"),
6527 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6528 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6529 check_added_monitors!(nodes[0], 1);
6532 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6533 // 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.
6534 //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.
6537 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6538 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6539 let chanmon_cfgs = create_chanmon_cfgs(2);
6540 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6541 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6542 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6543 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6545 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6546 route.paths[0][0].fee_msat = 100;
6548 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6549 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6550 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6551 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6555 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6556 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6557 let chanmon_cfgs = create_chanmon_cfgs(2);
6558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6560 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6561 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6563 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6564 route.paths[0][0].fee_msat = 0;
6565 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6566 assert_eq!(err, "Cannot send 0-msat HTLC"));
6568 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6569 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6573 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6574 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6575 let chanmon_cfgs = create_chanmon_cfgs(2);
6576 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6577 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6578 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6579 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6581 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6582 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6583 check_added_monitors!(nodes[0], 1);
6584 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6585 updates.update_add_htlcs[0].amount_msat = 0;
6587 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6588 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6589 check_closed_broadcast!(nodes[1], true).unwrap();
6590 check_added_monitors!(nodes[1], 1);
6591 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6595 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6596 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6597 //It is enforced when constructing a route.
6598 let chanmon_cfgs = create_chanmon_cfgs(2);
6599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6602 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6604 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6605 .with_features(InvoiceFeatures::known());
6606 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6607 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6608 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6609 assert_eq!(err, &"Channel CLTV overflowed?"));
6613 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6614 //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.
6615 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6616 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6617 let chanmon_cfgs = create_chanmon_cfgs(2);
6618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6620 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6621 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6622 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6624 for i in 0..max_accepted_htlcs {
6625 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6626 let payment_event = {
6627 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6628 check_added_monitors!(nodes[0], 1);
6630 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6631 assert_eq!(events.len(), 1);
6632 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6633 assert_eq!(htlcs[0].htlc_id, i);
6637 SendEvent::from_event(events.remove(0))
6639 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6640 check_added_monitors!(nodes[1], 0);
6641 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6643 expect_pending_htlcs_forwardable!(nodes[1]);
6644 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6646 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6647 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6648 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6650 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6651 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6655 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6656 //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.
6657 let chanmon_cfgs = create_chanmon_cfgs(2);
6658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6660 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6661 let channel_value = 100000;
6662 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6663 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6665 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6667 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6668 // Manually create a route over our max in flight (which our router normally automatically
6670 route.paths[0][0].fee_msat = max_in_flight + 1;
6671 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6672 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)));
6674 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6675 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);
6677 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6680 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6682 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6683 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6684 let chanmon_cfgs = create_chanmon_cfgs(2);
6685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6687 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6689 let htlc_minimum_msat: u64;
6691 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6692 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6693 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6696 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6697 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6698 check_added_monitors!(nodes[0], 1);
6699 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6700 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6701 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6702 assert!(nodes[1].node.list_channels().is_empty());
6703 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6704 assert!(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()));
6705 check_added_monitors!(nodes[1], 1);
6706 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6710 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6711 //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
6712 let chanmon_cfgs = create_chanmon_cfgs(2);
6713 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6714 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6715 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6716 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6718 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6719 let channel_reserve = chan_stat.channel_reserve_msat;
6720 let feerate = get_feerate!(nodes[0], chan.2);
6721 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6722 // The 2* and +1 are for the fee spike reserve.
6723 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6725 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6726 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6727 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6728 check_added_monitors!(nodes[0], 1);
6729 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6731 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6732 // at this time channel-initiatee receivers are not required to enforce that senders
6733 // respect the fee_spike_reserve.
6734 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6735 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6737 assert!(nodes[1].node.list_channels().is_empty());
6738 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6739 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6740 check_added_monitors!(nodes[1], 1);
6741 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6745 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6746 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6747 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6748 let chanmon_cfgs = create_chanmon_cfgs(2);
6749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6751 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6754 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6755 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6756 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6757 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6758 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6759 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6761 let mut msg = msgs::UpdateAddHTLC {
6765 payment_hash: our_payment_hash,
6766 cltv_expiry: htlc_cltv,
6767 onion_routing_packet: onion_packet.clone(),
6770 for i in 0..super::channel::OUR_MAX_HTLCS {
6771 msg.htlc_id = i as u64;
6772 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6774 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6775 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6777 assert!(nodes[1].node.list_channels().is_empty());
6778 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6779 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6780 check_added_monitors!(nodes[1], 1);
6781 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6785 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6786 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6787 let chanmon_cfgs = create_chanmon_cfgs(2);
6788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6790 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6791 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6793 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6794 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6795 check_added_monitors!(nodes[0], 1);
6796 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6797 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6798 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6800 assert!(nodes[1].node.list_channels().is_empty());
6801 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6802 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6803 check_added_monitors!(nodes[1], 1);
6804 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6808 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6809 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6810 let chanmon_cfgs = create_chanmon_cfgs(2);
6811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6813 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6815 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6816 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6817 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6818 check_added_monitors!(nodes[0], 1);
6819 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6820 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6821 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6823 assert!(nodes[1].node.list_channels().is_empty());
6824 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6825 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6826 check_added_monitors!(nodes[1], 1);
6827 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6831 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6832 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6833 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6834 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6835 let chanmon_cfgs = create_chanmon_cfgs(2);
6836 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6837 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6838 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6840 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6841 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6842 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6843 check_added_monitors!(nodes[0], 1);
6844 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6845 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6847 //Disconnect and Reconnect
6848 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6849 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6850 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6851 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6852 assert_eq!(reestablish_1.len(), 1);
6853 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6854 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6855 assert_eq!(reestablish_2.len(), 1);
6856 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6857 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6858 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6859 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6862 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6863 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6864 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6865 check_added_monitors!(nodes[1], 1);
6866 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6868 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6870 assert!(nodes[1].node.list_channels().is_empty());
6871 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6872 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6873 check_added_monitors!(nodes[1], 1);
6874 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6878 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6879 //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.
6881 let chanmon_cfgs = create_chanmon_cfgs(2);
6882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6884 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6885 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6886 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6887 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6889 check_added_monitors!(nodes[0], 1);
6890 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6891 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6893 let update_msg = msgs::UpdateFulfillHTLC{
6896 payment_preimage: our_payment_preimage,
6899 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6901 assert!(nodes[0].node.list_channels().is_empty());
6902 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6903 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()));
6904 check_added_monitors!(nodes[0], 1);
6905 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6909 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6910 //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.
6912 let chanmon_cfgs = create_chanmon_cfgs(2);
6913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6915 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6916 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6918 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6919 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6920 check_added_monitors!(nodes[0], 1);
6921 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6922 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6924 let update_msg = msgs::UpdateFailHTLC{
6927 reason: msgs::OnionErrorPacket { data: Vec::new()},
6930 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6932 assert!(nodes[0].node.list_channels().is_empty());
6933 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6934 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()));
6935 check_added_monitors!(nodes[0], 1);
6936 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6940 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6941 //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.
6943 let chanmon_cfgs = create_chanmon_cfgs(2);
6944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6946 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6947 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6949 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6950 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6951 check_added_monitors!(nodes[0], 1);
6952 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6954 let update_msg = msgs::UpdateFailMalformedHTLC{
6957 sha256_of_onion: [1; 32],
6958 failure_code: 0x8000,
6961 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6963 assert!(nodes[0].node.list_channels().is_empty());
6964 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6965 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()));
6966 check_added_monitors!(nodes[0], 1);
6967 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6971 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6972 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6974 let chanmon_cfgs = create_chanmon_cfgs(2);
6975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6977 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6978 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6980 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6982 nodes[1].node.claim_funds(our_payment_preimage);
6983 check_added_monitors!(nodes[1], 1);
6984 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6986 let events = nodes[1].node.get_and_clear_pending_msg_events();
6987 assert_eq!(events.len(), 1);
6988 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6990 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, .. } } => {
6991 assert!(update_add_htlcs.is_empty());
6992 assert_eq!(update_fulfill_htlcs.len(), 1);
6993 assert!(update_fail_htlcs.is_empty());
6994 assert!(update_fail_malformed_htlcs.is_empty());
6995 assert!(update_fee.is_none());
6996 update_fulfill_htlcs[0].clone()
6998 _ => panic!("Unexpected event"),
7002 update_fulfill_msg.htlc_id = 1;
7004 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7006 assert!(nodes[0].node.list_channels().is_empty());
7007 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7008 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7009 check_added_monitors!(nodes[0], 1);
7010 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7014 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7015 //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.
7017 let chanmon_cfgs = create_chanmon_cfgs(2);
7018 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7019 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7020 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7021 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7023 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7025 nodes[1].node.claim_funds(our_payment_preimage);
7026 check_added_monitors!(nodes[1], 1);
7027 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7029 let events = nodes[1].node.get_and_clear_pending_msg_events();
7030 assert_eq!(events.len(), 1);
7031 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7033 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, .. } } => {
7034 assert!(update_add_htlcs.is_empty());
7035 assert_eq!(update_fulfill_htlcs.len(), 1);
7036 assert!(update_fail_htlcs.is_empty());
7037 assert!(update_fail_malformed_htlcs.is_empty());
7038 assert!(update_fee.is_none());
7039 update_fulfill_htlcs[0].clone()
7041 _ => panic!("Unexpected event"),
7045 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7047 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7049 assert!(nodes[0].node.list_channels().is_empty());
7050 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7051 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7052 check_added_monitors!(nodes[0], 1);
7053 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7057 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7058 //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.
7060 let chanmon_cfgs = create_chanmon_cfgs(2);
7061 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7062 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7063 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7064 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7066 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7067 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7068 check_added_monitors!(nodes[0], 1);
7070 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7071 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7073 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7074 check_added_monitors!(nodes[1], 0);
7075 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7077 let events = nodes[1].node.get_and_clear_pending_msg_events();
7079 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7081 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, .. } } => {
7082 assert!(update_add_htlcs.is_empty());
7083 assert!(update_fulfill_htlcs.is_empty());
7084 assert!(update_fail_htlcs.is_empty());
7085 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7086 assert!(update_fee.is_none());
7087 update_fail_malformed_htlcs[0].clone()
7089 _ => panic!("Unexpected event"),
7092 update_msg.failure_code &= !0x8000;
7093 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7095 assert!(nodes[0].node.list_channels().is_empty());
7096 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7097 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7098 check_added_monitors!(nodes[0], 1);
7099 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7103 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7104 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7105 // * 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.
7107 let chanmon_cfgs = create_chanmon_cfgs(3);
7108 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7109 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7110 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7111 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7112 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7114 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7117 let mut payment_event = {
7118 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7119 check_added_monitors!(nodes[0], 1);
7120 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7121 assert_eq!(events.len(), 1);
7122 SendEvent::from_event(events.remove(0))
7124 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7125 check_added_monitors!(nodes[1], 0);
7126 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7127 expect_pending_htlcs_forwardable!(nodes[1]);
7128 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7129 assert_eq!(events_2.len(), 1);
7130 check_added_monitors!(nodes[1], 1);
7131 payment_event = SendEvent::from_event(events_2.remove(0));
7132 assert_eq!(payment_event.msgs.len(), 1);
7135 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7136 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7137 check_added_monitors!(nodes[2], 0);
7138 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7140 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7141 assert_eq!(events_3.len(), 1);
7142 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7144 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 } } => {
7145 assert!(update_add_htlcs.is_empty());
7146 assert!(update_fulfill_htlcs.is_empty());
7147 assert!(update_fail_htlcs.is_empty());
7148 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7149 assert!(update_fee.is_none());
7150 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7152 _ => panic!("Unexpected event"),
7156 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7158 check_added_monitors!(nodes[1], 0);
7159 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7160 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
7161 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7162 assert_eq!(events_4.len(), 1);
7164 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7166 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, .. } } => {
7167 assert!(update_add_htlcs.is_empty());
7168 assert!(update_fulfill_htlcs.is_empty());
7169 assert_eq!(update_fail_htlcs.len(), 1);
7170 assert!(update_fail_malformed_htlcs.is_empty());
7171 assert!(update_fee.is_none());
7173 _ => panic!("Unexpected event"),
7176 check_added_monitors!(nodes[1], 1);
7179 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7180 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7181 // 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
7182 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7184 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7185 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7187 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7188 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7189 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7191 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7193 // We route 2 dust-HTLCs between A and B
7194 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7195 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7196 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7198 // Cache one local commitment tx as previous
7199 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7201 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7202 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7203 check_added_monitors!(nodes[1], 0);
7204 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7205 check_added_monitors!(nodes[1], 1);
7207 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7208 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7209 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7210 check_added_monitors!(nodes[0], 1);
7212 // Cache one local commitment tx as lastest
7213 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7215 let events = nodes[0].node.get_and_clear_pending_msg_events();
7217 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7218 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7220 _ => panic!("Unexpected event"),
7223 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7224 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7226 _ => panic!("Unexpected event"),
7229 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7230 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7231 if announce_latest {
7232 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7234 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7237 check_closed_broadcast!(nodes[0], true);
7238 check_added_monitors!(nodes[0], 1);
7239 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7241 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7242 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7243 let events = nodes[0].node.get_and_clear_pending_events();
7244 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7245 assert_eq!(events.len(), 2);
7246 let mut first_failed = false;
7247 for event in events {
7249 Event::PaymentPathFailed { payment_hash, .. } => {
7250 if payment_hash == payment_hash_1 {
7251 assert!(!first_failed);
7252 first_failed = true;
7254 assert_eq!(payment_hash, payment_hash_2);
7257 _ => panic!("Unexpected event"),
7263 fn test_failure_delay_dust_htlc_local_commitment() {
7264 do_test_failure_delay_dust_htlc_local_commitment(true);
7265 do_test_failure_delay_dust_htlc_local_commitment(false);
7268 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7269 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7270 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7271 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7272 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7273 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7274 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7276 let chanmon_cfgs = create_chanmon_cfgs(3);
7277 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7278 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7279 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7280 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7282 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7284 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7285 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7287 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7288 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7290 // We revoked bs_commitment_tx
7292 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7293 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7296 let mut timeout_tx = Vec::new();
7298 // We fail dust-HTLC 1 by broadcast of local commitment tx
7299 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7300 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7301 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7302 expect_payment_failed!(nodes[0], dust_hash, true);
7304 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7305 check_closed_broadcast!(nodes[0], true);
7306 check_added_monitors!(nodes[0], 1);
7307 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7308 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7309 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7310 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7311 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7312 mine_transaction(&nodes[0], &timeout_tx[0]);
7313 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7314 expect_payment_failed!(nodes[0], non_dust_hash, true);
7316 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7317 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7318 check_closed_broadcast!(nodes[0], true);
7319 check_added_monitors!(nodes[0], 1);
7320 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7321 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7323 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7324 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7325 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7326 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7327 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7328 // dust HTLC should have been failed.
7329 expect_payment_failed!(nodes[0], dust_hash, true);
7332 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7334 assert_eq!(timeout_tx[0].lock_time, 0);
7336 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7337 mine_transaction(&nodes[0], &timeout_tx[0]);
7338 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7339 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7340 expect_payment_failed!(nodes[0], non_dust_hash, true);
7345 fn test_sweep_outbound_htlc_failure_update() {
7346 do_test_sweep_outbound_htlc_failure_update(false, true);
7347 do_test_sweep_outbound_htlc_failure_update(false, false);
7348 do_test_sweep_outbound_htlc_failure_update(true, false);
7352 fn test_user_configurable_csv_delay() {
7353 // We test our channel constructors yield errors when we pass them absurd csv delay
7355 let mut low_our_to_self_config = UserConfig::default();
7356 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7357 let mut high_their_to_self_config = UserConfig::default();
7358 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7359 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7360 let chanmon_cfgs = create_chanmon_cfgs(2);
7361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7363 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7365 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7366 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7367 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7368 &low_our_to_self_config, 0, 42)
7371 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())); },
7372 _ => panic!("Unexpected event"),
7374 } else { assert!(false) }
7376 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7377 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7378 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7379 open_channel.to_self_delay = 200;
7380 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7381 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7382 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7385 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())); },
7386 _ => panic!("Unexpected event"),
7388 } else { assert!(false); }
7390 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7391 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7392 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()));
7393 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7394 accept_channel.to_self_delay = 200;
7395 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7397 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7399 &ErrorAction::SendErrorMessage { ref msg } => {
7400 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()));
7401 reason_msg = msg.data.clone();
7405 } else { panic!(); }
7406 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7408 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7409 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7410 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7411 open_channel.to_self_delay = 200;
7412 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7413 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7414 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7417 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())); },
7418 _ => panic!("Unexpected event"),
7420 } else { assert!(false); }
7423 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7424 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7425 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7426 // panic message informs the user they should force-close without broadcasting, which is tested
7427 // if `reconnect_panicing` is not set.
7433 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7434 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7435 // during signing due to revoked tx
7436 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7437 let keys_manager = &chanmon_cfgs[0].keys_manager;
7440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7442 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7444 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7446 // Cache node A state before any channel update
7447 let previous_node_state = nodes[0].node.encode();
7448 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7449 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7451 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7452 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7454 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7455 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7457 // Restore node A from previous state
7458 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7459 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7460 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7461 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7462 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7463 persister = test_utils::TestPersister::new();
7464 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7466 let mut channel_monitors = HashMap::new();
7467 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7468 <(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 {
7469 keys_manager: keys_manager,
7470 fee_estimator: &fee_estimator,
7471 chain_monitor: &monitor,
7473 tx_broadcaster: &tx_broadcaster,
7474 default_config: UserConfig::default(),
7478 nodes[0].node = &node_state_0;
7479 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7480 nodes[0].chain_monitor = &monitor;
7481 nodes[0].chain_source = &chain_source;
7483 check_added_monitors!(nodes[0], 1);
7485 if reconnect_panicing {
7486 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7487 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7489 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7491 // Check we close channel detecting A is fallen-behind
7492 // Check that we sent the warning message when we detected that A has fallen behind,
7493 // and give the possibility for A to recover from the warning.
7494 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7495 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7496 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7499 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7500 // The node B should not broadcast the transaction to force close the channel!
7501 assert!(node_txn.is_empty());
7504 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7505 // Check A panics upon seeing proof it has fallen behind.
7506 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7507 return; // By this point we should have panic'ed!
7510 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7511 check_added_monitors!(nodes[0], 1);
7512 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7514 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7515 assert_eq!(node_txn.len(), 0);
7518 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7519 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7520 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7522 &ErrorAction::SendErrorMessage { ref msg } => {
7523 assert_eq!(msg.data, "Channel force-closed");
7525 _ => panic!("Unexpected event!"),
7528 panic!("Unexpected event {:?}", msg)
7532 // after the warning message sent by B, we should not able to
7533 // use the channel, or reconnect with success to the channel.
7534 assert!(nodes[0].node.list_usable_channels().is_empty());
7535 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7536 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7537 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7539 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7540 let mut err_msgs_0 = Vec::with_capacity(1);
7541 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7542 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7544 &ErrorAction::SendErrorMessage { ref msg } => {
7545 assert_eq!(msg.data, "Failed to find corresponding channel");
7546 err_msgs_0.push(msg.clone());
7548 _ => panic!("Unexpected event!"),
7551 panic!("Unexpected event!");
7554 assert_eq!(err_msgs_0.len(), 1);
7555 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7556 assert!(nodes[1].node.list_usable_channels().is_empty());
7557 check_added_monitors!(nodes[1], 1);
7558 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7559 check_closed_broadcast!(nodes[1], false);
7564 fn test_data_loss_protect_showing_stale_state_panics() {
7565 do_test_data_loss_protect(true);
7569 fn test_force_close_without_broadcast() {
7570 do_test_data_loss_protect(false);
7574 fn test_check_htlc_underpaying() {
7575 // Send payment through A -> B but A is maliciously
7576 // sending a probe payment (i.e less than expected value0
7577 // to B, B should refuse payment.
7579 let chanmon_cfgs = create_chanmon_cfgs(2);
7580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7584 // Create some initial channels
7585 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7587 let scorer = test_utils::TestScorer::with_penalty(0);
7588 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7589 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7590 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();
7591 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7592 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7593 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7594 check_added_monitors!(nodes[0], 1);
7596 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7597 assert_eq!(events.len(), 1);
7598 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7599 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7600 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7602 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7603 // and then will wait a second random delay before failing the HTLC back:
7604 expect_pending_htlcs_forwardable!(nodes[1]);
7605 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7607 // Node 3 is expecting payment of 100_000 but received 10_000,
7608 // it should fail htlc like we didn't know the preimage.
7609 nodes[1].node.process_pending_htlc_forwards();
7611 let events = nodes[1].node.get_and_clear_pending_msg_events();
7612 assert_eq!(events.len(), 1);
7613 let (update_fail_htlc, commitment_signed) = match events[0] {
7614 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 } } => {
7615 assert!(update_add_htlcs.is_empty());
7616 assert!(update_fulfill_htlcs.is_empty());
7617 assert_eq!(update_fail_htlcs.len(), 1);
7618 assert!(update_fail_malformed_htlcs.is_empty());
7619 assert!(update_fee.is_none());
7620 (update_fail_htlcs[0].clone(), commitment_signed)
7622 _ => panic!("Unexpected event"),
7624 check_added_monitors!(nodes[1], 1);
7626 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7627 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7629 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7630 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7631 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7632 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7636 fn test_announce_disable_channels() {
7637 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7638 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7640 let chanmon_cfgs = create_chanmon_cfgs(2);
7641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7643 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7645 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7646 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7647 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7650 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7651 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7653 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7654 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7655 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7656 assert_eq!(msg_events.len(), 3);
7657 let mut chans_disabled = HashMap::new();
7658 for e in msg_events {
7660 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7661 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7662 // Check that each channel gets updated exactly once
7663 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7664 panic!("Generated ChannelUpdate for wrong chan!");
7667 _ => panic!("Unexpected event"),
7671 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7672 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7673 assert_eq!(reestablish_1.len(), 3);
7674 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7675 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7676 assert_eq!(reestablish_2.len(), 3);
7678 // Reestablish chan_1
7679 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7680 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7681 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7682 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7683 // Reestablish chan_2
7684 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7685 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7686 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7687 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7688 // Reestablish chan_3
7689 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7690 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7691 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7692 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7694 nodes[0].node.timer_tick_occurred();
7695 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7696 nodes[0].node.timer_tick_occurred();
7697 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7698 assert_eq!(msg_events.len(), 3);
7699 for e in msg_events {
7701 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7702 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7703 match chans_disabled.remove(&msg.contents.short_channel_id) {
7704 // Each update should have a higher timestamp than the previous one, replacing
7706 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7707 None => panic!("Generated ChannelUpdate for wrong chan!"),
7710 _ => panic!("Unexpected event"),
7713 // Check that each channel gets updated exactly once
7714 assert!(chans_disabled.is_empty());
7718 fn test_bump_penalty_txn_on_revoked_commitment() {
7719 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7720 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7722 let chanmon_cfgs = create_chanmon_cfgs(2);
7723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7727 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7729 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7730 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7731 .with_features(InvoiceFeatures::known());
7732 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7733 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7735 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7736 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7737 assert_eq!(revoked_txn[0].output.len(), 4);
7738 assert_eq!(revoked_txn[0].input.len(), 1);
7739 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7740 let revoked_txid = revoked_txn[0].txid();
7742 let mut penalty_sum = 0;
7743 for outp in revoked_txn[0].output.iter() {
7744 if outp.script_pubkey.is_v0_p2wsh() {
7745 penalty_sum += outp.value;
7749 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7750 let header_114 = connect_blocks(&nodes[1], 14);
7752 // Actually revoke tx by claiming a HTLC
7753 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7754 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7755 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7756 check_added_monitors!(nodes[1], 1);
7758 // One or more justice tx should have been broadcast, check it
7762 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7763 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7764 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7765 assert_eq!(node_txn[0].output.len(), 1);
7766 check_spends!(node_txn[0], revoked_txn[0]);
7767 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7768 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7769 penalty_1 = node_txn[0].txid();
7773 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7774 connect_blocks(&nodes[1], 15);
7775 let mut penalty_2 = penalty_1;
7776 let mut feerate_2 = 0;
7778 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7779 assert_eq!(node_txn.len(), 1);
7780 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7781 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7782 assert_eq!(node_txn[0].output.len(), 1);
7783 check_spends!(node_txn[0], revoked_txn[0]);
7784 penalty_2 = node_txn[0].txid();
7785 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7786 assert_ne!(penalty_2, penalty_1);
7787 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7788 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7789 // Verify 25% bump heuristic
7790 assert!(feerate_2 * 100 >= feerate_1 * 125);
7794 assert_ne!(feerate_2, 0);
7796 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7797 connect_blocks(&nodes[1], 1);
7799 let mut feerate_3 = 0;
7801 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7802 assert_eq!(node_txn.len(), 1);
7803 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7804 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7805 assert_eq!(node_txn[0].output.len(), 1);
7806 check_spends!(node_txn[0], revoked_txn[0]);
7807 penalty_3 = node_txn[0].txid();
7808 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7809 assert_ne!(penalty_3, penalty_2);
7810 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7811 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7812 // Verify 25% bump heuristic
7813 assert!(feerate_3 * 100 >= feerate_2 * 125);
7817 assert_ne!(feerate_3, 0);
7819 nodes[1].node.get_and_clear_pending_events();
7820 nodes[1].node.get_and_clear_pending_msg_events();
7824 fn test_bump_penalty_txn_on_revoked_htlcs() {
7825 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7826 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7828 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7829 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7834 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7835 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7836 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7837 let scorer = test_utils::TestScorer::with_penalty(0);
7838 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7839 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7840 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7841 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7842 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7843 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7844 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7845 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7847 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7848 assert_eq!(revoked_local_txn[0].input.len(), 1);
7849 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7851 // Revoke local commitment tx
7852 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7854 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7855 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7856 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7857 check_closed_broadcast!(nodes[1], true);
7858 check_added_monitors!(nodes[1], 1);
7859 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7860 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7862 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7863 assert_eq!(revoked_htlc_txn.len(), 3);
7864 check_spends!(revoked_htlc_txn[1], chan.3);
7866 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7867 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7868 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7870 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7871 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7872 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7873 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7875 // Broadcast set of revoked txn on A
7876 let hash_128 = connect_blocks(&nodes[0], 40);
7877 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7878 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7879 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7880 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7881 let events = nodes[0].node.get_and_clear_pending_events();
7882 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7883 match events.last().unwrap() {
7884 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7885 _ => panic!("Unexpected event"),
7891 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7892 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7893 // Verify claim tx are spending revoked HTLC txn
7895 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7896 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7897 // which are included in the same block (they are broadcasted because we scan the
7898 // transactions linearly and generate claims as we go, they likely should be removed in the
7900 assert_eq!(node_txn[0].input.len(), 1);
7901 check_spends!(node_txn[0], revoked_local_txn[0]);
7902 assert_eq!(node_txn[1].input.len(), 1);
7903 check_spends!(node_txn[1], revoked_local_txn[0]);
7904 assert_eq!(node_txn[2].input.len(), 1);
7905 check_spends!(node_txn[2], revoked_local_txn[0]);
7907 // Each of the three justice transactions claim a separate (single) output of the three
7908 // available, which we check here:
7909 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7910 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7911 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7913 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7914 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7916 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7917 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7918 // a remote commitment tx has already been confirmed).
7919 check_spends!(node_txn[3], chan.3);
7921 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7922 // output, checked above).
7923 assert_eq!(node_txn[4].input.len(), 2);
7924 assert_eq!(node_txn[4].output.len(), 1);
7925 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7927 first = node_txn[4].txid();
7928 // Store both feerates for later comparison
7929 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7930 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7931 penalty_txn = vec![node_txn[2].clone()];
7935 // Connect one more block to see if bumped penalty are issued for HTLC txn
7936 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7937 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7938 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7939 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7941 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7942 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7944 check_spends!(node_txn[0], revoked_local_txn[0]);
7945 check_spends!(node_txn[1], revoked_local_txn[0]);
7946 // Note that these are both bogus - they spend outputs already claimed in block 129:
7947 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7948 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7950 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7951 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7957 // Few more blocks to confirm penalty txn
7958 connect_blocks(&nodes[0], 4);
7959 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7960 let header_144 = connect_blocks(&nodes[0], 9);
7962 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7963 assert_eq!(node_txn.len(), 1);
7965 assert_eq!(node_txn[0].input.len(), 2);
7966 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7967 // Verify bumped tx is different and 25% bump heuristic
7968 assert_ne!(first, node_txn[0].txid());
7969 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7970 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7971 assert!(feerate_2 * 100 > feerate_1 * 125);
7972 let txn = vec![node_txn[0].clone()];
7976 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7977 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7978 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7979 connect_blocks(&nodes[0], 20);
7981 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7982 // We verify than no new transaction has been broadcast because previously
7983 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7984 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7985 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7986 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7987 // up bumped justice generation.
7988 assert_eq!(node_txn.len(), 0);
7991 check_closed_broadcast!(nodes[0], true);
7992 check_added_monitors!(nodes[0], 1);
7996 fn test_bump_penalty_txn_on_remote_commitment() {
7997 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7998 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8001 // Provide preimage for one
8002 // Check aggregation
8004 let chanmon_cfgs = create_chanmon_cfgs(2);
8005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8007 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8009 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8010 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8011 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8013 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8014 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8015 assert_eq!(remote_txn[0].output.len(), 4);
8016 assert_eq!(remote_txn[0].input.len(), 1);
8017 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8019 // Claim a HTLC without revocation (provide B monitor with preimage)
8020 nodes[1].node.claim_funds(payment_preimage);
8021 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8022 mine_transaction(&nodes[1], &remote_txn[0]);
8023 check_added_monitors!(nodes[1], 2);
8024 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8026 // One or more claim tx should have been broadcast, check it
8030 let feerate_timeout;
8031 let feerate_preimage;
8033 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8034 // 9 transactions including:
8035 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8036 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8037 // 2 * HTLC-Success (one RBF bump we'll check later)
8039 assert_eq!(node_txn.len(), 8);
8040 assert_eq!(node_txn[0].input.len(), 1);
8041 assert_eq!(node_txn[6].input.len(), 1);
8042 check_spends!(node_txn[0], remote_txn[0]);
8043 check_spends!(node_txn[6], remote_txn[0]);
8045 check_spends!(node_txn[1], chan.3);
8046 check_spends!(node_txn[2], node_txn[1]);
8048 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8049 preimage_bump = node_txn[3].clone();
8050 check_spends!(node_txn[3], remote_txn[0]);
8052 assert_eq!(node_txn[1], node_txn[4]);
8053 assert_eq!(node_txn[2], node_txn[5]);
8055 preimage_bump = node_txn[7].clone();
8056 check_spends!(node_txn[7], remote_txn[0]);
8057 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8059 assert_eq!(node_txn[1], node_txn[3]);
8060 assert_eq!(node_txn[2], node_txn[4]);
8063 timeout = node_txn[6].txid();
8064 let index = node_txn[6].input[0].previous_output.vout;
8065 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8066 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8068 preimage = node_txn[0].txid();
8069 let index = node_txn[0].input[0].previous_output.vout;
8070 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8071 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8075 assert_ne!(feerate_timeout, 0);
8076 assert_ne!(feerate_preimage, 0);
8078 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8079 connect_blocks(&nodes[1], 15);
8081 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8082 assert_eq!(node_txn.len(), 1);
8083 assert_eq!(node_txn[0].input.len(), 1);
8084 assert_eq!(preimage_bump.input.len(), 1);
8085 check_spends!(node_txn[0], remote_txn[0]);
8086 check_spends!(preimage_bump, remote_txn[0]);
8088 let index = preimage_bump.input[0].previous_output.vout;
8089 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8090 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8091 assert!(new_feerate * 100 > feerate_timeout * 125);
8092 assert_ne!(timeout, preimage_bump.txid());
8094 let index = node_txn[0].input[0].previous_output.vout;
8095 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8096 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8097 assert!(new_feerate * 100 > feerate_preimage * 125);
8098 assert_ne!(preimage, node_txn[0].txid());
8103 nodes[1].node.get_and_clear_pending_events();
8104 nodes[1].node.get_and_clear_pending_msg_events();
8108 fn test_counterparty_raa_skip_no_crash() {
8109 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8110 // commitment transaction, we would have happily carried on and provided them the next
8111 // commitment transaction based on one RAA forward. This would probably eventually have led to
8112 // channel closure, but it would not have resulted in funds loss. Still, our
8113 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8114 // check simply that the channel is closed in response to such an RAA, but don't check whether
8115 // we decide to punish our counterparty for revoking their funds (as we don't currently
8117 let chanmon_cfgs = create_chanmon_cfgs(2);
8118 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8120 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8123 let per_commitment_secret;
8124 let next_per_commitment_point;
8126 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8127 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8129 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8131 // Make signer believe we got a counterparty signature, so that it allows the revocation
8132 keys.get_enforcement_state().last_holder_commitment -= 1;
8133 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8135 // Must revoke without gaps
8136 keys.get_enforcement_state().last_holder_commitment -= 1;
8137 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8139 keys.get_enforcement_state().last_holder_commitment -= 1;
8140 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8141 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8144 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8145 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8146 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8147 check_added_monitors!(nodes[1], 1);
8148 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8152 fn test_bump_txn_sanitize_tracking_maps() {
8153 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8154 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8156 let chanmon_cfgs = create_chanmon_cfgs(2);
8157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8159 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8161 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8162 // Lock HTLC in both directions
8163 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
8164 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
8166 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8167 assert_eq!(revoked_local_txn[0].input.len(), 1);
8168 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8170 // Revoke local commitment tx
8171 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
8173 // Broadcast set of revoked txn on A
8174 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8175 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
8176 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8178 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8179 check_closed_broadcast!(nodes[0], true);
8180 check_added_monitors!(nodes[0], 1);
8181 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8183 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8184 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8185 check_spends!(node_txn[0], revoked_local_txn[0]);
8186 check_spends!(node_txn[1], revoked_local_txn[0]);
8187 check_spends!(node_txn[2], revoked_local_txn[0]);
8188 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8192 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8193 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8194 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8196 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8197 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8198 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8203 fn test_pending_claimed_htlc_no_balance_underflow() {
8204 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8205 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8206 let chanmon_cfgs = create_chanmon_cfgs(2);
8207 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8208 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8209 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8210 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8212 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8213 nodes[1].node.claim_funds(payment_preimage);
8214 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8215 check_added_monitors!(nodes[1], 1);
8216 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8218 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8219 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8220 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8221 check_added_monitors!(nodes[0], 1);
8222 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8224 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8225 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8226 // can get our balance.
8228 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8229 // the public key of the only hop. This works around ChannelDetails not showing the
8230 // almost-claimed HTLC as available balance.
8231 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8232 route.payment_params = None; // This is all wrong, but unnecessary
8233 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8234 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8235 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8237 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8241 fn test_channel_conf_timeout() {
8242 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8243 // confirm within 2016 blocks, as recommended by BOLT 2.
8244 let chanmon_cfgs = create_chanmon_cfgs(2);
8245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8249 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8251 // The outbound node should wait forever for confirmation:
8252 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8253 // copied here instead of directly referencing the constant.
8254 connect_blocks(&nodes[0], 2016);
8255 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8257 // The inbound node should fail the channel after exactly 2016 blocks
8258 connect_blocks(&nodes[1], 2015);
8259 check_added_monitors!(nodes[1], 0);
8260 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8262 connect_blocks(&nodes[1], 1);
8263 check_added_monitors!(nodes[1], 1);
8264 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8265 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8266 assert_eq!(close_ev.len(), 1);
8268 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8269 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8270 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8272 _ => panic!("Unexpected event"),
8277 fn test_override_channel_config() {
8278 let chanmon_cfgs = create_chanmon_cfgs(2);
8279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8281 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8283 // Node0 initiates a channel to node1 using the override config.
8284 let mut override_config = UserConfig::default();
8285 override_config.channel_handshake_config.our_to_self_delay = 200;
8287 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8289 // Assert the channel created by node0 is using the override config.
8290 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8291 assert_eq!(res.channel_flags, 0);
8292 assert_eq!(res.to_self_delay, 200);
8296 fn test_override_0msat_htlc_minimum() {
8297 let mut zero_config = UserConfig::default();
8298 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8299 let chanmon_cfgs = create_chanmon_cfgs(2);
8300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8302 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8304 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8305 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8306 assert_eq!(res.htlc_minimum_msat, 1);
8308 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8309 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8310 assert_eq!(res.htlc_minimum_msat, 1);
8314 fn test_channel_update_has_correct_htlc_maximum_msat() {
8315 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8316 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8317 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8318 // 90% of the `channel_value`.
8319 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8321 let mut config_30_percent = UserConfig::default();
8322 config_30_percent.channel_handshake_config.announced_channel = true;
8323 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8324 let mut config_50_percent = UserConfig::default();
8325 config_50_percent.channel_handshake_config.announced_channel = true;
8326 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8327 let mut config_95_percent = UserConfig::default();
8328 config_95_percent.channel_handshake_config.announced_channel = true;
8329 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8330 let mut config_100_percent = UserConfig::default();
8331 config_100_percent.channel_handshake_config.announced_channel = true;
8332 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8334 let chanmon_cfgs = create_chanmon_cfgs(4);
8335 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8336 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[Some(config_30_percent), Some(config_50_percent), Some(config_95_percent), Some(config_100_percent)]);
8337 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8339 let channel_value_satoshis = 100000;
8340 let channel_value_msat = channel_value_satoshis * 1000;
8341 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8342 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8343 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8345 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8346 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001, InitFeatures::known(), InitFeatures::known());
8348 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8349 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8350 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
8351 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8352 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8353 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
8355 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8356 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8358 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8359 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8360 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8362 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
8366 fn test_manually_accept_inbound_channel_request() {
8367 let mut manually_accept_conf = UserConfig::default();
8368 manually_accept_conf.manually_accept_inbound_channels = true;
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, Some(manually_accept_conf.clone())]);
8372 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8374 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8375 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8377 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8379 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8380 // accepting the inbound channel request.
8381 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8383 let events = nodes[1].node.get_and_clear_pending_events();
8385 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8386 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8388 _ => panic!("Unexpected event"),
8391 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8392 assert_eq!(accept_msg_ev.len(), 1);
8394 match accept_msg_ev[0] {
8395 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8396 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8398 _ => panic!("Unexpected event"),
8401 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8403 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8404 assert_eq!(close_msg_ev.len(), 1);
8406 let events = nodes[1].node.get_and_clear_pending_events();
8408 Event::ChannelClosed { user_channel_id, .. } => {
8409 assert_eq!(user_channel_id, 23);
8411 _ => panic!("Unexpected event"),
8416 fn test_manually_reject_inbound_channel_request() {
8417 let mut manually_accept_conf = UserConfig::default();
8418 manually_accept_conf.manually_accept_inbound_channels = true;
8419 let chanmon_cfgs = create_chanmon_cfgs(2);
8420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8422 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8424 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8425 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8427 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8429 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8430 // rejecting the inbound channel request.
8431 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8433 let events = nodes[1].node.get_and_clear_pending_events();
8435 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8436 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8438 _ => panic!("Unexpected event"),
8441 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8442 assert_eq!(close_msg_ev.len(), 1);
8444 match close_msg_ev[0] {
8445 MessageSendEvent::HandleError { ref node_id, .. } => {
8446 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8448 _ => panic!("Unexpected event"),
8450 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8454 fn test_reject_funding_before_inbound_channel_accepted() {
8455 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8456 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8457 // the node operator before the counterparty sends a `FundingCreated` message. If a
8458 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8459 // and the channel should be closed.
8460 let mut manually_accept_conf = UserConfig::default();
8461 manually_accept_conf.manually_accept_inbound_channels = true;
8462 let chanmon_cfgs = create_chanmon_cfgs(2);
8463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8467 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8468 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8469 let temp_channel_id = res.temporary_channel_id;
8471 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8473 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8474 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8476 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8477 nodes[1].node.get_and_clear_pending_events();
8479 // Get the `AcceptChannel` message of `nodes[1]` without calling
8480 // `ChannelManager::accept_inbound_channel`, which generates a
8481 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8482 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8483 // succeed when `nodes[0]` is passed to it.
8484 let accept_chan_msg = {
8486 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8487 channel.get_accept_channel_message()
8489 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8491 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8493 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8494 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8496 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8497 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8499 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8500 assert_eq!(close_msg_ev.len(), 1);
8502 let expected_err = "FundingCreated message received before the channel was accepted";
8503 match close_msg_ev[0] {
8504 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8505 assert_eq!(msg.channel_id, temp_channel_id);
8506 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8507 assert_eq!(msg.data, expected_err);
8509 _ => panic!("Unexpected event"),
8512 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8516 fn test_can_not_accept_inbound_channel_twice() {
8517 let mut manually_accept_conf = UserConfig::default();
8518 manually_accept_conf.manually_accept_inbound_channels = true;
8519 let chanmon_cfgs = create_chanmon_cfgs(2);
8520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8524 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8525 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8527 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8529 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8530 // accepting the inbound channel request.
8531 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8533 let events = nodes[1].node.get_and_clear_pending_events();
8535 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8536 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8537 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8539 Err(APIError::APIMisuseError { err }) => {
8540 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8542 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8543 Err(_) => panic!("Unexpected Error"),
8546 _ => panic!("Unexpected event"),
8549 // Ensure that the channel wasn't closed after attempting to accept it twice.
8550 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8551 assert_eq!(accept_msg_ev.len(), 1);
8553 match accept_msg_ev[0] {
8554 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8555 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8557 _ => panic!("Unexpected event"),
8562 fn test_can_not_accept_unknown_inbound_channel() {
8563 let chanmon_cfg = create_chanmon_cfgs(2);
8564 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8565 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8566 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8568 let unknown_channel_id = [0; 32];
8569 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8571 Err(APIError::ChannelUnavailable { err }) => {
8572 assert_eq!(err, "Can't accept a channel that doesn't exist");
8574 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8575 Err(_) => panic!("Unexpected Error"),
8580 fn test_simple_mpp() {
8581 // Simple test of sending a multi-path payment.
8582 let chanmon_cfgs = create_chanmon_cfgs(4);
8583 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8584 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8585 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8587 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8588 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8589 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8590 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8592 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8593 let path = route.paths[0].clone();
8594 route.paths.push(path);
8595 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8596 route.paths[0][0].short_channel_id = chan_1_id;
8597 route.paths[0][1].short_channel_id = chan_3_id;
8598 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8599 route.paths[1][0].short_channel_id = chan_2_id;
8600 route.paths[1][1].short_channel_id = chan_4_id;
8601 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8602 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8606 fn test_preimage_storage() {
8607 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8608 let chanmon_cfgs = create_chanmon_cfgs(2);
8609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8613 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8616 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8617 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8618 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8619 check_added_monitors!(nodes[0], 1);
8620 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8621 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8623 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8625 // Note that after leaving the above scope we have no knowledge of any arguments or return
8626 // values from previous calls.
8627 expect_pending_htlcs_forwardable!(nodes[1]);
8628 let events = nodes[1].node.get_and_clear_pending_events();
8629 assert_eq!(events.len(), 1);
8631 Event::PaymentReceived { ref purpose, .. } => {
8633 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8634 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8636 _ => panic!("expected PaymentPurpose::InvoicePayment")
8639 _ => panic!("Unexpected event"),
8644 #[allow(deprecated)]
8645 fn test_secret_timeout() {
8646 // Simple test of payment secret storage time outs. After
8647 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8648 let chanmon_cfgs = create_chanmon_cfgs(2);
8649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8651 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8653 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8655 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8657 // We should fail to register the same payment hash twice, at least until we've connected a
8658 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8659 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8660 assert_eq!(err, "Duplicate payment hash");
8661 } else { panic!(); }
8663 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8665 header: BlockHeader {
8667 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8668 merkle_root: Default::default(),
8669 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8673 connect_block(&nodes[1], &block);
8674 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8675 assert_eq!(err, "Duplicate payment hash");
8676 } else { panic!(); }
8678 // If we then connect the second block, we should be able to register the same payment hash
8679 // again (this time getting a new payment secret).
8680 block.header.prev_blockhash = block.header.block_hash();
8681 block.header.time += 1;
8682 connect_block(&nodes[1], &block);
8683 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8684 assert_ne!(payment_secret_1, our_payment_secret);
8687 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8688 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8689 check_added_monitors!(nodes[0], 1);
8690 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8691 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8692 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8693 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8695 // Note that after leaving the above scope we have no knowledge of any arguments or return
8696 // values from previous calls.
8697 expect_pending_htlcs_forwardable!(nodes[1]);
8698 let events = nodes[1].node.get_and_clear_pending_events();
8699 assert_eq!(events.len(), 1);
8701 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8702 assert!(payment_preimage.is_none());
8703 assert_eq!(payment_secret, our_payment_secret);
8704 // We don't actually have the payment preimage with which to claim this payment!
8706 _ => panic!("Unexpected event"),
8711 fn test_bad_secret_hash() {
8712 // Simple test of unregistered payment hash/invalid payment secret handling
8713 let chanmon_cfgs = create_chanmon_cfgs(2);
8714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8716 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8718 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8720 let random_payment_hash = PaymentHash([42; 32]);
8721 let random_payment_secret = PaymentSecret([43; 32]);
8722 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8723 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8725 // All the below cases should end up being handled exactly identically, so we macro the
8726 // resulting events.
8727 macro_rules! handle_unknown_invalid_payment_data {
8728 ($payment_hash: expr) => {
8729 check_added_monitors!(nodes[0], 1);
8730 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8731 let payment_event = SendEvent::from_event(events.pop().unwrap());
8732 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8733 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8735 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8736 // again to process the pending backwards-failure of the HTLC
8737 expect_pending_htlcs_forwardable!(nodes[1]);
8738 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8739 check_added_monitors!(nodes[1], 1);
8741 // We should fail the payment back
8742 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8743 match events.pop().unwrap() {
8744 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8745 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8746 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8748 _ => panic!("Unexpected event"),
8753 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8754 // Error data is the HTLC value (100,000) and current block height
8755 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8757 // Send a payment with the right payment hash but the wrong payment secret
8758 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8759 handle_unknown_invalid_payment_data!(our_payment_hash);
8760 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8762 // Send a payment with a random payment hash, but the right payment secret
8763 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8764 handle_unknown_invalid_payment_data!(random_payment_hash);
8765 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8767 // Send a payment with a random payment hash and random payment secret
8768 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8769 handle_unknown_invalid_payment_data!(random_payment_hash);
8770 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8774 fn test_update_err_monitor_lockdown() {
8775 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8776 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8777 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8779 // This scenario may happen in a watchtower setup, where watchtower process a block height
8780 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8781 // commitment at same time.
8783 let chanmon_cfgs = create_chanmon_cfgs(2);
8784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8786 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8788 // Create some initial channel
8789 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8790 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8792 // Rebalance the network to generate htlc in the two directions
8793 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8795 // Route a HTLC from node 0 to node 1 (but don't settle)
8796 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8798 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8799 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8800 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8801 let persister = test_utils::TestPersister::new();
8803 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8804 let mut w = test_utils::TestVecWriter(Vec::new());
8805 monitor.write(&mut w).unwrap();
8806 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8807 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8808 assert!(new_monitor == *monitor);
8809 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);
8810 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8813 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8814 let block = Block { header, txdata: vec![] };
8815 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8816 // transaction lock time requirements here.
8817 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8818 watchtower.chain_monitor.block_connected(&block, 200);
8820 // Try to update ChannelMonitor
8821 nodes[1].node.claim_funds(preimage);
8822 check_added_monitors!(nodes[1], 1);
8823 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8825 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8826 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8827 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8828 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8829 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8830 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8831 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8832 } else { assert!(false); }
8833 } else { assert!(false); };
8834 // Our local monitor is in-sync and hasn't processed yet timeout
8835 check_added_monitors!(nodes[0], 1);
8836 let events = nodes[0].node.get_and_clear_pending_events();
8837 assert_eq!(events.len(), 1);
8841 fn test_concurrent_monitor_claim() {
8842 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8843 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8844 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8845 // state N+1 confirms. Alice claims output from state N+1.
8847 let chanmon_cfgs = create_chanmon_cfgs(2);
8848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8850 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8852 // Create some initial channel
8853 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8854 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8856 // Rebalance the network to generate htlc in the two directions
8857 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8859 // Route a HTLC from node 0 to node 1 (but don't settle)
8860 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8862 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8863 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8864 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8865 let persister = test_utils::TestPersister::new();
8866 let watchtower_alice = {
8867 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8868 let mut w = test_utils::TestVecWriter(Vec::new());
8869 monitor.write(&mut w).unwrap();
8870 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8871 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8872 assert!(new_monitor == *monitor);
8873 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);
8874 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8877 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8878 let block = Block { header, txdata: vec![] };
8879 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8880 // transaction lock time requirements here.
8881 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8882 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8884 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8886 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8887 assert_eq!(txn.len(), 2);
8891 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8892 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8893 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8894 let persister = test_utils::TestPersister::new();
8895 let watchtower_bob = {
8896 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8897 let mut w = test_utils::TestVecWriter(Vec::new());
8898 monitor.write(&mut w).unwrap();
8899 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8900 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8901 assert!(new_monitor == *monitor);
8902 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);
8903 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8906 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8907 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8909 // Route another payment to generate another update with still previous HTLC pending
8910 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8912 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8914 check_added_monitors!(nodes[1], 1);
8916 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8917 assert_eq!(updates.update_add_htlcs.len(), 1);
8918 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8919 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8920 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8921 // Watchtower Alice should already have seen the block and reject the update
8922 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8923 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8924 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8925 } else { assert!(false); }
8926 } else { assert!(false); };
8927 // Our local monitor is in-sync and hasn't processed yet timeout
8928 check_added_monitors!(nodes[0], 1);
8930 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8931 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8932 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8934 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8937 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8938 assert_eq!(txn.len(), 2);
8939 bob_state_y = txn[0].clone();
8943 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8944 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8945 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);
8947 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8948 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8949 // the onchain detection of the HTLC output
8950 assert_eq!(htlc_txn.len(), 2);
8951 check_spends!(htlc_txn[0], bob_state_y);
8952 check_spends!(htlc_txn[1], bob_state_y);
8957 fn test_pre_lockin_no_chan_closed_update() {
8958 // Test that if a peer closes a channel in response to a funding_created message we don't
8959 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8962 // Doing so would imply a channel monitor update before the initial channel monitor
8963 // registration, violating our API guarantees.
8965 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8966 // then opening a second channel with the same funding output as the first (which is not
8967 // rejected because the first channel does not exist in the ChannelManager) and closing it
8968 // before receiving funding_signed.
8969 let chanmon_cfgs = create_chanmon_cfgs(2);
8970 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8971 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8972 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8974 // Create an initial channel
8975 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8976 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8977 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8978 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8979 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8981 // Move the first channel through the funding flow...
8982 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8984 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8985 check_added_monitors!(nodes[0], 0);
8987 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8988 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8989 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8990 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8991 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8995 fn test_htlc_no_detection() {
8996 // This test is a mutation to underscore the detection logic bug we had
8997 // before #653. HTLC value routed is above the remaining balance, thus
8998 // inverting HTLC and `to_remote` output. HTLC will come second and
8999 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
9000 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
9001 // outputs order detection for correct spending children filtring.
9003 let chanmon_cfgs = create_chanmon_cfgs(2);
9004 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9005 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9006 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9008 // Create some initial channels
9009 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9011 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9012 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9013 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9014 assert_eq!(local_txn[0].input.len(), 1);
9015 assert_eq!(local_txn[0].output.len(), 3);
9016 check_spends!(local_txn[0], chan_1.3);
9018 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9019 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9020 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9021 // We deliberately connect the local tx twice as this should provoke a failure calling
9022 // this test before #653 fix.
9023 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);
9024 check_closed_broadcast!(nodes[0], true);
9025 check_added_monitors!(nodes[0], 1);
9026 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9027 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9029 let htlc_timeout = {
9030 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9031 assert_eq!(node_txn[1].input.len(), 1);
9032 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9033 check_spends!(node_txn[1], local_txn[0]);
9037 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9038 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9039 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9040 expect_payment_failed!(nodes[0], our_payment_hash, true);
9043 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9044 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9045 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9046 // Carol, Alice would be the upstream node, and Carol the downstream.)
9048 // Steps of the test:
9049 // 1) Alice sends a HTLC to Carol through Bob.
9050 // 2) Carol doesn't settle the HTLC.
9051 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9052 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9053 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9054 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9055 // 5) Carol release the preimage to Bob off-chain.
9056 // 6) Bob claims the offered output on the broadcasted commitment.
9057 let chanmon_cfgs = create_chanmon_cfgs(3);
9058 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9059 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9060 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9062 // Create some initial channels
9063 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9064 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9066 // Steps (1) and (2):
9067 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9068 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9070 // Check that Alice's commitment transaction now contains an output for this HTLC.
9071 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9072 check_spends!(alice_txn[0], chan_ab.3);
9073 assert_eq!(alice_txn[0].output.len(), 2);
9074 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9075 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9076 assert_eq!(alice_txn.len(), 2);
9078 // Steps (3) and (4):
9079 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9080 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9081 let mut force_closing_node = 0; // Alice force-closes
9082 let mut counterparty_node = 1; // Bob if Alice force-closes
9085 if !broadcast_alice {
9086 force_closing_node = 1;
9087 counterparty_node = 0;
9089 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9090 check_closed_broadcast!(nodes[force_closing_node], true);
9091 check_added_monitors!(nodes[force_closing_node], 1);
9092 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9093 if go_onchain_before_fulfill {
9094 let txn_to_broadcast = match broadcast_alice {
9095 true => alice_txn.clone(),
9096 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9098 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9099 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9100 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9101 if broadcast_alice {
9102 check_closed_broadcast!(nodes[1], true);
9103 check_added_monitors!(nodes[1], 1);
9104 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9106 assert_eq!(bob_txn.len(), 1);
9107 check_spends!(bob_txn[0], chan_ab.3);
9111 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9112 // process of removing the HTLC from their commitment transactions.
9113 nodes[2].node.claim_funds(payment_preimage);
9114 check_added_monitors!(nodes[2], 1);
9115 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9117 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9118 assert!(carol_updates.update_add_htlcs.is_empty());
9119 assert!(carol_updates.update_fail_htlcs.is_empty());
9120 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9121 assert!(carol_updates.update_fee.is_none());
9122 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9124 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9125 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9126 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9127 if !go_onchain_before_fulfill && broadcast_alice {
9128 let events = nodes[1].node.get_and_clear_pending_msg_events();
9129 assert_eq!(events.len(), 1);
9131 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9132 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9134 _ => panic!("Unexpected event"),
9137 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9138 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9139 // Carol<->Bob's updated commitment transaction info.
9140 check_added_monitors!(nodes[1], 2);
9142 let events = nodes[1].node.get_and_clear_pending_msg_events();
9143 assert_eq!(events.len(), 2);
9144 let bob_revocation = match events[0] {
9145 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9146 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9149 _ => panic!("Unexpected event"),
9151 let bob_updates = match events[1] {
9152 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9153 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9156 _ => panic!("Unexpected event"),
9159 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9160 check_added_monitors!(nodes[2], 1);
9161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9162 check_added_monitors!(nodes[2], 1);
9164 let events = nodes[2].node.get_and_clear_pending_msg_events();
9165 assert_eq!(events.len(), 1);
9166 let carol_revocation = match events[0] {
9167 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9168 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9171 _ => panic!("Unexpected event"),
9173 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9174 check_added_monitors!(nodes[1], 1);
9176 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9177 // here's where we put said channel's commitment tx on-chain.
9178 let mut txn_to_broadcast = alice_txn.clone();
9179 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9180 if !go_onchain_before_fulfill {
9181 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9182 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9183 // If Bob was the one to force-close, he will have already passed these checks earlier.
9184 if broadcast_alice {
9185 check_closed_broadcast!(nodes[1], true);
9186 check_added_monitors!(nodes[1], 1);
9187 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9189 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9190 if broadcast_alice {
9191 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9192 // new block being connected. The ChannelManager being notified triggers a monitor update,
9193 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9194 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9196 assert_eq!(bob_txn.len(), 3);
9197 check_spends!(bob_txn[1], chan_ab.3);
9199 assert_eq!(bob_txn.len(), 2);
9200 check_spends!(bob_txn[0], chan_ab.3);
9205 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9206 // broadcasted commitment transaction.
9208 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9209 if go_onchain_before_fulfill {
9210 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9211 assert_eq!(bob_txn.len(), 2);
9213 let script_weight = match broadcast_alice {
9214 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9215 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9217 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9218 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9219 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9220 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9221 if broadcast_alice && !go_onchain_before_fulfill {
9222 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9223 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9225 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9226 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9232 fn test_onchain_htlc_settlement_after_close() {
9233 do_test_onchain_htlc_settlement_after_close(true, true);
9234 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9235 do_test_onchain_htlc_settlement_after_close(true, false);
9236 do_test_onchain_htlc_settlement_after_close(false, false);
9240 fn test_duplicate_chan_id() {
9241 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9242 // already open we reject it and keep the old channel.
9244 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9245 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9246 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9247 // updating logic for the existing channel.
9248 let chanmon_cfgs = create_chanmon_cfgs(2);
9249 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9250 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9251 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9253 // Create an initial channel
9254 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9255 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9256 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9257 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()));
9259 // Try to create a second channel with the same temporary_channel_id as the first and check
9260 // that it is rejected.
9261 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9263 let events = nodes[1].node.get_and_clear_pending_msg_events();
9264 assert_eq!(events.len(), 1);
9266 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9267 // Technically, at this point, nodes[1] would be justified in thinking both the
9268 // first (valid) and second (invalid) channels are closed, given they both have
9269 // the same non-temporary channel_id. However, currently we do not, so we just
9270 // move forward with it.
9271 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9272 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9274 _ => panic!("Unexpected event"),
9278 // Move the first channel through the funding flow...
9279 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9281 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9282 check_added_monitors!(nodes[0], 0);
9284 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9285 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9287 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9288 assert_eq!(added_monitors.len(), 1);
9289 assert_eq!(added_monitors[0].0, funding_output);
9290 added_monitors.clear();
9292 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9294 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9295 let channel_id = funding_outpoint.to_channel_id();
9297 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9300 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9301 // Technically this is allowed by the spec, but we don't support it and there's little reason
9302 // to. Still, it shouldn't cause any other issues.
9303 open_chan_msg.temporary_channel_id = channel_id;
9304 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9306 let events = nodes[1].node.get_and_clear_pending_msg_events();
9307 assert_eq!(events.len(), 1);
9309 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9310 // Technically, at this point, nodes[1] would be justified in thinking both
9311 // channels are closed, but currently we do not, so we just move forward with it.
9312 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9313 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9315 _ => panic!("Unexpected event"),
9319 // Now try to create a second channel which has a duplicate funding output.
9320 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9321 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9322 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9323 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()));
9324 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9326 let funding_created = {
9327 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9328 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9329 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9330 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9331 // channelmanager in a possibly nonsense state instead).
9332 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9333 let logger = test_utils::TestLogger::new();
9334 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9336 check_added_monitors!(nodes[0], 0);
9337 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9338 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9339 // still needs to be cleared here.
9340 check_added_monitors!(nodes[1], 1);
9342 // ...still, nodes[1] will reject the duplicate channel.
9344 let events = nodes[1].node.get_and_clear_pending_msg_events();
9345 assert_eq!(events.len(), 1);
9347 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9348 // Technically, at this point, nodes[1] would be justified in thinking both
9349 // channels are closed, but currently we do not, so we just move forward with it.
9350 assert_eq!(msg.channel_id, channel_id);
9351 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9353 _ => panic!("Unexpected event"),
9357 // finally, finish creating the original channel and send a payment over it to make sure
9358 // everything is functional.
9359 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9361 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9362 assert_eq!(added_monitors.len(), 1);
9363 assert_eq!(added_monitors[0].0, funding_output);
9364 added_monitors.clear();
9367 let events_4 = nodes[0].node.get_and_clear_pending_events();
9368 assert_eq!(events_4.len(), 0);
9369 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9370 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9372 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9373 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9374 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9375 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9379 fn test_error_chans_closed() {
9380 // Test that we properly handle error messages, closing appropriate channels.
9382 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9383 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9384 // we can test various edge cases around it to ensure we don't regress.
9385 let chanmon_cfgs = create_chanmon_cfgs(3);
9386 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9387 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9388 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9390 // Create some initial channels
9391 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9392 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9393 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9395 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9396 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9397 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9399 // Closing a channel from a different peer has no effect
9400 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9401 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9403 // Closing one channel doesn't impact others
9404 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9405 check_added_monitors!(nodes[0], 1);
9406 check_closed_broadcast!(nodes[0], false);
9407 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9408 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9409 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9410 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);
9411 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);
9413 // A null channel ID should close all channels
9414 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9415 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9416 check_added_monitors!(nodes[0], 2);
9417 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9418 let events = nodes[0].node.get_and_clear_pending_msg_events();
9419 assert_eq!(events.len(), 2);
9421 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9422 assert_eq!(msg.contents.flags & 2, 2);
9424 _ => panic!("Unexpected event"),
9427 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9428 assert_eq!(msg.contents.flags & 2, 2);
9430 _ => panic!("Unexpected event"),
9432 // Note that at this point users of a standard PeerHandler will end up calling
9433 // peer_disconnected with no_connection_possible set to false, duplicating the
9434 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9435 // users with their own peer handling logic. We duplicate the call here, however.
9436 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9437 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9439 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9440 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9441 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9445 fn test_invalid_funding_tx() {
9446 // Test that we properly handle invalid funding transactions sent to us from a peer.
9448 // Previously, all other major lightning implementations had failed to properly sanitize
9449 // funding transactions from their counterparties, leading to a multi-implementation critical
9450 // security vulnerability (though we always sanitized properly, we've previously had
9451 // un-released crashes in the sanitization process).
9453 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9454 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9455 // gave up on it. We test this here by generating such a transaction.
9456 let chanmon_cfgs = create_chanmon_cfgs(2);
9457 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9458 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9459 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9461 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9462 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()));
9463 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()));
9465 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9467 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9468 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9469 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9471 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9472 assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9473 chan_utils::HTLCType::AcceptedHTLC);
9475 let wit_program_script: Script = wit_program.clone().into();
9476 for output in tx.output.iter_mut() {
9477 // Make the confirmed funding transaction have a bogus script_pubkey
9478 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9481 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9482 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()));
9483 check_added_monitors!(nodes[1], 1);
9485 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()));
9486 check_added_monitors!(nodes[0], 1);
9488 let events_1 = nodes[0].node.get_and_clear_pending_events();
9489 assert_eq!(events_1.len(), 0);
9491 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9492 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9493 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9495 let expected_err = "funding tx had wrong script/value or output index";
9496 confirm_transaction_at(&nodes[1], &tx, 1);
9497 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9498 check_added_monitors!(nodes[1], 1);
9499 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9500 assert_eq!(events_2.len(), 1);
9501 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9502 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9503 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9504 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9505 } else { panic!(); }
9506 } else { panic!(); }
9507 assert_eq!(nodes[1].node.list_channels().len(), 0);
9509 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9510 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9511 // as its not 32 bytes long.
9512 let mut spend_tx = Transaction {
9513 version: 2i32, lock_time: 0,
9514 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9515 previous_output: BitcoinOutPoint {
9519 script_sig: Script::new(),
9520 sequence: 0xfffffffd,
9521 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9523 output: vec![TxOut {
9525 script_pubkey: Script::new(),
9528 check_spends!(spend_tx, tx);
9529 mine_transaction(&nodes[1], &spend_tx);
9532 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9533 // In the first version of the chain::Confirm interface, after a refactor was made to not
9534 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9535 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9536 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9537 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9538 // spending transaction until height N+1 (or greater). This was due to the way
9539 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9540 // spending transaction at the height the input transaction was confirmed at, not whether we
9541 // should broadcast a spending transaction at the current height.
9542 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9543 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9544 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9545 // until we learned about an additional block.
9547 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9548 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9549 let chanmon_cfgs = create_chanmon_cfgs(3);
9550 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9551 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9552 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9553 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9555 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9556 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9557 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9558 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9559 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9561 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9562 check_closed_broadcast!(nodes[1], true);
9563 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9564 check_added_monitors!(nodes[1], 1);
9565 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9566 assert_eq!(node_txn.len(), 1);
9568 let conf_height = nodes[1].best_block_info().1;
9569 if !test_height_before_timelock {
9570 connect_blocks(&nodes[1], 24 * 6);
9572 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9573 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9574 if test_height_before_timelock {
9575 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9576 // generate any events or broadcast any transactions
9577 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9578 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9580 // We should broadcast an HTLC transaction spending our funding transaction first
9581 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9582 assert_eq!(spending_txn.len(), 2);
9583 assert_eq!(spending_txn[0], node_txn[0]);
9584 check_spends!(spending_txn[1], node_txn[0]);
9585 // We should also generate a SpendableOutputs event with the to_self output (as its
9587 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9588 assert_eq!(descriptor_spend_txn.len(), 1);
9590 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9591 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9592 // additional block built on top of the current chain.
9593 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9594 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9595 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9596 check_added_monitors!(nodes[1], 1);
9598 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9599 assert!(updates.update_add_htlcs.is_empty());
9600 assert!(updates.update_fulfill_htlcs.is_empty());
9601 assert_eq!(updates.update_fail_htlcs.len(), 1);
9602 assert!(updates.update_fail_malformed_htlcs.is_empty());
9603 assert!(updates.update_fee.is_none());
9604 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9605 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9606 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9611 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9612 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9613 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9617 fn test_forwardable_regen() {
9618 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9619 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9621 // We test it for both payment receipt and payment forwarding.
9623 let chanmon_cfgs = create_chanmon_cfgs(3);
9624 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9625 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9626 let persister: test_utils::TestPersister;
9627 let new_chain_monitor: test_utils::TestChainMonitor;
9628 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9629 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9630 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9631 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9633 // First send a payment to nodes[1]
9634 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9635 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9636 check_added_monitors!(nodes[0], 1);
9638 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9639 assert_eq!(events.len(), 1);
9640 let payment_event = SendEvent::from_event(events.pop().unwrap());
9641 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9642 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9644 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9646 // Next send a payment which is forwarded by nodes[1]
9647 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9648 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9649 check_added_monitors!(nodes[0], 1);
9651 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9652 assert_eq!(events.len(), 1);
9653 let payment_event = SendEvent::from_event(events.pop().unwrap());
9654 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9655 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9657 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9659 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9661 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9662 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9663 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9665 let nodes_1_serialized = nodes[1].node.encode();
9666 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9667 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9668 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9669 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9671 persister = test_utils::TestPersister::new();
9672 let keys_manager = &chanmon_cfgs[1].keys_manager;
9673 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);
9674 nodes[1].chain_monitor = &new_chain_monitor;
9676 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9677 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9678 &mut chan_0_monitor_read, keys_manager).unwrap();
9679 assert!(chan_0_monitor_read.is_empty());
9680 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9681 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9682 &mut chan_1_monitor_read, keys_manager).unwrap();
9683 assert!(chan_1_monitor_read.is_empty());
9685 let mut nodes_1_read = &nodes_1_serialized[..];
9686 let (_, nodes_1_deserialized_tmp) = {
9687 let mut channel_monitors = HashMap::new();
9688 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9689 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9690 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9691 default_config: UserConfig::default(),
9693 fee_estimator: node_cfgs[1].fee_estimator,
9694 chain_monitor: nodes[1].chain_monitor,
9695 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9696 logger: nodes[1].logger,
9700 nodes_1_deserialized = nodes_1_deserialized_tmp;
9701 assert!(nodes_1_read.is_empty());
9703 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9704 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9705 nodes[1].node = &nodes_1_deserialized;
9706 check_added_monitors!(nodes[1], 2);
9708 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9709 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9710 // the commitment state.
9711 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9713 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9715 expect_pending_htlcs_forwardable!(nodes[1]);
9716 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9717 check_added_monitors!(nodes[1], 1);
9719 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9720 assert_eq!(events.len(), 1);
9721 let payment_event = SendEvent::from_event(events.pop().unwrap());
9722 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9723 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9724 expect_pending_htlcs_forwardable!(nodes[2]);
9725 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9727 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9728 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9731 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9732 let chanmon_cfgs = create_chanmon_cfgs(2);
9733 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9734 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9735 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9737 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9739 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9740 .with_features(InvoiceFeatures::known());
9741 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9743 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9746 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9747 check_added_monitors!(nodes[0], 1);
9748 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9749 assert_eq!(events.len(), 1);
9750 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9751 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9752 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9754 expect_pending_htlcs_forwardable!(nodes[1]);
9755 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9758 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9759 check_added_monitors!(nodes[0], 1);
9760 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9761 assert_eq!(events.len(), 1);
9762 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9763 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9764 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9765 // At this point, nodes[1] would notice it has too much value for the payment. It will
9766 // assume the second is a privacy attack (no longer particularly relevant
9767 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9768 // the first HTLC delivered above.
9771 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9772 nodes[1].node.process_pending_htlc_forwards();
9774 if test_for_second_fail_panic {
9775 // Now we go fail back the first HTLC from the user end.
9776 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9778 let expected_destinations = vec![
9779 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9780 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9782 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9783 nodes[1].node.process_pending_htlc_forwards();
9785 check_added_monitors!(nodes[1], 1);
9786 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9787 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9789 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9790 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9791 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9793 let failure_events = nodes[0].node.get_and_clear_pending_events();
9794 assert_eq!(failure_events.len(), 2);
9795 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9796 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9798 // Let the second HTLC fail and claim the first
9799 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9800 nodes[1].node.process_pending_htlc_forwards();
9802 check_added_monitors!(nodes[1], 1);
9803 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9804 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9805 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9807 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9809 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9814 fn test_dup_htlc_second_fail_panic() {
9815 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9816 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9817 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9818 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9819 do_test_dup_htlc_second_rejected(true);
9823 fn test_dup_htlc_second_rejected() {
9824 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9825 // simply reject the second HTLC but are still able to claim the first HTLC.
9826 do_test_dup_htlc_second_rejected(false);
9830 fn test_inconsistent_mpp_params() {
9831 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9832 // such HTLC and allow the second to stay.
9833 let chanmon_cfgs = create_chanmon_cfgs(4);
9834 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9835 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9836 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9838 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9839 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9840 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9841 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9843 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9844 .with_features(InvoiceFeatures::known());
9845 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9846 assert_eq!(route.paths.len(), 2);
9847 route.paths.sort_by(|path_a, _| {
9848 // Sort the path so that the path through nodes[1] comes first
9849 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9850 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9852 let payment_params_opt = Some(payment_params);
9854 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9856 let cur_height = nodes[0].best_block_info().1;
9857 let payment_id = PaymentId([42; 32]);
9859 nodes[0].node.send_payment_along_path(&route.paths[0], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None).unwrap();
9860 check_added_monitors!(nodes[0], 1);
9862 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9863 assert_eq!(events.len(), 1);
9864 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9866 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9869 nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None).unwrap();
9870 check_added_monitors!(nodes[0], 1);
9872 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9873 assert_eq!(events.len(), 1);
9874 let payment_event = SendEvent::from_event(events.pop().unwrap());
9876 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9877 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9879 expect_pending_htlcs_forwardable!(nodes[2]);
9880 check_added_monitors!(nodes[2], 1);
9882 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9883 assert_eq!(events.len(), 1);
9884 let payment_event = SendEvent::from_event(events.pop().unwrap());
9886 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9887 check_added_monitors!(nodes[3], 0);
9888 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9890 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9891 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9892 // post-payment_secrets) and fail back the new HTLC.
9894 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9895 nodes[3].node.process_pending_htlc_forwards();
9896 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9897 nodes[3].node.process_pending_htlc_forwards();
9899 check_added_monitors!(nodes[3], 1);
9901 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9902 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9903 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9905 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9906 check_added_monitors!(nodes[2], 1);
9908 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9909 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9910 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9912 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9914 nodes[0].node.send_payment_along_path(&route.paths[1], &payment_params_opt, &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None).unwrap();
9915 check_added_monitors!(nodes[0], 1);
9917 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9918 assert_eq!(events.len(), 1);
9919 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9921 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9925 fn test_keysend_payments_to_public_node() {
9926 let chanmon_cfgs = create_chanmon_cfgs(2);
9927 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9928 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9929 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9931 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9932 let network_graph = nodes[0].network_graph;
9933 let payer_pubkey = nodes[0].node.get_our_node_id();
9934 let payee_pubkey = nodes[1].node.get_our_node_id();
9935 let route_params = RouteParameters {
9936 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9937 final_value_msat: 10000,
9938 final_cltv_expiry_delta: 40,
9940 let scorer = test_utils::TestScorer::with_penalty(0);
9941 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9942 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9944 let test_preimage = PaymentPreimage([42; 32]);
9945 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9946 check_added_monitors!(nodes[0], 1);
9947 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9948 assert_eq!(events.len(), 1);
9949 let event = events.pop().unwrap();
9950 let path = vec![&nodes[1]];
9951 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9952 claim_payment(&nodes[0], &path, test_preimage);
9956 fn test_keysend_payments_to_private_node() {
9957 let chanmon_cfgs = create_chanmon_cfgs(2);
9958 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9959 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9960 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9962 let payer_pubkey = nodes[0].node.get_our_node_id();
9963 let payee_pubkey = nodes[1].node.get_our_node_id();
9964 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9965 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9967 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9968 let route_params = RouteParameters {
9969 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9970 final_value_msat: 10000,
9971 final_cltv_expiry_delta: 40,
9973 let network_graph = nodes[0].network_graph;
9974 let first_hops = nodes[0].node.list_usable_channels();
9975 let scorer = test_utils::TestScorer::with_penalty(0);
9976 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9977 let route = find_route(
9978 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9979 nodes[0].logger, &scorer, &random_seed_bytes
9982 let test_preimage = PaymentPreimage([42; 32]);
9983 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9984 check_added_monitors!(nodes[0], 1);
9985 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9986 assert_eq!(events.len(), 1);
9987 let event = events.pop().unwrap();
9988 let path = vec![&nodes[1]];
9989 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9990 claim_payment(&nodes[0], &path, test_preimage);
9994 fn test_double_partial_claim() {
9995 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9996 // time out, the sender resends only some of the MPP parts, then the user processes the
9997 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9999 let chanmon_cfgs = create_chanmon_cfgs(4);
10000 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10001 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10002 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10004 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10005 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10006 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10007 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10009 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10010 assert_eq!(route.paths.len(), 2);
10011 route.paths.sort_by(|path_a, _| {
10012 // Sort the path so that the path through nodes[1] comes first
10013 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10014 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10017 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10018 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10019 // amount of time to respond to.
10021 // Connect some blocks to time out the payment
10022 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10023 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10025 let failed_destinations = vec![
10026 HTLCDestination::FailedPayment { payment_hash },
10027 HTLCDestination::FailedPayment { payment_hash },
10029 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
10031 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10033 // nodes[1] now retries one of the two paths...
10034 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10035 check_added_monitors!(nodes[0], 2);
10037 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10038 assert_eq!(events.len(), 2);
10039 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10041 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10042 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10043 nodes[3].node.claim_funds(payment_preimage);
10044 check_added_monitors!(nodes[3], 0);
10045 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10048 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10049 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10050 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10051 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10052 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10053 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10054 // not have the preimage tied to the still-pending HTLC.
10056 // To get to the correct state, on startup we should propagate the preimage to the
10057 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10058 // receiving the preimage without a state update.
10060 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10061 // definitely claimed.
10062 let chanmon_cfgs = create_chanmon_cfgs(4);
10063 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10064 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10066 let persister: test_utils::TestPersister;
10067 let new_chain_monitor: test_utils::TestChainMonitor;
10068 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10070 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10072 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10073 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10074 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10075 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10077 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10078 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10079 assert_eq!(route.paths.len(), 2);
10080 route.paths.sort_by(|path_a, _| {
10081 // Sort the path so that the path through nodes[1] comes first
10082 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10083 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10086 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10087 check_added_monitors!(nodes[0], 2);
10089 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10090 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10091 assert_eq!(send_events.len(), 2);
10092 do_pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[0].clone(), true, false, None);
10093 do_pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), send_events[1].clone(), true, false, None);
10095 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10096 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10097 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10098 if !persist_both_monitors {
10099 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10100 if outpoint.to_channel_id() == chan_id_not_persisted {
10101 assert!(original_monitor.0.is_empty());
10102 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10107 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10108 nodes[3].node.write(&mut original_manager).unwrap();
10110 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10112 nodes[3].node.claim_funds(payment_preimage);
10113 check_added_monitors!(nodes[3], 2);
10114 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10116 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10117 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10118 // with the old ChannelManager.
10119 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10120 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10121 if outpoint.to_channel_id() == chan_id_persisted {
10122 assert!(updated_monitor.0.is_empty());
10123 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10126 // If `persist_both_monitors` is set, get the second monitor here as well
10127 if persist_both_monitors {
10128 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10129 if outpoint.to_channel_id() == chan_id_not_persisted {
10130 assert!(original_monitor.0.is_empty());
10131 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10136 // Now restart nodes[3].
10137 persister = test_utils::TestPersister::new();
10138 let keys_manager = &chanmon_cfgs[3].keys_manager;
10139 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[3].chain_source), nodes[3].tx_broadcaster.clone(), nodes[3].logger, node_cfgs[3].fee_estimator, &persister, keys_manager);
10140 nodes[3].chain_monitor = &new_chain_monitor;
10141 let mut monitors = Vec::new();
10142 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10143 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10144 monitors.push(deserialized_monitor);
10147 let config = UserConfig::default();
10148 nodes_3_deserialized = {
10149 let mut channel_monitors = HashMap::new();
10150 for monitor in monitors.iter_mut() {
10151 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10153 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10154 default_config: config,
10156 fee_estimator: node_cfgs[3].fee_estimator,
10157 chain_monitor: nodes[3].chain_monitor,
10158 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10159 logger: nodes[3].logger,
10163 nodes[3].node = &nodes_3_deserialized;
10165 for monitor in monitors {
10166 // On startup the preimage should have been copied into the non-persisted monitor:
10167 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10168 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10170 check_added_monitors!(nodes[3], 2);
10172 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10173 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10175 // During deserialization, we should have closed one channel and broadcast its latest
10176 // commitment transaction. We should also still have the original PaymentReceived event we
10177 // never finished processing.
10178 let events = nodes[3].node.get_and_clear_pending_events();
10179 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10180 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10181 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10182 if persist_both_monitors {
10183 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10186 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10187 // ChannelManager prior to handling the original one.
10188 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10189 events[if persist_both_monitors { 3 } else { 2 }]
10191 assert_eq!(payment_hash, our_payment_hash);
10192 } else { panic!(); }
10194 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10195 if !persist_both_monitors {
10196 // If one of the two channels is still live, reveal the payment preimage over it.
10198 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10199 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10200 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10201 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10203 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10204 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10205 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10207 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10209 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10210 // claim should fly.
10211 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10212 check_added_monitors!(nodes[3], 1);
10213 assert_eq!(ds_msgs.len(), 2);
10214 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10216 let cs_updates = match ds_msgs[0] {
10217 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10218 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10219 check_added_monitors!(nodes[2], 1);
10220 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10221 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10222 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10228 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10229 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10230 expect_payment_sent!(nodes[0], payment_preimage);
10235 fn test_partial_claim_before_restart() {
10236 do_test_partial_claim_before_restart(false);
10237 do_test_partial_claim_before_restart(true);
10240 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10241 #[derive(Clone, Copy, PartialEq)]
10242 enum ExposureEvent {
10243 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10245 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10247 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10248 AtUpdateFeeOutbound,
10251 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10252 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10255 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10256 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10257 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10258 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10259 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10260 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10261 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10262 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10264 let chanmon_cfgs = create_chanmon_cfgs(2);
10265 let mut config = test_default_channel_config();
10266 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10269 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10271 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10272 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10273 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10274 open_channel.max_accepted_htlcs = 60;
10276 open_channel.dust_limit_satoshis = 546;
10278 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10279 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10280 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10282 let opt_anchors = false;
10284 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10287 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10288 chan.holder_dust_limit_satoshis = 546;
10292 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10293 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()));
10294 check_added_monitors!(nodes[1], 1);
10296 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()));
10297 check_added_monitors!(nodes[0], 1);
10299 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10300 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10301 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10303 let dust_buffer_feerate = {
10304 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10305 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10306 chan.get_dust_buffer_feerate(None) as u64
10308 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;
10309 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10311 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;
10312 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10314 let dust_htlc_on_counterparty_tx: u64 = 25;
10315 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10318 if dust_outbound_balance {
10319 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10320 // Outbound dust balance: 4372 sats
10321 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10322 for i in 0..dust_outbound_htlc_on_holder_tx {
10323 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10324 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10327 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10328 // Inbound dust balance: 4372 sats
10329 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10330 for _ in 0..dust_inbound_htlc_on_holder_tx {
10331 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10335 if dust_outbound_balance {
10336 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10337 // Outbound dust balance: 5000 sats
10338 for i in 0..dust_htlc_on_counterparty_tx {
10339 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10340 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10343 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10344 // Inbound dust balance: 5000 sats
10345 for _ in 0..dust_htlc_on_counterparty_tx {
10346 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10351 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10352 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10353 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 });
10354 let mut config = UserConfig::default();
10355 // With default dust exposure: 5000 sats
10357 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10358 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10359 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
10361 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
10363 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10364 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 });
10365 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10366 check_added_monitors!(nodes[1], 1);
10367 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10368 assert_eq!(events.len(), 1);
10369 let payment_event = SendEvent::from_event(events.remove(0));
10370 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10371 // With default dust exposure: 5000 sats
10373 // Outbound dust balance: 6399 sats
10374 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10375 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10376 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat), 1);
10378 // Outbound dust balance: 5200 sats
10379 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
10381 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10382 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10383 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10385 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10386 *feerate_lock = *feerate_lock * 10;
10388 nodes[0].node.timer_tick_occurred();
10389 check_added_monitors!(nodes[0], 1);
10390 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);
10393 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10394 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10395 added_monitors.clear();
10399 fn test_max_dust_htlc_exposure() {
10400 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10401 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10402 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10403 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10404 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10405 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10406 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10407 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10408 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10409 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10410 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10411 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10415 fn test_non_final_funding_tx() {
10416 let chanmon_cfgs = create_chanmon_cfgs(2);
10417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10419 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10421 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10422 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10423 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10424 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10425 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10427 let best_height = nodes[0].node.best_block.read().unwrap().height();
10429 let chan_id = *nodes[0].network_chan_count.borrow();
10430 let events = nodes[0].node.get_and_clear_pending_events();
10431 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10432 assert_eq!(events.len(), 1);
10433 let mut tx = match events[0] {
10434 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10435 // Timelock the transaction _beyond_ the best client height + 2.
10436 Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10437 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10440 _ => panic!("Unexpected event"),
10442 // Transaction should fail as it's evaluated as non-final for propagation.
10443 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10444 Err(APIError::APIMisuseError { err }) => {
10445 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10450 // However, transaction should be accepted if it's in a +2 headroom from best block.
10452 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10453 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());