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, OptionalField, ErrorAction};
32 use util::enforcing_trait_impls::EnforcingSigner;
33 use util::{byte_utils, test_utils};
34 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
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 sync::{Arc, Mutex};
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
63 fn test_insane_channel_opens() {
64 // Stand up a network of 2 nodes
65 use ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
66 let mut cfg = UserConfig::default();
67 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
68 let chanmon_cfgs = create_chanmon_cfgs(2);
69 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
70 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
71 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
73 // Instantiate channel parameters where we push the maximum msats given our
75 let channel_value_sat = 31337; // same as funding satoshis
76 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
77 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
79 // Have node0 initiate a channel to node1 with aforementioned parameters
80 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
82 // Extract the channel open message from node0 to node1
83 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
85 // Test helper that asserts we get the correct error string given a mutator
86 // that supposedly makes the channel open message insane
87 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
88 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
89 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
90 assert_eq!(msg_events.len(), 1);
91 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
92 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
94 &ErrorAction::SendErrorMessage { .. } => {
95 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
97 _ => panic!("unexpected event!"),
99 } else { assert!(false); }
102 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104 // Test all mutations that would make the channel open message insane
105 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 });
106 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 });
108 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
110 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 });
112 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
114 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 });
116 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 });
118 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
120 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
124 fn test_funding_exceeds_no_wumbo_limit() {
125 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
127 use ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
128 let chanmon_cfgs = create_chanmon_cfgs(2);
129 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
130 node_cfgs[1].features = InitFeatures::known().clear_wumbo();
131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
132 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
134 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
135 Err(APIError::APIMisuseError { err }) => {
136 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
142 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
143 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
144 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
145 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
146 // in normal testing, we test it explicitly here.
147 let chanmon_cfgs = create_chanmon_cfgs(2);
148 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
149 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
150 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
151 let default_config = UserConfig::default();
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, &default_config) * 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 default_config = UserConfig::default();
638 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
640 let opt_anchors = false;
642 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
643 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
644 // calculate two different feerates here - the expected local limit as well as the expected
646 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;
647 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
649 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
650 *feerate_lock = feerate;
652 nodes[0].node.timer_tick_occurred();
653 check_added_monitors!(nodes[0], 1);
654 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
656 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
658 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
660 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
662 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
664 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
665 assert_eq!(commitment_tx.output.len(), 2);
666 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
667 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
668 actual_fee = channel_value - actual_fee;
669 assert_eq!(total_fee, actual_fee);
673 // Increment the feerate by a small constant, accounting for rounding errors
674 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
677 nodes[0].node.timer_tick_occurred();
678 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
679 check_added_monitors!(nodes[0], 0);
681 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
683 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
684 // needed to sign the new commitment tx and (2) sign the new commitment tx.
685 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
686 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
687 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
688 let chan_signer = local_chan.get_signer();
689 let pubkeys = chan_signer.pubkeys();
690 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
691 pubkeys.funding_pubkey)
693 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
694 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
695 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
696 let chan_signer = remote_chan.get_signer();
697 let pubkeys = chan_signer.pubkeys();
698 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
699 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
700 pubkeys.funding_pubkey)
703 // Assemble the set of keys we can use for signatures for our commitment_signed message.
704 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
705 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
708 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
709 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
710 let local_chan_signer = local_chan.get_signer();
711 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
712 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
713 INITIAL_COMMITMENT_NUMBER - 1,
715 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
716 opt_anchors, local_funding, remote_funding,
717 commit_tx_keys.clone(),
718 non_buffer_feerate + 4,
720 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
722 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
725 let commit_signed_msg = msgs::CommitmentSigned {
728 htlc_signatures: res.1
731 let update_fee = msgs::UpdateFee {
733 feerate_per_kw: non_buffer_feerate + 4,
736 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
738 //While producing the commitment_signed response after handling a received update_fee request the
739 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
740 //Should produce and error.
741 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
742 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
743 check_added_monitors!(nodes[1], 1);
744 check_closed_broadcast!(nodes[1], true);
745 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
749 fn test_update_fee_with_fundee_update_add_htlc() {
750 let chanmon_cfgs = create_chanmon_cfgs(2);
751 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
752 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
753 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
754 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
757 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
760 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
763 nodes[0].node.timer_tick_occurred();
764 check_added_monitors!(nodes[0], 1);
766 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
767 assert_eq!(events_0.len(), 1);
768 let (update_msg, commitment_signed) = match events_0[0] {
769 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 } } => {
770 (update_fee.as_ref(), commitment_signed)
772 _ => panic!("Unexpected event"),
774 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
776 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
777 check_added_monitors!(nodes[1], 1);
779 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
781 // nothing happens since node[1] is in AwaitingRemoteRevoke
782 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
784 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
785 assert_eq!(added_monitors.len(), 0);
786 added_monitors.clear();
788 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
789 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
790 // node[1] has nothing to do
792 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
793 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
794 check_added_monitors!(nodes[0], 1);
796 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
797 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
798 // No commitment_signed so get_event_msg's assert(len == 1) passes
799 check_added_monitors!(nodes[0], 1);
800 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
801 check_added_monitors!(nodes[1], 1);
802 // AwaitingRemoteRevoke ends here
804 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
805 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
806 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
807 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
808 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
809 assert_eq!(commitment_update.update_fee.is_none(), true);
811 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
812 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
813 check_added_monitors!(nodes[0], 1);
814 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
816 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
817 check_added_monitors!(nodes[1], 1);
818 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
820 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
821 check_added_monitors!(nodes[1], 1);
822 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
823 // No commitment_signed so get_event_msg's assert(len == 1) passes
825 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
826 check_added_monitors!(nodes[0], 1);
827 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
829 expect_pending_htlcs_forwardable!(nodes[0]);
831 let events = nodes[0].node.get_and_clear_pending_events();
832 assert_eq!(events.len(), 1);
834 Event::PaymentReceived { .. } => { },
835 _ => panic!("Unexpected event"),
838 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
840 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
841 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
842 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
843 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
844 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
848 fn test_update_fee() {
849 let chanmon_cfgs = create_chanmon_cfgs(2);
850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
852 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
853 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
854 let channel_id = chan.2;
857 // (1) update_fee/commitment_signed ->
858 // <- (2) revoke_and_ack
859 // .- send (3) commitment_signed
860 // (4) update_fee/commitment_signed ->
861 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
862 // <- (3) commitment_signed delivered
863 // send (6) revoke_and_ack -.
864 // <- (5) deliver revoke_and_ack
865 // (6) deliver revoke_and_ack ->
866 // .- send (7) commitment_signed in response to (4)
867 // <- (7) deliver commitment_signed
870 // Create and deliver (1)...
873 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
874 feerate = *feerate_lock;
875 *feerate_lock = feerate + 20;
877 nodes[0].node.timer_tick_occurred();
878 check_added_monitors!(nodes[0], 1);
880 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
881 assert_eq!(events_0.len(), 1);
882 let (update_msg, commitment_signed) = match events_0[0] {
883 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 } } => {
884 (update_fee.as_ref(), commitment_signed)
886 _ => panic!("Unexpected event"),
888 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
890 // Generate (2) and (3):
891 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
892 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
893 check_added_monitors!(nodes[1], 1);
896 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
897 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
898 check_added_monitors!(nodes[0], 1);
900 // Create and deliver (4)...
902 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
903 *feerate_lock = feerate + 30;
905 nodes[0].node.timer_tick_occurred();
906 check_added_monitors!(nodes[0], 1);
907 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
908 assert_eq!(events_0.len(), 1);
909 let (update_msg, commitment_signed) = match events_0[0] {
910 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 } } => {
911 (update_fee.as_ref(), commitment_signed)
913 _ => panic!("Unexpected event"),
916 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
917 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
918 check_added_monitors!(nodes[1], 1);
920 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
921 // No commitment_signed so get_event_msg's assert(len == 1) passes
923 // Handle (3), creating (6):
924 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
925 check_added_monitors!(nodes[0], 1);
926 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
927 // No commitment_signed so get_event_msg's assert(len == 1) passes
930 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
931 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
932 check_added_monitors!(nodes[0], 1);
934 // Deliver (6), creating (7):
935 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
936 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
937 assert!(commitment_update.update_add_htlcs.is_empty());
938 assert!(commitment_update.update_fulfill_htlcs.is_empty());
939 assert!(commitment_update.update_fail_htlcs.is_empty());
940 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
941 assert!(commitment_update.update_fee.is_none());
942 check_added_monitors!(nodes[1], 1);
945 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
946 check_added_monitors!(nodes[0], 1);
947 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
948 // No commitment_signed so get_event_msg's assert(len == 1) passes
950 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
951 check_added_monitors!(nodes[1], 1);
952 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
954 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
955 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
956 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
957 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
958 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
962 fn fake_network_test() {
963 // Simple test which builds a network of ChannelManagers, connects them to each other, and
964 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
965 let chanmon_cfgs = create_chanmon_cfgs(4);
966 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
967 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
968 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
970 // Create some initial channels
971 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
972 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
973 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
975 // Rebalance the network a bit by relaying one payment through all the channels...
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);
979 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
981 // Send some more payments
982 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
983 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
984 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
986 // Test failure packets
987 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
988 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
990 // Add a new channel that skips 3
991 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
994 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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);
999 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1001 // Do some rebalance loop payments, simultaneously
1002 let mut hops = Vec::with_capacity(3);
1003 hops.push(RouteHop {
1004 pubkey: nodes[2].node.get_our_node_id(),
1005 node_features: NodeFeatures::empty(),
1006 short_channel_id: chan_2.0.contents.short_channel_id,
1007 channel_features: ChannelFeatures::empty(),
1009 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1011 hops.push(RouteHop {
1012 pubkey: nodes[3].node.get_our_node_id(),
1013 node_features: NodeFeatures::empty(),
1014 short_channel_id: chan_3.0.contents.short_channel_id,
1015 channel_features: ChannelFeatures::empty(),
1017 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1019 hops.push(RouteHop {
1020 pubkey: nodes[1].node.get_our_node_id(),
1021 node_features: NodeFeatures::known(),
1022 short_channel_id: chan_4.0.contents.short_channel_id,
1023 channel_features: ChannelFeatures::known(),
1025 cltv_expiry_delta: TEST_FINAL_CLTV,
1027 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;
1028 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;
1029 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;
1031 let mut hops = Vec::with_capacity(3);
1032 hops.push(RouteHop {
1033 pubkey: nodes[3].node.get_our_node_id(),
1034 node_features: NodeFeatures::empty(),
1035 short_channel_id: chan_4.0.contents.short_channel_id,
1036 channel_features: ChannelFeatures::empty(),
1038 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1040 hops.push(RouteHop {
1041 pubkey: nodes[2].node.get_our_node_id(),
1042 node_features: NodeFeatures::empty(),
1043 short_channel_id: chan_3.0.contents.short_channel_id,
1044 channel_features: ChannelFeatures::empty(),
1046 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1048 hops.push(RouteHop {
1049 pubkey: nodes[1].node.get_our_node_id(),
1050 node_features: NodeFeatures::known(),
1051 short_channel_id: chan_2.0.contents.short_channel_id,
1052 channel_features: ChannelFeatures::known(),
1054 cltv_expiry_delta: TEST_FINAL_CLTV,
1056 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;
1057 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;
1058 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;
1060 // Claim the rebalances...
1061 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1062 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1064 // Add a duplicate new channel from 2 to 4
1065 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1067 // Send some payments across both channels
1068 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1069 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1070 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1073 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1074 let events = nodes[0].node.get_and_clear_pending_msg_events();
1075 assert_eq!(events.len(), 0);
1076 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1078 //TODO: Test that routes work again here as we've been notified that the channel is full
1080 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1081 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1082 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1084 // Close down the channels...
1085 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1086 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1092 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1093 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1095 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1097 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1098 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1099 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1103 fn holding_cell_htlc_counting() {
1104 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1105 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1106 // commitment dance rounds.
1107 let chanmon_cfgs = create_chanmon_cfgs(3);
1108 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1109 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1110 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1111 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1112 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1114 let mut payments = Vec::new();
1115 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1116 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1117 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1118 payments.push((payment_preimage, payment_hash));
1120 check_added_monitors!(nodes[1], 1);
1122 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1123 assert_eq!(events.len(), 1);
1124 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1125 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1127 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1128 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1130 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1132 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1133 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1135 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1138 // This should also be true if we try to forward a payment.
1139 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1141 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1142 check_added_monitors!(nodes[0], 1);
1145 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1146 assert_eq!(events.len(), 1);
1147 let payment_event = SendEvent::from_event(events.pop().unwrap());
1148 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1150 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1151 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1152 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1153 // fails), the second will process the resulting failure and fail the HTLC backward.
1154 expect_pending_htlcs_forwardable!(nodes[1]);
1155 expect_pending_htlcs_forwardable!(nodes[1]);
1156 check_added_monitors!(nodes[1], 1);
1158 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1159 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1160 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1162 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1164 // Now forward all the pending HTLCs and claim them back
1165 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1166 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1167 check_added_monitors!(nodes[2], 1);
1169 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1170 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1171 check_added_monitors!(nodes[1], 1);
1172 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1174 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1175 check_added_monitors!(nodes[1], 1);
1176 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1178 for ref update in as_updates.update_add_htlcs.iter() {
1179 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1181 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1182 check_added_monitors!(nodes[2], 1);
1183 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1184 check_added_monitors!(nodes[2], 1);
1185 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1187 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1188 check_added_monitors!(nodes[1], 1);
1189 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1190 check_added_monitors!(nodes[1], 1);
1191 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1193 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1194 check_added_monitors!(nodes[2], 1);
1196 expect_pending_htlcs_forwardable!(nodes[2]);
1198 let events = nodes[2].node.get_and_clear_pending_events();
1199 assert_eq!(events.len(), payments.len());
1200 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1202 &Event::PaymentReceived { ref payment_hash, .. } => {
1203 assert_eq!(*payment_hash, *hash);
1205 _ => panic!("Unexpected event"),
1209 for (preimage, _) in payments.drain(..) {
1210 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1213 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1217 fn duplicate_htlc_test() {
1218 // Test that we accept duplicate payment_hash HTLCs across the network and that
1219 // claiming/failing them are all separate and don't affect each other
1220 let chanmon_cfgs = create_chanmon_cfgs(6);
1221 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1222 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1223 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1225 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1226 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1227 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1228 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1229 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1230 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1232 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1234 *nodes[0].network_payment_count.borrow_mut() -= 1;
1235 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1237 *nodes[0].network_payment_count.borrow_mut() -= 1;
1238 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1240 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1241 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1242 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1246 fn test_duplicate_htlc_different_direction_onchain() {
1247 // Test that ChannelMonitor doesn't generate 2 preimage txn
1248 // when we have 2 HTLCs with same preimage that go across a node
1249 // in opposite directions, even with the same payment secret.
1250 let chanmon_cfgs = create_chanmon_cfgs(2);
1251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1253 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1255 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1258 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1260 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1262 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1263 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1264 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1266 // Provide preimage to node 0 by claiming payment
1267 nodes[0].node.claim_funds(payment_preimage);
1268 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1269 check_added_monitors!(nodes[0], 1);
1271 // Broadcast node 1 commitment txn
1272 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1274 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1275 let mut has_both_htlcs = 0; // check htlcs match ones committed
1276 for outp in remote_txn[0].output.iter() {
1277 if outp.value == 800_000 / 1000 {
1278 has_both_htlcs += 1;
1279 } else if outp.value == 900_000 / 1000 {
1280 has_both_htlcs += 1;
1283 assert_eq!(has_both_htlcs, 2);
1285 mine_transaction(&nodes[0], &remote_txn[0]);
1286 check_added_monitors!(nodes[0], 1);
1287 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1288 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1290 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1291 assert_eq!(claim_txn.len(), 8);
1293 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1295 check_spends!(claim_txn[1], chan_1.3); // Alternative commitment tx
1296 check_spends!(claim_txn[2], claim_txn[1]); // HTLC spend in alternative commitment tx
1298 let bump_tx = if claim_txn[1] == claim_txn[4] {
1299 assert_eq!(claim_txn[1], claim_txn[4]);
1300 assert_eq!(claim_txn[2], claim_txn[5]);
1302 check_spends!(claim_txn[7], claim_txn[1]); // HTLC timeout on alternative commitment tx
1304 check_spends!(claim_txn[3], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1307 assert_eq!(claim_txn[1], claim_txn[3]);
1308 assert_eq!(claim_txn[2], claim_txn[4]);
1310 check_spends!(claim_txn[5], claim_txn[1]); // HTLC timeout on alternative commitment tx
1312 check_spends!(claim_txn[7], remote_txn[0]); // HTLC timeout on broadcasted commitment tx
1317 assert_eq!(claim_txn[0].input.len(), 1);
1318 assert_eq!(bump_tx.input.len(), 1);
1319 assert_eq!(claim_txn[0].input[0].previous_output, bump_tx.input[0].previous_output);
1321 assert_eq!(claim_txn[0].input.len(), 1);
1322 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1323 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1325 assert_eq!(claim_txn[6].input.len(), 1);
1326 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1327 check_spends!(claim_txn[6], remote_txn[0]);
1328 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1330 let events = nodes[0].node.get_and_clear_pending_msg_events();
1331 assert_eq!(events.len(), 3);
1334 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1335 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1336 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1337 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1339 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, .. } } => {
1340 assert!(update_add_htlcs.is_empty());
1341 assert!(update_fail_htlcs.is_empty());
1342 assert_eq!(update_fulfill_htlcs.len(), 1);
1343 assert!(update_fail_malformed_htlcs.is_empty());
1344 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1346 _ => panic!("Unexpected event"),
1352 fn test_basic_channel_reserve() {
1353 let chanmon_cfgs = create_chanmon_cfgs(2);
1354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1356 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1359 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1360 let channel_reserve = chan_stat.channel_reserve_msat;
1362 // The 2* and +1 are for the fee spike reserve.
1363 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1364 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1365 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1366 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1368 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1370 &APIError::ChannelUnavailable{ref err} =>
1371 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1372 _ => panic!("Unexpected error variant"),
1375 _ => panic!("Unexpected error variant"),
1377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1378 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);
1380 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1384 fn test_fee_spike_violation_fails_htlc() {
1385 let chanmon_cfgs = create_chanmon_cfgs(2);
1386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1389 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1391 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1392 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1393 let secp_ctx = Secp256k1::new();
1394 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1396 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1398 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1399 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1400 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1401 let msg = msgs::UpdateAddHTLC {
1404 amount_msat: htlc_msat,
1405 payment_hash: payment_hash,
1406 cltv_expiry: htlc_cltv,
1407 onion_routing_packet: onion_packet,
1410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1412 // Now manually create the commitment_signed message corresponding to the update_add
1413 // nodes[0] just sent. In the code for construction of this message, "local" refers
1414 // to the sender of the message, and "remote" refers to the receiver.
1416 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1418 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1420 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1421 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1422 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1423 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1424 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1425 let chan_signer = local_chan.get_signer();
1426 // Make the signer believe we validated another commitment, so we can release the secret
1427 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1429 let pubkeys = chan_signer.pubkeys();
1430 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1431 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1432 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1433 chan_signer.pubkeys().funding_pubkey)
1435 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1436 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1437 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1438 let chan_signer = remote_chan.get_signer();
1439 let pubkeys = chan_signer.pubkeys();
1440 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1441 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1442 chan_signer.pubkeys().funding_pubkey)
1445 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1446 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1447 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1449 // Build the remote commitment transaction so we can sign it, and then later use the
1450 // signature for the commitment_signed message.
1451 let local_chan_balance = 1313;
1453 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1455 amount_msat: 3460001,
1456 cltv_expiry: htlc_cltv,
1458 transaction_output_index: Some(1),
1461 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1464 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1465 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1466 let local_chan_signer = local_chan.get_signer();
1467 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1471 local_chan.opt_anchors(), local_funding, remote_funding,
1472 commit_tx_keys.clone(),
1474 &mut vec![(accepted_htlc_info, ())],
1475 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1477 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1480 let commit_signed_msg = msgs::CommitmentSigned {
1483 htlc_signatures: res.1
1486 // Send the commitment_signed message to the nodes[1].
1487 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1488 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1490 // Send the RAA to nodes[1].
1491 let raa_msg = msgs::RevokeAndACK {
1493 per_commitment_secret: local_secret,
1494 next_per_commitment_point: next_local_point
1496 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1498 let events = nodes[1].node.get_and_clear_pending_msg_events();
1499 assert_eq!(events.len(), 1);
1500 // Make sure the HTLC failed in the way we expect.
1502 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1503 assert_eq!(update_fail_htlcs.len(), 1);
1504 update_fail_htlcs[0].clone()
1506 _ => panic!("Unexpected event"),
1508 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1509 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1511 check_added_monitors!(nodes[1], 2);
1515 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1516 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1517 // Set the fee rate for the channel very high, to the point where the fundee
1518 // sending any above-dust amount would result in a channel reserve violation.
1519 // In this test we check that we would be prevented from sending an HTLC in
1521 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1522 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1523 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1524 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1525 let default_config = UserConfig::default();
1526 let opt_anchors = false;
1528 let mut push_amt = 100_000_000;
1529 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1531 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1533 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1535 // Sending exactly enough to hit the reserve amount should be accepted
1536 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1537 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1540 // However one more HTLC should be significantly over the reserve amount and fail.
1541 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1542 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1543 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1544 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1545 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);
1549 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1550 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1551 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1554 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1555 let default_config = UserConfig::default();
1556 let opt_anchors = false;
1558 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1559 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1560 // transaction fee with 0 HTLCs (183 sats)).
1561 let mut push_amt = 100_000_000;
1562 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1563 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1564 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1566 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1567 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1568 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1571 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1572 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1573 let secp_ctx = Secp256k1::new();
1574 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1575 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1576 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1577 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1578 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1579 let msg = msgs::UpdateAddHTLC {
1581 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1582 amount_msat: htlc_msat,
1583 payment_hash: payment_hash,
1584 cltv_expiry: htlc_cltv,
1585 onion_routing_packet: onion_packet,
1588 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1589 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1590 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);
1591 assert_eq!(nodes[0].node.list_channels().len(), 0);
1592 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1593 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1594 check_added_monitors!(nodes[0], 1);
1595 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() });
1599 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1600 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1601 // calculating our commitment transaction fee (this was previously broken).
1602 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1603 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1605 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1607 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1608 let default_config = UserConfig::default();
1609 let opt_anchors = false;
1611 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1612 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1613 // transaction fee with 0 HTLCs (183 sats)).
1614 let mut push_amt = 100_000_000;
1615 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1616 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1617 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1619 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1620 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1621 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1622 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1623 // commitment transaction fee.
1624 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1626 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1627 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1628 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1631 // One more than the dust amt should fail, however.
1632 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1633 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1634 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1638 fn test_chan_init_feerate_unaffordability() {
1639 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1640 // channel reserve and feerate requirements.
1641 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1642 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1645 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1646 let default_config = UserConfig::default();
1647 let opt_anchors = false;
1649 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1651 let mut push_amt = 100_000_000;
1652 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1653 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1654 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1656 // During open, we don't have a "counterparty channel reserve" to check against, so that
1657 // requirement only comes into play on the open_channel handling side.
1658 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1659 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1660 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1661 open_channel_msg.push_msat += 1;
1662 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1664 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1665 assert_eq!(msg_events.len(), 1);
1666 match msg_events[0] {
1667 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1668 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1670 _ => panic!("Unexpected event"),
1675 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1676 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1677 // calculating our counterparty's commitment transaction fee (this was previously broken).
1678 let chanmon_cfgs = create_chanmon_cfgs(2);
1679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1681 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1682 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1684 let payment_amt = 46000; // Dust amount
1685 // In the previous code, these first four payments would succeed.
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1699 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1700 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1701 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1705 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1706 let chanmon_cfgs = create_chanmon_cfgs(3);
1707 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1708 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1709 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1710 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1711 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1714 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1715 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1716 let feerate = get_feerate!(nodes[0], chan.2);
1717 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1719 // Add a 2* and +1 for the fee spike reserve.
1720 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1721 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;
1722 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1724 // Add a pending HTLC.
1725 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1726 let payment_event_1 = {
1727 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1728 check_added_monitors!(nodes[0], 1);
1730 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1731 assert_eq!(events.len(), 1);
1732 SendEvent::from_event(events.remove(0))
1734 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1736 // Attempt to trigger a channel reserve violation --> payment failure.
1737 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1738 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;
1739 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1740 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1742 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1743 let secp_ctx = Secp256k1::new();
1744 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1745 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1746 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1747 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1748 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1749 let msg = msgs::UpdateAddHTLC {
1752 amount_msat: htlc_msat + 1,
1753 payment_hash: our_payment_hash_1,
1754 cltv_expiry: htlc_cltv,
1755 onion_routing_packet: onion_packet,
1758 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1759 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1760 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1761 assert_eq!(nodes[1].node.list_channels().len(), 1);
1762 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1763 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1764 check_added_monitors!(nodes[1], 1);
1765 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1769 fn test_inbound_outbound_capacity_is_not_zero() {
1770 let chanmon_cfgs = create_chanmon_cfgs(2);
1771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1774 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1775 let channels0 = node_chanmgrs[0].list_channels();
1776 let channels1 = node_chanmgrs[1].list_channels();
1777 let default_config = UserConfig::default();
1778 assert_eq!(channels0.len(), 1);
1779 assert_eq!(channels1.len(), 1);
1781 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1782 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1783 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1785 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1786 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1789 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1790 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1794 fn test_channel_reserve_holding_cell_htlcs() {
1795 let chanmon_cfgs = create_chanmon_cfgs(3);
1796 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1797 // When this test was written, the default base fee floated based on the HTLC count.
1798 // It is now fixed, so we simply set the fee to the expected value here.
1799 let mut config = test_default_channel_config();
1800 config.channel_config.forwarding_fee_base_msat = 239;
1801 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1802 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1803 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1804 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1806 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1807 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1809 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1810 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1812 macro_rules! expect_forward {
1814 let mut events = $node.node.get_and_clear_pending_msg_events();
1815 assert_eq!(events.len(), 1);
1816 check_added_monitors!($node, 1);
1817 let payment_event = SendEvent::from_event(events.remove(0));
1822 let feemsat = 239; // set above
1823 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1824 let feerate = get_feerate!(nodes[0], chan_1.2);
1825 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1827 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1829 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1831 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1832 .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1833 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);
1834 route.paths[0].last_mut().unwrap().fee_msat += 1;
1835 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1837 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1838 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)));
1839 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1840 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);
1843 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1844 // nodes[0]'s wealth
1846 let amt_msat = recv_value_0 + total_fee_msat;
1847 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1848 // Also, ensure that each payment has enough to be over the dust limit to
1849 // ensure it'll be included in each commit tx fee calculation.
1850 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1851 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1852 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1856 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())
1857 .with_features(InvoiceFeatures::known()).with_max_channel_saturation_power_of_half(0);
1858 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1859 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1860 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1862 let (stat01_, stat11_, stat12_, stat22_) = (
1863 get_channel_value_stat!(nodes[0], chan_1.2),
1864 get_channel_value_stat!(nodes[1], chan_1.2),
1865 get_channel_value_stat!(nodes[1], chan_2.2),
1866 get_channel_value_stat!(nodes[2], chan_2.2),
1869 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1870 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1871 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1872 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1873 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1876 // adding pending output.
1877 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1878 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1879 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1880 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1881 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1882 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1883 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1884 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1885 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1887 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1888 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1889 let amt_msat_1 = recv_value_1 + total_fee_msat;
1891 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);
1892 let payment_event_1 = {
1893 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1894 check_added_monitors!(nodes[0], 1);
1896 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1897 assert_eq!(events.len(), 1);
1898 SendEvent::from_event(events.remove(0))
1900 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1902 // channel reserve test with htlc pending output > 0
1903 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1905 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 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());
1911 // split the rest to test holding cell
1912 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1913 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1914 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1915 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1917 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1918 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);
1921 // now see if they go through on both sides
1922 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);
1923 // but this will stuck in the holding cell
1924 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1925 check_added_monitors!(nodes[0], 0);
1926 let events = nodes[0].node.get_and_clear_pending_events();
1927 assert_eq!(events.len(), 0);
1929 // test with outbound holding cell amount > 0
1931 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1932 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1933 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1934 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1935 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);
1938 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);
1939 // this will also stuck in the holding cell
1940 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1941 check_added_monitors!(nodes[0], 0);
1942 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1943 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1945 // flush the pending htlc
1946 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1947 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1948 check_added_monitors!(nodes[1], 1);
1950 // the pending htlc should be promoted to committed
1951 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1952 check_added_monitors!(nodes[0], 1);
1953 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1956 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1957 // No commitment_signed so get_event_msg's assert(len == 1) passes
1958 check_added_monitors!(nodes[0], 1);
1960 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1961 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1962 check_added_monitors!(nodes[1], 1);
1964 expect_pending_htlcs_forwardable!(nodes[1]);
1966 let ref payment_event_11 = expect_forward!(nodes[1]);
1967 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1968 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1970 expect_pending_htlcs_forwardable!(nodes[2]);
1971 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1973 // flush the htlcs in the holding cell
1974 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1975 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1976 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1977 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1978 expect_pending_htlcs_forwardable!(nodes[1]);
1980 let ref payment_event_3 = expect_forward!(nodes[1]);
1981 assert_eq!(payment_event_3.msgs.len(), 2);
1982 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1983 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1985 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1986 expect_pending_htlcs_forwardable!(nodes[2]);
1988 let events = nodes[2].node.get_and_clear_pending_events();
1989 assert_eq!(events.len(), 2);
1991 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
1992 assert_eq!(our_payment_hash_21, *payment_hash);
1993 assert_eq!(recv_value_21, amount_msat);
1995 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1996 assert!(payment_preimage.is_none());
1997 assert_eq!(our_payment_secret_21, *payment_secret);
1999 _ => panic!("expected PaymentPurpose::InvoicePayment")
2002 _ => panic!("Unexpected event"),
2005 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
2006 assert_eq!(our_payment_hash_22, *payment_hash);
2007 assert_eq!(recv_value_22, amount_msat);
2009 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2010 assert!(payment_preimage.is_none());
2011 assert_eq!(our_payment_secret_22, *payment_secret);
2013 _ => panic!("expected PaymentPurpose::InvoicePayment")
2016 _ => panic!("Unexpected event"),
2019 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2020 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2021 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2023 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2024 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2025 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2027 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2028 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);
2029 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2030 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2031 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2033 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2034 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2038 fn channel_reserve_in_flight_removes() {
2039 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2040 // can send to its counterparty, but due to update ordering, the other side may not yet have
2041 // considered those HTLCs fully removed.
2042 // This tests that we don't count HTLCs which will not be included in the next remote
2043 // commitment transaction towards the reserve value (as it implies no commitment transaction
2044 // will be generated which violates the remote reserve value).
2045 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2047 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2048 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2049 // you only consider the value of the first HTLC, it may not),
2050 // * start routing a third HTLC from A to B,
2051 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2052 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2053 // * deliver the first fulfill from B
2054 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2056 // * deliver A's response CS and RAA.
2057 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2058 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2059 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2060 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2061 let chanmon_cfgs = create_chanmon_cfgs(2);
2062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2064 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2065 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2067 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2068 // Route the first two HTLCs.
2069 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2070 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2071 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2073 // Start routing the third HTLC (this is just used to get everyone in the right state).
2074 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2076 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2077 check_added_monitors!(nodes[0], 1);
2078 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2079 assert_eq!(events.len(), 1);
2080 SendEvent::from_event(events.remove(0))
2083 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2084 // initial fulfill/CS.
2085 nodes[1].node.claim_funds(payment_preimage_1);
2086 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2087 check_added_monitors!(nodes[1], 1);
2088 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2090 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2091 // remove the second HTLC when we send the HTLC back from B to A.
2092 nodes[1].node.claim_funds(payment_preimage_2);
2093 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2094 check_added_monitors!(nodes[1], 1);
2095 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2097 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2098 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2099 check_added_monitors!(nodes[0], 1);
2100 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2101 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2103 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2105 check_added_monitors!(nodes[1], 1);
2106 // B is already AwaitingRAA, so cant generate a CS here
2107 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2109 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2110 check_added_monitors!(nodes[1], 1);
2111 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2113 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2114 check_added_monitors!(nodes[0], 1);
2115 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2117 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2118 check_added_monitors!(nodes[1], 1);
2119 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2121 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2122 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2123 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2124 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2125 // on-chain as necessary).
2126 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2127 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2128 check_added_monitors!(nodes[0], 1);
2129 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2130 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2132 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2133 check_added_monitors!(nodes[1], 1);
2134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2136 expect_pending_htlcs_forwardable!(nodes[1]);
2137 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2139 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2140 // resolve the second HTLC from A's point of view.
2141 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2142 check_added_monitors!(nodes[0], 1);
2143 expect_payment_path_successful!(nodes[0]);
2144 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2146 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2147 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2148 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2150 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2151 check_added_monitors!(nodes[1], 1);
2152 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2153 assert_eq!(events.len(), 1);
2154 SendEvent::from_event(events.remove(0))
2157 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2158 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2159 check_added_monitors!(nodes[0], 1);
2160 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2162 // Now just resolve all the outstanding messages/HTLCs for completeness...
2164 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2165 check_added_monitors!(nodes[1], 1);
2166 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2168 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2169 check_added_monitors!(nodes[1], 1);
2171 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2172 check_added_monitors!(nodes[0], 1);
2173 expect_payment_path_successful!(nodes[0]);
2174 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2176 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2177 check_added_monitors!(nodes[1], 1);
2178 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2180 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2181 check_added_monitors!(nodes[0], 1);
2183 expect_pending_htlcs_forwardable!(nodes[0]);
2184 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2186 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2187 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2191 fn channel_monitor_network_test() {
2192 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2193 // tests that ChannelMonitor is able to recover from various states.
2194 let chanmon_cfgs = create_chanmon_cfgs(5);
2195 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2196 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2197 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2199 // Create some initial channels
2200 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2201 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2202 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2203 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2205 // Make sure all nodes are at the same starting height
2206 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2207 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2208 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2209 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2210 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2212 // Rebalance the network a bit by relaying one payment through all the channels...
2213 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2214 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2215 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2216 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2218 // Simple case with no pending HTLCs:
2219 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2220 check_added_monitors!(nodes[1], 1);
2221 check_closed_broadcast!(nodes[1], true);
2223 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2224 assert_eq!(node_txn.len(), 1);
2225 mine_transaction(&nodes[0], &node_txn[0]);
2226 check_added_monitors!(nodes[0], 1);
2227 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2229 check_closed_broadcast!(nodes[0], true);
2230 assert_eq!(nodes[0].node.list_channels().len(), 0);
2231 assert_eq!(nodes[1].node.list_channels().len(), 1);
2232 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2233 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2235 // One pending HTLC is discarded by the force-close:
2236 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2238 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2239 // broadcasted until we reach the timelock time).
2240 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2241 check_closed_broadcast!(nodes[1], true);
2242 check_added_monitors!(nodes[1], 1);
2244 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2245 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2246 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2247 mine_transaction(&nodes[2], &node_txn[0]);
2248 check_added_monitors!(nodes[2], 1);
2249 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2251 check_closed_broadcast!(nodes[2], true);
2252 assert_eq!(nodes[1].node.list_channels().len(), 0);
2253 assert_eq!(nodes[2].node.list_channels().len(), 1);
2254 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2255 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2257 macro_rules! claim_funds {
2258 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2260 $node.node.claim_funds($preimage);
2261 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2262 check_added_monitors!($node, 1);
2264 let events = $node.node.get_and_clear_pending_msg_events();
2265 assert_eq!(events.len(), 1);
2267 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2268 assert!(update_add_htlcs.is_empty());
2269 assert!(update_fail_htlcs.is_empty());
2270 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2272 _ => panic!("Unexpected event"),
2278 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2279 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2280 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2281 check_added_monitors!(nodes[2], 1);
2282 check_closed_broadcast!(nodes[2], true);
2283 let node2_commitment_txid;
2285 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2286 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2287 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2288 node2_commitment_txid = node_txn[0].txid();
2290 // Claim the payment on nodes[3], giving it knowledge of the preimage
2291 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2292 mine_transaction(&nodes[3], &node_txn[0]);
2293 check_added_monitors!(nodes[3], 1);
2294 check_preimage_claim(&nodes[3], &node_txn);
2296 check_closed_broadcast!(nodes[3], true);
2297 assert_eq!(nodes[2].node.list_channels().len(), 0);
2298 assert_eq!(nodes[3].node.list_channels().len(), 1);
2299 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2300 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2302 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2303 // confusing us in the following tests.
2304 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2306 // One pending HTLC to time out:
2307 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2308 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2311 let (close_chan_update_1, close_chan_update_2) = {
2312 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2313 let events = nodes[3].node.get_and_clear_pending_msg_events();
2314 assert_eq!(events.len(), 2);
2315 let close_chan_update_1 = match events[0] {
2316 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2319 _ => panic!("Unexpected event"),
2322 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2323 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2325 _ => panic!("Unexpected event"),
2327 check_added_monitors!(nodes[3], 1);
2329 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2331 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2332 node_txn.retain(|tx| {
2333 if tx.input[0].previous_output.txid == node2_commitment_txid {
2339 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2341 // Claim the payment on nodes[4], giving it knowledge of the preimage
2342 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2344 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2345 let events = nodes[4].node.get_and_clear_pending_msg_events();
2346 assert_eq!(events.len(), 2);
2347 let close_chan_update_2 = match events[0] {
2348 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2351 _ => panic!("Unexpected event"),
2354 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2355 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2357 _ => panic!("Unexpected event"),
2359 check_added_monitors!(nodes[4], 1);
2360 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2362 mine_transaction(&nodes[4], &node_txn[0]);
2363 check_preimage_claim(&nodes[4], &node_txn);
2364 (close_chan_update_1, close_chan_update_2)
2366 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2367 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2368 assert_eq!(nodes[3].node.list_channels().len(), 0);
2369 assert_eq!(nodes[4].node.list_channels().len(), 0);
2371 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2372 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2373 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2377 fn test_justice_tx() {
2378 // Test justice txn built on revoked HTLC-Success tx, against both sides
2379 let mut alice_config = UserConfig::default();
2380 alice_config.channel_handshake_config.announced_channel = true;
2381 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2382 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2383 let mut bob_config = UserConfig::default();
2384 bob_config.channel_handshake_config.announced_channel = true;
2385 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2386 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2387 let user_cfgs = [Some(alice_config), Some(bob_config)];
2388 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2389 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2390 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2393 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2394 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2395 // Create some new channels:
2396 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2398 // A pending HTLC which will be revoked:
2399 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2400 // Get the will-be-revoked local txn from nodes[0]
2401 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2402 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2403 assert_eq!(revoked_local_txn[0].input.len(), 1);
2404 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2405 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2406 assert_eq!(revoked_local_txn[1].input.len(), 1);
2407 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2408 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2409 // Revoke the old state
2410 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2413 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2415 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2416 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2417 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2419 check_spends!(node_txn[0], revoked_local_txn[0]);
2420 node_txn.swap_remove(0);
2421 node_txn.truncate(1);
2423 check_added_monitors!(nodes[1], 1);
2424 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2425 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2427 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2428 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2429 // Verify broadcast of revoked HTLC-timeout
2430 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2431 check_added_monitors!(nodes[0], 1);
2432 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2433 // Broadcast revoked HTLC-timeout on node 1
2434 mine_transaction(&nodes[1], &node_txn[1]);
2435 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2437 get_announce_close_broadcast_events(&nodes, 0, 1);
2439 assert_eq!(nodes[0].node.list_channels().len(), 0);
2440 assert_eq!(nodes[1].node.list_channels().len(), 0);
2442 // We test justice_tx build by A on B's revoked HTLC-Success tx
2443 // Create some new channels:
2444 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2446 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2450 // A pending HTLC which will be revoked:
2451 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2452 // Get the will-be-revoked local txn from B
2453 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2454 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2455 assert_eq!(revoked_local_txn[0].input.len(), 1);
2456 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2457 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2458 // Revoke the old state
2459 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2461 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2463 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2464 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2465 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2467 check_spends!(node_txn[0], revoked_local_txn[0]);
2468 node_txn.swap_remove(0);
2470 check_added_monitors!(nodes[0], 1);
2471 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2473 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2474 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2475 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2476 check_added_monitors!(nodes[1], 1);
2477 mine_transaction(&nodes[0], &node_txn[1]);
2478 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2479 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2481 get_announce_close_broadcast_events(&nodes, 0, 1);
2482 assert_eq!(nodes[0].node.list_channels().len(), 0);
2483 assert_eq!(nodes[1].node.list_channels().len(), 0);
2487 fn revoked_output_claim() {
2488 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2489 // transaction is broadcast by its counterparty
2490 let chanmon_cfgs = create_chanmon_cfgs(2);
2491 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2492 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2493 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2494 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2495 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2496 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2497 assert_eq!(revoked_local_txn.len(), 1);
2498 // Only output is the full channel value back to nodes[0]:
2499 assert_eq!(revoked_local_txn[0].output.len(), 1);
2500 // Send a payment through, updating everyone's latest commitment txn
2501 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2503 // Inform nodes[1] that nodes[0] broadcast a stale tx
2504 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2505 check_added_monitors!(nodes[1], 1);
2506 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2507 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2508 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2510 check_spends!(node_txn[0], revoked_local_txn[0]);
2511 check_spends!(node_txn[1], chan_1.3);
2513 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2514 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2515 get_announce_close_broadcast_events(&nodes, 0, 1);
2516 check_added_monitors!(nodes[0], 1);
2517 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2521 fn claim_htlc_outputs_shared_tx() {
2522 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2523 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2524 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2529 // Create some new channel:
2530 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2532 // Rebalance the network to generate htlc in the two directions
2533 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2534 // 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
2535 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2536 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2538 // Get the will-be-revoked local txn from node[0]
2539 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2540 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2541 assert_eq!(revoked_local_txn[0].input.len(), 1);
2542 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2543 assert_eq!(revoked_local_txn[1].input.len(), 1);
2544 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2545 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2546 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2548 //Revoke the old state
2549 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2552 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2553 check_added_monitors!(nodes[0], 1);
2554 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2555 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2556 check_added_monitors!(nodes[1], 1);
2557 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2558 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2559 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2561 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2562 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2564 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2565 check_spends!(node_txn[0], revoked_local_txn[0]);
2567 let mut witness_lens = BTreeSet::new();
2568 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2569 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2570 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2571 assert_eq!(witness_lens.len(), 3);
2572 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2573 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2574 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2576 // Next nodes[1] broadcasts its current local tx state:
2577 assert_eq!(node_txn[1].input.len(), 1);
2578 check_spends!(node_txn[1], chan_1.3);
2580 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2581 // ANTI_REORG_DELAY confirmations.
2582 mine_transaction(&nodes[1], &node_txn[0]);
2583 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2584 expect_payment_failed!(nodes[1], payment_hash_2, true);
2586 get_announce_close_broadcast_events(&nodes, 0, 1);
2587 assert_eq!(nodes[0].node.list_channels().len(), 0);
2588 assert_eq!(nodes[1].node.list_channels().len(), 0);
2592 fn claim_htlc_outputs_single_tx() {
2593 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2594 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2595 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2598 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2600 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2602 // Rebalance the network to generate htlc in the two directions
2603 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2604 // 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
2605 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2606 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2607 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2609 // Get the will-be-revoked local txn from node[0]
2610 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2612 //Revoke the old state
2613 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2616 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2617 check_added_monitors!(nodes[0], 1);
2618 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2619 check_added_monitors!(nodes[1], 1);
2620 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2621 let mut events = nodes[0].node.get_and_clear_pending_events();
2622 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2624 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2625 _ => panic!("Unexpected event"),
2628 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2629 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2631 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2632 assert!(node_txn.len() == 9 || node_txn.len() == 10);
2634 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2635 assert_eq!(node_txn[0].input.len(), 1);
2636 check_spends!(node_txn[0], chan_1.3);
2637 assert_eq!(node_txn[1].input.len(), 1);
2638 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2639 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2640 check_spends!(node_txn[1], node_txn[0]);
2642 // Justice transactions are indices 1-2-4
2643 assert_eq!(node_txn[2].input.len(), 1);
2644 assert_eq!(node_txn[3].input.len(), 1);
2645 assert_eq!(node_txn[4].input.len(), 1);
2647 check_spends!(node_txn[2], revoked_local_txn[0]);
2648 check_spends!(node_txn[3], revoked_local_txn[0]);
2649 check_spends!(node_txn[4], revoked_local_txn[0]);
2651 let mut witness_lens = BTreeSet::new();
2652 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2653 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2654 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2655 assert_eq!(witness_lens.len(), 3);
2656 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2657 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2658 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2660 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2661 // ANTI_REORG_DELAY confirmations.
2662 mine_transaction(&nodes[1], &node_txn[2]);
2663 mine_transaction(&nodes[1], &node_txn[3]);
2664 mine_transaction(&nodes[1], &node_txn[4]);
2665 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2666 expect_payment_failed!(nodes[1], payment_hash_2, true);
2668 get_announce_close_broadcast_events(&nodes, 0, 1);
2669 assert_eq!(nodes[0].node.list_channels().len(), 0);
2670 assert_eq!(nodes[1].node.list_channels().len(), 0);
2674 fn test_htlc_on_chain_success() {
2675 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2676 // the preimage backward accordingly. So here we test that ChannelManager is
2677 // broadcasting the right event to other nodes in payment path.
2678 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2679 // A --------------------> B ----------------------> C (preimage)
2680 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2681 // commitment transaction was broadcast.
2682 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2684 // B should be able to claim via preimage if A then broadcasts its local tx.
2685 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2686 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2687 // PaymentSent event).
2689 let chanmon_cfgs = create_chanmon_cfgs(3);
2690 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2691 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2692 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2694 // Create some initial channels
2695 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2696 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2698 // Ensure all nodes are at the same height
2699 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2700 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2701 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2702 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2704 // Rebalance the network a bit by relaying one payment through all the channels...
2705 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2706 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2708 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2709 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2711 // Broadcast legit commitment tx from C on B's chain
2712 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2713 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2714 assert_eq!(commitment_tx.len(), 1);
2715 check_spends!(commitment_tx[0], chan_2.3);
2716 nodes[2].node.claim_funds(our_payment_preimage);
2717 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2718 nodes[2].node.claim_funds(our_payment_preimage_2);
2719 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2720 check_added_monitors!(nodes[2], 2);
2721 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2722 assert!(updates.update_add_htlcs.is_empty());
2723 assert!(updates.update_fail_htlcs.is_empty());
2724 assert!(updates.update_fail_malformed_htlcs.is_empty());
2725 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2727 mine_transaction(&nodes[2], &commitment_tx[0]);
2728 check_closed_broadcast!(nodes[2], true);
2729 check_added_monitors!(nodes[2], 1);
2730 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2731 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)
2732 assert_eq!(node_txn.len(), 5);
2733 assert_eq!(node_txn[0], node_txn[3]);
2734 assert_eq!(node_txn[1], node_txn[4]);
2735 assert_eq!(node_txn[2], commitment_tx[0]);
2736 check_spends!(node_txn[0], commitment_tx[0]);
2737 check_spends!(node_txn[1], commitment_tx[0]);
2738 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2739 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2740 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2741 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2742 assert_eq!(node_txn[0].lock_time, 0);
2743 assert_eq!(node_txn[1].lock_time, 0);
2745 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2746 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2747 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2748 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2750 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2751 assert_eq!(added_monitors.len(), 1);
2752 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2753 added_monitors.clear();
2755 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2756 assert_eq!(forwarded_events.len(), 3);
2757 match forwarded_events[0] {
2758 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2759 _ => panic!("Unexpected event"),
2761 let chan_id = Some(chan_1.2);
2762 match forwarded_events[1] {
2763 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2764 assert_eq!(fee_earned_msat, Some(1000));
2765 assert_eq!(prev_channel_id, chan_id);
2766 assert_eq!(claim_from_onchain_tx, true);
2767 assert_eq!(next_channel_id, Some(chan_2.2));
2771 match forwarded_events[2] {
2772 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2773 assert_eq!(fee_earned_msat, Some(1000));
2774 assert_eq!(prev_channel_id, chan_id);
2775 assert_eq!(claim_from_onchain_tx, true);
2776 assert_eq!(next_channel_id, Some(chan_2.2));
2780 let events = nodes[1].node.get_and_clear_pending_msg_events();
2782 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2783 assert_eq!(added_monitors.len(), 2);
2784 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2785 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2786 added_monitors.clear();
2788 assert_eq!(events.len(), 3);
2790 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2791 _ => panic!("Unexpected event"),
2794 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2795 _ => panic!("Unexpected event"),
2799 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, .. } } => {
2800 assert!(update_add_htlcs.is_empty());
2801 assert!(update_fail_htlcs.is_empty());
2802 assert_eq!(update_fulfill_htlcs.len(), 1);
2803 assert!(update_fail_malformed_htlcs.is_empty());
2804 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2806 _ => panic!("Unexpected event"),
2808 macro_rules! check_tx_local_broadcast {
2809 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2810 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2811 assert_eq!(node_txn.len(), 3);
2812 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2813 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2814 check_spends!(node_txn[1], $commitment_tx);
2815 check_spends!(node_txn[2], $commitment_tx);
2816 assert_ne!(node_txn[1].lock_time, 0);
2817 assert_ne!(node_txn[2].lock_time, 0);
2819 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2820 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2821 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2822 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2824 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2825 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2826 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2827 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2829 check_spends!(node_txn[0], $chan_tx);
2830 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2834 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2835 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2836 // timeout-claim of the output that nodes[2] just claimed via success.
2837 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2839 // Broadcast legit commitment tx from A on B's chain
2840 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2841 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2842 check_spends!(node_a_commitment_tx[0], chan_1.3);
2843 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2844 check_closed_broadcast!(nodes[1], true);
2845 check_added_monitors!(nodes[1], 1);
2846 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2847 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2848 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2849 let commitment_spend =
2850 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2851 check_spends!(node_txn[1], commitment_tx[0]);
2852 check_spends!(node_txn[2], commitment_tx[0]);
2853 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2856 check_spends!(node_txn[0], commitment_tx[0]);
2857 check_spends!(node_txn[1], commitment_tx[0]);
2858 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2862 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2863 assert_eq!(commitment_spend.input.len(), 2);
2864 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2865 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2866 assert_eq!(commitment_spend.lock_time, 0);
2867 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2868 check_spends!(node_txn[3], chan_1.3);
2869 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2870 check_spends!(node_txn[4], node_txn[3]);
2871 check_spends!(node_txn[5], node_txn[3]);
2872 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2873 // we already checked the same situation with A.
2875 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2876 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2877 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2878 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2879 check_closed_broadcast!(nodes[0], true);
2880 check_added_monitors!(nodes[0], 1);
2881 let events = nodes[0].node.get_and_clear_pending_events();
2882 assert_eq!(events.len(), 5);
2883 let mut first_claimed = false;
2884 for event in events {
2886 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2887 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2888 assert!(!first_claimed);
2889 first_claimed = true;
2891 assert_eq!(payment_preimage, our_payment_preimage_2);
2892 assert_eq!(payment_hash, payment_hash_2);
2895 Event::PaymentPathSuccessful { .. } => {},
2896 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2897 _ => panic!("Unexpected event"),
2900 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2903 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2904 // Test that in case of a unilateral close onchain, we detect the state of output and
2905 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2906 // broadcasting the right event to other nodes in payment path.
2907 // A ------------------> B ----------------------> C (timeout)
2908 // B's commitment tx C's commitment tx
2910 // B's HTLC timeout tx B's timeout tx
2912 let chanmon_cfgs = create_chanmon_cfgs(3);
2913 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2914 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2915 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2916 *nodes[0].connect_style.borrow_mut() = connect_style;
2917 *nodes[1].connect_style.borrow_mut() = connect_style;
2918 *nodes[2].connect_style.borrow_mut() = connect_style;
2920 // Create some intial channels
2921 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2922 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2924 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2925 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2926 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2928 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2930 // Broadcast legit commitment tx from C on B's chain
2931 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2932 check_spends!(commitment_tx[0], chan_2.3);
2933 nodes[2].node.fail_htlc_backwards(&payment_hash);
2934 check_added_monitors!(nodes[2], 0);
2935 expect_pending_htlcs_forwardable!(nodes[2]);
2936 check_added_monitors!(nodes[2], 1);
2938 let events = nodes[2].node.get_and_clear_pending_msg_events();
2939 assert_eq!(events.len(), 1);
2941 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, .. } } => {
2942 assert!(update_add_htlcs.is_empty());
2943 assert!(!update_fail_htlcs.is_empty());
2944 assert!(update_fulfill_htlcs.is_empty());
2945 assert!(update_fail_malformed_htlcs.is_empty());
2946 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2948 _ => panic!("Unexpected event"),
2950 mine_transaction(&nodes[2], &commitment_tx[0]);
2951 check_closed_broadcast!(nodes[2], true);
2952 check_added_monitors!(nodes[2], 1);
2953 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2954 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2955 assert_eq!(node_txn.len(), 1);
2956 check_spends!(node_txn[0], chan_2.3);
2957 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2959 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2960 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2961 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2962 mine_transaction(&nodes[1], &commitment_tx[0]);
2963 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2966 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2967 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2968 assert_eq!(node_txn[0], node_txn[3]);
2969 assert_eq!(node_txn[1], node_txn[4]);
2971 check_spends!(node_txn[2], commitment_tx[0]);
2972 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2974 check_spends!(node_txn[0], chan_2.3);
2975 check_spends!(node_txn[1], node_txn[0]);
2976 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2977 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2979 timeout_tx = node_txn[2].clone();
2983 mine_transaction(&nodes[1], &timeout_tx);
2984 check_added_monitors!(nodes[1], 1);
2985 check_closed_broadcast!(nodes[1], true);
2987 // B will rebroadcast a fee-bumped timeout transaction here.
2988 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2989 assert_eq!(node_txn.len(), 1);
2990 check_spends!(node_txn[0], commitment_tx[0]);
2993 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2995 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2996 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2997 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2998 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2999 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3000 if node_txn.len() == 1 {
3001 check_spends!(node_txn[0], chan_2.3);
3003 assert_eq!(node_txn.len(), 0);
3007 expect_pending_htlcs_forwardable!(nodes[1]);
3008 check_added_monitors!(nodes[1], 1);
3009 let events = nodes[1].node.get_and_clear_pending_msg_events();
3010 assert_eq!(events.len(), 1);
3012 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, .. } } => {
3013 assert!(update_add_htlcs.is_empty());
3014 assert!(!update_fail_htlcs.is_empty());
3015 assert!(update_fulfill_htlcs.is_empty());
3016 assert!(update_fail_malformed_htlcs.is_empty());
3017 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3019 _ => panic!("Unexpected event"),
3022 // Broadcast legit commitment tx from B on A's chain
3023 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3024 check_spends!(commitment_tx[0], chan_1.3);
3026 mine_transaction(&nodes[0], &commitment_tx[0]);
3027 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3029 check_closed_broadcast!(nodes[0], true);
3030 check_added_monitors!(nodes[0], 1);
3031 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3032 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3033 assert_eq!(node_txn.len(), 2);
3034 check_spends!(node_txn[0], chan_1.3);
3035 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3036 check_spends!(node_txn[1], commitment_tx[0]);
3037 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3041 fn test_htlc_on_chain_timeout() {
3042 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3043 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3044 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3048 fn test_simple_commitment_revoked_fail_backward() {
3049 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3050 // and fail backward accordingly.
3052 let chanmon_cfgs = create_chanmon_cfgs(3);
3053 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3054 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3055 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3057 // Create some initial channels
3058 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3059 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3061 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3062 // Get the will-be-revoked local txn from nodes[2]
3063 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3064 // Revoke the old state
3065 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3067 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3069 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3070 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3071 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3072 check_added_monitors!(nodes[1], 1);
3073 check_closed_broadcast!(nodes[1], true);
3075 expect_pending_htlcs_forwardable!(nodes[1]);
3076 check_added_monitors!(nodes[1], 1);
3077 let events = nodes[1].node.get_and_clear_pending_msg_events();
3078 assert_eq!(events.len(), 1);
3080 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, .. } } => {
3081 assert!(update_add_htlcs.is_empty());
3082 assert_eq!(update_fail_htlcs.len(), 1);
3083 assert!(update_fulfill_htlcs.is_empty());
3084 assert!(update_fail_malformed_htlcs.is_empty());
3085 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3087 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3088 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3089 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3091 _ => panic!("Unexpected event"),
3095 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3096 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3097 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3098 // commitment transaction anymore.
3099 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3100 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3101 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3102 // technically disallowed and we should probably handle it reasonably.
3103 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3104 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3106 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3107 // commitment_signed (implying it will be in the latest remote commitment transaction).
3108 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3109 // and once they revoke the previous commitment transaction (allowing us to send a new
3110 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3111 let chanmon_cfgs = create_chanmon_cfgs(3);
3112 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3113 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3114 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3116 // Create some initial channels
3117 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3118 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3120 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 });
3121 // Get the will-be-revoked local txn from nodes[2]
3122 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3123 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3124 // Revoke the old state
3125 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3127 let value = if use_dust {
3128 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3129 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3130 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3133 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3134 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3135 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3137 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3138 expect_pending_htlcs_forwardable!(nodes[2]);
3139 check_added_monitors!(nodes[2], 1);
3140 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3141 assert!(updates.update_add_htlcs.is_empty());
3142 assert!(updates.update_fulfill_htlcs.is_empty());
3143 assert!(updates.update_fail_malformed_htlcs.is_empty());
3144 assert_eq!(updates.update_fail_htlcs.len(), 1);
3145 assert!(updates.update_fee.is_none());
3146 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3147 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3148 // Drop the last RAA from 3 -> 2
3150 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3151 expect_pending_htlcs_forwardable!(nodes[2]);
3152 check_added_monitors!(nodes[2], 1);
3153 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3154 assert!(updates.update_add_htlcs.is_empty());
3155 assert!(updates.update_fulfill_htlcs.is_empty());
3156 assert!(updates.update_fail_malformed_htlcs.is_empty());
3157 assert_eq!(updates.update_fail_htlcs.len(), 1);
3158 assert!(updates.update_fee.is_none());
3159 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3160 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3161 check_added_monitors!(nodes[1], 1);
3162 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3163 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3164 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3165 check_added_monitors!(nodes[2], 1);
3167 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3168 expect_pending_htlcs_forwardable!(nodes[2]);
3169 check_added_monitors!(nodes[2], 1);
3170 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3171 assert!(updates.update_add_htlcs.is_empty());
3172 assert!(updates.update_fulfill_htlcs.is_empty());
3173 assert!(updates.update_fail_malformed_htlcs.is_empty());
3174 assert_eq!(updates.update_fail_htlcs.len(), 1);
3175 assert!(updates.update_fee.is_none());
3176 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3177 // At this point first_payment_hash has dropped out of the latest two commitment
3178 // transactions that nodes[1] is tracking...
3179 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3180 check_added_monitors!(nodes[1], 1);
3181 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3182 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3183 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3184 check_added_monitors!(nodes[2], 1);
3186 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3187 // on nodes[2]'s RAA.
3188 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3189 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3190 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3191 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3192 check_added_monitors!(nodes[1], 0);
3195 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3196 // One monitor for the new revocation preimage, no second on as we won't generate a new
3197 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3198 check_added_monitors!(nodes[1], 1);
3199 let events = nodes[1].node.get_and_clear_pending_events();
3200 assert_eq!(events.len(), 1);
3202 Event::PendingHTLCsForwardable { .. } => { },
3203 _ => panic!("Unexpected event"),
3205 // Deliberately don't process the pending fail-back so they all fail back at once after
3206 // block connection just like the !deliver_bs_raa case
3209 let mut failed_htlcs = HashSet::new();
3210 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3212 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3213 check_added_monitors!(nodes[1], 1);
3214 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3215 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3217 let events = nodes[1].node.get_and_clear_pending_events();
3218 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3220 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3221 _ => panic!("Unexepected event"),
3224 Event::PaymentPathFailed { ref payment_hash, .. } => {
3225 assert_eq!(*payment_hash, fourth_payment_hash);
3227 _ => panic!("Unexpected event"),
3229 if !deliver_bs_raa {
3231 Event::PaymentFailed { ref payment_hash, .. } => {
3232 assert_eq!(*payment_hash, fourth_payment_hash);
3234 _ => panic!("Unexpected event"),
3237 Event::PendingHTLCsForwardable { .. } => { },
3238 _ => panic!("Unexpected event"),
3241 nodes[1].node.process_pending_htlc_forwards();
3242 check_added_monitors!(nodes[1], 1);
3244 let events = nodes[1].node.get_and_clear_pending_msg_events();
3245 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3246 match events[if deliver_bs_raa { 1 } else { 0 }] {
3247 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3248 _ => panic!("Unexpected event"),
3250 match events[if deliver_bs_raa { 2 } else { 1 }] {
3251 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3252 assert_eq!(channel_id, chan_2.2);
3253 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3255 _ => panic!("Unexpected event"),
3259 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, .. } } => {
3260 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3261 assert_eq!(update_add_htlcs.len(), 1);
3262 assert!(update_fulfill_htlcs.is_empty());
3263 assert!(update_fail_htlcs.is_empty());
3264 assert!(update_fail_malformed_htlcs.is_empty());
3266 _ => panic!("Unexpected event"),
3269 match events[if deliver_bs_raa { 3 } else { 2 }] {
3270 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, .. } } => {
3271 assert!(update_add_htlcs.is_empty());
3272 assert_eq!(update_fail_htlcs.len(), 3);
3273 assert!(update_fulfill_htlcs.is_empty());
3274 assert!(update_fail_malformed_htlcs.is_empty());
3275 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3277 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3278 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3279 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3281 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3283 let events = nodes[0].node.get_and_clear_pending_events();
3284 assert_eq!(events.len(), 3);
3286 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3287 assert!(failed_htlcs.insert(payment_hash.0));
3288 // If we delivered B's RAA we got an unknown preimage error, not something
3289 // that we should update our routing table for.
3290 if !deliver_bs_raa {
3291 assert!(network_update.is_some());
3294 _ => panic!("Unexpected event"),
3297 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3298 assert!(failed_htlcs.insert(payment_hash.0));
3299 assert!(network_update.is_some());
3301 _ => panic!("Unexpected event"),
3304 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3305 assert!(failed_htlcs.insert(payment_hash.0));
3306 assert!(network_update.is_some());
3308 _ => panic!("Unexpected event"),
3311 _ => panic!("Unexpected event"),
3314 assert!(failed_htlcs.contains(&first_payment_hash.0));
3315 assert!(failed_htlcs.contains(&second_payment_hash.0));
3316 assert!(failed_htlcs.contains(&third_payment_hash.0));
3320 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3321 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3322 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3323 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3324 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3328 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3329 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3330 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3331 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3332 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3336 fn fail_backward_pending_htlc_upon_channel_failure() {
3337 let chanmon_cfgs = create_chanmon_cfgs(2);
3338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3341 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3343 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3345 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3346 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3347 check_added_monitors!(nodes[0], 1);
3349 let payment_event = {
3350 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3351 assert_eq!(events.len(), 1);
3352 SendEvent::from_event(events.remove(0))
3354 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3355 assert_eq!(payment_event.msgs.len(), 1);
3358 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3359 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3361 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3362 check_added_monitors!(nodes[0], 0);
3364 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3367 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3369 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3371 let secp_ctx = Secp256k1::new();
3372 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3373 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3374 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3375 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3376 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3378 // Send a 0-msat update_add_htlc to fail the channel.
3379 let update_add_htlc = msgs::UpdateAddHTLC {
3385 onion_routing_packet,
3387 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3389 let events = nodes[0].node.get_and_clear_pending_events();
3390 assert_eq!(events.len(), 2);
3391 // Check that Alice fails backward the pending HTLC from the second payment.
3393 Event::PaymentPathFailed { payment_hash, .. } => {
3394 assert_eq!(payment_hash, failed_payment_hash);
3396 _ => panic!("Unexpected event"),
3399 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3400 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3402 _ => panic!("Unexpected event {:?}", events[1]),
3404 check_closed_broadcast!(nodes[0], true);
3405 check_added_monitors!(nodes[0], 1);
3409 fn test_htlc_ignore_latest_remote_commitment() {
3410 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3411 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3412 let chanmon_cfgs = create_chanmon_cfgs(2);
3413 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3414 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3415 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3416 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3418 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3419 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3420 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3421 check_closed_broadcast!(nodes[0], true);
3422 check_added_monitors!(nodes[0], 1);
3423 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3425 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3426 assert_eq!(node_txn.len(), 3);
3427 assert_eq!(node_txn[0], node_txn[1]);
3429 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3430 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3431 check_closed_broadcast!(nodes[1], true);
3432 check_added_monitors!(nodes[1], 1);
3433 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3435 // Duplicate the connect_block call since this may happen due to other listeners
3436 // registering new transactions
3437 header.prev_blockhash = header.block_hash();
3438 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3442 fn test_force_close_fail_back() {
3443 // Check which HTLCs are failed-backwards on channel force-closure
3444 let chanmon_cfgs = create_chanmon_cfgs(3);
3445 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3446 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3447 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3448 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3449 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3451 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3453 let mut payment_event = {
3454 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3455 check_added_monitors!(nodes[0], 1);
3457 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3458 assert_eq!(events.len(), 1);
3459 SendEvent::from_event(events.remove(0))
3462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3463 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3465 expect_pending_htlcs_forwardable!(nodes[1]);
3467 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3468 assert_eq!(events_2.len(), 1);
3469 payment_event = SendEvent::from_event(events_2.remove(0));
3470 assert_eq!(payment_event.msgs.len(), 1);
3472 check_added_monitors!(nodes[1], 1);
3473 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3474 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3475 check_added_monitors!(nodes[2], 1);
3476 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3478 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3479 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3480 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3482 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3483 check_closed_broadcast!(nodes[2], true);
3484 check_added_monitors!(nodes[2], 1);
3485 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3487 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3488 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3489 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3490 // back to nodes[1] upon timeout otherwise.
3491 assert_eq!(node_txn.len(), 1);
3495 mine_transaction(&nodes[1], &tx);
3497 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3498 check_closed_broadcast!(nodes[1], true);
3499 check_added_monitors!(nodes[1], 1);
3500 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3502 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3504 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3505 .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);
3507 mine_transaction(&nodes[2], &tx);
3508 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3509 assert_eq!(node_txn.len(), 1);
3510 assert_eq!(node_txn[0].input.len(), 1);
3511 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3512 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3513 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3515 check_spends!(node_txn[0], tx);
3519 fn test_dup_events_on_peer_disconnect() {
3520 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3521 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3522 // as we used to generate the event immediately upon receipt of the payment preimage in the
3523 // update_fulfill_htlc message.
3525 let chanmon_cfgs = create_chanmon_cfgs(2);
3526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3528 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3529 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3531 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3533 nodes[1].node.claim_funds(payment_preimage);
3534 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3535 check_added_monitors!(nodes[1], 1);
3536 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3537 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3538 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3540 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3541 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3543 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3544 expect_payment_path_successful!(nodes[0]);
3548 fn test_peer_disconnected_before_funding_broadcasted() {
3549 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3550 // before the funding transaction has been broadcasted.
3551 let chanmon_cfgs = create_chanmon_cfgs(2);
3552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3554 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3556 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3557 // broadcasted, even though it's created by `nodes[0]`.
3558 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();
3559 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3560 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
3561 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3562 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
3564 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3565 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3567 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3569 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3570 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3572 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3573 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3576 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3579 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3580 // disconnected before the funding transaction was broadcasted.
3581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3584 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3585 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3589 fn test_simple_peer_disconnect() {
3590 // Test that we can reconnect when there are no lost messages
3591 let chanmon_cfgs = create_chanmon_cfgs(3);
3592 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3593 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3594 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3595 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3596 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3598 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3599 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3600 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3602 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3603 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3604 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3605 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3607 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3608 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3609 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3611 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3612 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3613 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3614 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3616 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3617 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3619 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3620 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3622 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3624 let events = nodes[0].node.get_and_clear_pending_events();
3625 assert_eq!(events.len(), 3);
3627 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3628 assert_eq!(payment_preimage, payment_preimage_3);
3629 assert_eq!(payment_hash, payment_hash_3);
3631 _ => panic!("Unexpected event"),
3634 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3635 assert_eq!(payment_hash, payment_hash_5);
3636 assert!(rejected_by_dest);
3638 _ => panic!("Unexpected event"),
3641 Event::PaymentPathSuccessful { .. } => {},
3642 _ => panic!("Unexpected event"),
3646 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3647 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3650 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3651 // Test that we can reconnect when in-flight HTLC updates get dropped
3652 let chanmon_cfgs = create_chanmon_cfgs(2);
3653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3655 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3657 let mut as_channel_ready = None;
3658 if messages_delivered == 0 {
3659 let (channel_ready, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3660 as_channel_ready = Some(channel_ready);
3661 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3662 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3663 // it before the channel_reestablish message.
3665 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3668 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3670 let payment_event = {
3671 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3672 check_added_monitors!(nodes[0], 1);
3674 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3675 assert_eq!(events.len(), 1);
3676 SendEvent::from_event(events.remove(0))
3678 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3680 if messages_delivered < 2 {
3681 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3683 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3684 if messages_delivered >= 3 {
3685 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3686 check_added_monitors!(nodes[1], 1);
3687 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3689 if messages_delivered >= 4 {
3690 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3691 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3692 check_added_monitors!(nodes[0], 1);
3694 if messages_delivered >= 5 {
3695 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3696 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3697 // No commitment_signed so get_event_msg's assert(len == 1) passes
3698 check_added_monitors!(nodes[0], 1);
3700 if messages_delivered >= 6 {
3701 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3702 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3703 check_added_monitors!(nodes[1], 1);
3710 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3711 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3712 if messages_delivered < 3 {
3713 if simulate_broken_lnd {
3714 // lnd has a long-standing bug where they send a channel_ready prior to a
3715 // channel_reestablish if you reconnect prior to channel_ready time.
3717 // Here we simulate that behavior, delivering a channel_ready immediately on
3718 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3719 // in `reconnect_nodes` but we currently don't fail based on that.
3721 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3722 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3724 // Even if the channel_ready messages get exchanged, as long as nothing further was
3725 // received on either side, both sides will need to resend them.
3726 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3727 } else if messages_delivered == 3 {
3728 // nodes[0] still wants its RAA + commitment_signed
3729 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3730 } else if messages_delivered == 4 {
3731 // nodes[0] still wants its commitment_signed
3732 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733 } else if messages_delivered == 5 {
3734 // nodes[1] still wants its final RAA
3735 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3736 } else if messages_delivered == 6 {
3737 // Everything was delivered...
3738 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3741 let events_1 = nodes[1].node.get_and_clear_pending_events();
3742 assert_eq!(events_1.len(), 1);
3744 Event::PendingHTLCsForwardable { .. } => { },
3745 _ => panic!("Unexpected event"),
3748 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3749 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3750 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3752 nodes[1].node.process_pending_htlc_forwards();
3754 let events_2 = nodes[1].node.get_and_clear_pending_events();
3755 assert_eq!(events_2.len(), 1);
3757 Event::PaymentReceived { ref payment_hash, ref purpose, amount_msat } => {
3758 assert_eq!(payment_hash_1, *payment_hash);
3759 assert_eq!(amount_msat, 1_000_000);
3761 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3762 assert!(payment_preimage.is_none());
3763 assert_eq!(payment_secret_1, *payment_secret);
3765 _ => panic!("expected PaymentPurpose::InvoicePayment")
3768 _ => panic!("Unexpected event"),
3771 nodes[1].node.claim_funds(payment_preimage_1);
3772 check_added_monitors!(nodes[1], 1);
3773 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3775 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3776 assert_eq!(events_3.len(), 1);
3777 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3778 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3779 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3780 assert!(updates.update_add_htlcs.is_empty());
3781 assert!(updates.update_fail_htlcs.is_empty());
3782 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3783 assert!(updates.update_fail_malformed_htlcs.is_empty());
3784 assert!(updates.update_fee.is_none());
3785 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3787 _ => panic!("Unexpected event"),
3790 if messages_delivered >= 1 {
3791 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3793 let events_4 = nodes[0].node.get_and_clear_pending_events();
3794 assert_eq!(events_4.len(), 1);
3796 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3797 assert_eq!(payment_preimage_1, *payment_preimage);
3798 assert_eq!(payment_hash_1, *payment_hash);
3800 _ => panic!("Unexpected event"),
3803 if messages_delivered >= 2 {
3804 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3805 check_added_monitors!(nodes[0], 1);
3806 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3808 if messages_delivered >= 3 {
3809 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3810 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3811 check_added_monitors!(nodes[1], 1);
3813 if messages_delivered >= 4 {
3814 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3815 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3816 // No commitment_signed so get_event_msg's assert(len == 1) passes
3817 check_added_monitors!(nodes[1], 1);
3819 if messages_delivered >= 5 {
3820 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3822 check_added_monitors!(nodes[0], 1);
3829 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3830 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3831 if messages_delivered < 2 {
3832 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3833 if messages_delivered < 1 {
3834 expect_payment_sent!(nodes[0], payment_preimage_1);
3836 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3838 } else if messages_delivered == 2 {
3839 // nodes[0] still wants its RAA + commitment_signed
3840 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3841 } else if messages_delivered == 3 {
3842 // nodes[0] still wants its commitment_signed
3843 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3844 } else if messages_delivered == 4 {
3845 // nodes[1] still wants its final RAA
3846 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3847 } else if messages_delivered == 5 {
3848 // Everything was delivered...
3849 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3852 if messages_delivered == 1 || messages_delivered == 2 {
3853 expect_payment_path_successful!(nodes[0]);
3856 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3857 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3858 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3860 if messages_delivered > 2 {
3861 expect_payment_path_successful!(nodes[0]);
3864 // Channel should still work fine...
3865 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3866 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3867 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3871 fn test_drop_messages_peer_disconnect_a() {
3872 do_test_drop_messages_peer_disconnect(0, true);
3873 do_test_drop_messages_peer_disconnect(0, false);
3874 do_test_drop_messages_peer_disconnect(1, false);
3875 do_test_drop_messages_peer_disconnect(2, false);
3879 fn test_drop_messages_peer_disconnect_b() {
3880 do_test_drop_messages_peer_disconnect(3, false);
3881 do_test_drop_messages_peer_disconnect(4, false);
3882 do_test_drop_messages_peer_disconnect(5, false);
3883 do_test_drop_messages_peer_disconnect(6, false);
3887 fn test_funding_peer_disconnect() {
3888 // Test that we can lock in our funding tx while disconnected
3889 let chanmon_cfgs = create_chanmon_cfgs(2);
3890 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3891 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3892 let persister: test_utils::TestPersister;
3893 let new_chain_monitor: test_utils::TestChainMonitor;
3894 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3895 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3896 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3898 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3899 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3901 confirm_transaction(&nodes[0], &tx);
3902 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3903 assert!(events_1.is_empty());
3905 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3907 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3908 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3910 confirm_transaction(&nodes[1], &tx);
3911 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3912 assert!(events_2.is_empty());
3914 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3915 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3916 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3917 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3919 // nodes[0] hasn't yet received a channel_ready, so it only sends that on reconnect.
3920 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3921 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3922 assert_eq!(events_3.len(), 1);
3923 let as_channel_ready = match events_3[0] {
3924 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3925 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3928 _ => panic!("Unexpected event {:?}", events_3[0]),
3931 // nodes[1] received nodes[0]'s channel_ready on the first reconnect above, so it should send
3932 // announcement_signatures as well as channel_update.
3933 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3934 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3935 assert_eq!(events_4.len(), 3);
3937 let bs_channel_ready = match events_4[0] {
3938 MessageSendEvent::SendChannelReady { ref node_id, ref msg } => {
3939 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3940 chan_id = msg.channel_id;
3943 _ => panic!("Unexpected event {:?}", events_4[0]),
3945 let bs_announcement_sigs = match events_4[1] {
3946 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3947 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3950 _ => panic!("Unexpected event {:?}", events_4[1]),
3953 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3954 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3956 _ => panic!("Unexpected event {:?}", events_4[2]),
3959 // Re-deliver nodes[0]'s channel_ready, which nodes[1] can safely ignore. It currently
3960 // generates a duplicative private channel_update
3961 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3962 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3963 assert_eq!(events_5.len(), 1);
3965 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3966 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3968 _ => panic!("Unexpected event {:?}", events_5[0]),
3971 // When we deliver nodes[1]'s channel_ready, however, nodes[0] will generate its
3972 // announcement_signatures.
3973 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &bs_channel_ready);
3974 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3975 assert_eq!(events_6.len(), 1);
3976 let as_announcement_sigs = match events_6[0] {
3977 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3978 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3981 _ => panic!("Unexpected event {:?}", events_6[0]),
3984 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3985 // broadcast the channel announcement globally, as well as re-send its (now-public)
3987 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3988 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3989 assert_eq!(events_7.len(), 1);
3990 let (chan_announcement, as_update) = match events_7[0] {
3991 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3992 (msg.clone(), update_msg.clone())
3994 _ => panic!("Unexpected event {:?}", events_7[0]),
3997 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3998 // same channel_announcement.
3999 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
4000 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
4001 assert_eq!(events_8.len(), 1);
4002 let bs_update = match events_8[0] {
4003 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
4004 assert_eq!(*msg, chan_announcement);
4007 _ => panic!("Unexpected event {:?}", events_8[0]),
4010 // Provide the channel announcement and public updates to the network graph
4011 nodes[0].gossip_sync.handle_channel_announcement(&chan_announcement).unwrap();
4012 nodes[0].gossip_sync.handle_channel_update(&bs_update).unwrap();
4013 nodes[0].gossip_sync.handle_channel_update(&as_update).unwrap();
4015 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4016 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4017 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
4019 // Check that after deserialization and reconnection we can still generate an identical
4020 // channel_announcement from the cached signatures.
4021 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4023 let nodes_0_serialized = nodes[0].node.encode();
4024 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4025 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4027 persister = test_utils::TestPersister::new();
4028 let keys_manager = &chanmon_cfgs[0].keys_manager;
4029 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);
4030 nodes[0].chain_monitor = &new_chain_monitor;
4031 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4032 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4033 &mut chan_0_monitor_read, keys_manager).unwrap();
4034 assert!(chan_0_monitor_read.is_empty());
4036 let mut nodes_0_read = &nodes_0_serialized[..];
4037 let (_, nodes_0_deserialized_tmp) = {
4038 let mut channel_monitors = HashMap::new();
4039 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4040 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4041 default_config: UserConfig::default(),
4043 fee_estimator: node_cfgs[0].fee_estimator,
4044 chain_monitor: nodes[0].chain_monitor,
4045 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4046 logger: nodes[0].logger,
4050 nodes_0_deserialized = nodes_0_deserialized_tmp;
4051 assert!(nodes_0_read.is_empty());
4053 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4054 nodes[0].node = &nodes_0_deserialized;
4055 check_added_monitors!(nodes[0], 1);
4057 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4059 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
4060 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
4061 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
4062 let mut found_announcement = false;
4063 for event in msgs.iter() {
4065 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
4066 if *msg == chan_announcement { found_announcement = true; }
4068 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
4069 _ => panic!("Unexpected event"),
4072 assert!(found_announcement);
4076 fn test_channel_ready_without_best_block_updated() {
4077 // Previously, if we were offline when a funding transaction was locked in, and then we came
4078 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4079 // generate a channel_ready until a later best_block_updated. This tests that we generate the
4080 // channel_ready immediately instead.
4081 let chanmon_cfgs = create_chanmon_cfgs(2);
4082 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4083 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4084 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4085 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4087 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
4089 let conf_height = nodes[0].best_block_info().1 + 1;
4090 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4091 let block_txn = [funding_tx];
4092 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4093 let conf_block_header = nodes[0].get_block_header(conf_height);
4094 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4096 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4097 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4098 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4102 fn test_drop_messages_peer_disconnect_dual_htlc() {
4103 // Test that we can handle reconnecting when both sides of a channel have pending
4104 // commitment_updates when we disconnect.
4105 let chanmon_cfgs = create_chanmon_cfgs(2);
4106 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4107 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4108 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4109 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4111 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4113 // Now try to send a second payment which will fail to send
4114 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4115 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4116 check_added_monitors!(nodes[0], 1);
4118 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4119 assert_eq!(events_1.len(), 1);
4121 MessageSendEvent::UpdateHTLCs { .. } => {},
4122 _ => panic!("Unexpected event"),
4125 nodes[1].node.claim_funds(payment_preimage_1);
4126 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4127 check_added_monitors!(nodes[1], 1);
4129 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4130 assert_eq!(events_2.len(), 1);
4132 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 } } => {
4133 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4134 assert!(update_add_htlcs.is_empty());
4135 assert_eq!(update_fulfill_htlcs.len(), 1);
4136 assert!(update_fail_htlcs.is_empty());
4137 assert!(update_fail_malformed_htlcs.is_empty());
4138 assert!(update_fee.is_none());
4140 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4141 let events_3 = nodes[0].node.get_and_clear_pending_events();
4142 assert_eq!(events_3.len(), 1);
4144 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4145 assert_eq!(*payment_preimage, payment_preimage_1);
4146 assert_eq!(*payment_hash, payment_hash_1);
4148 _ => panic!("Unexpected event"),
4151 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4152 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4153 // No commitment_signed so get_event_msg's assert(len == 1) passes
4154 check_added_monitors!(nodes[0], 1);
4156 _ => panic!("Unexpected event"),
4159 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4160 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4162 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4163 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4164 assert_eq!(reestablish_1.len(), 1);
4165 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4166 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4167 assert_eq!(reestablish_2.len(), 1);
4169 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4170 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4171 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4172 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4174 assert!(as_resp.0.is_none());
4175 assert!(bs_resp.0.is_none());
4177 assert!(bs_resp.1.is_none());
4178 assert!(bs_resp.2.is_none());
4180 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4182 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4183 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4184 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4185 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4186 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4187 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4188 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4189 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4190 // No commitment_signed so get_event_msg's assert(len == 1) passes
4191 check_added_monitors!(nodes[1], 1);
4193 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4194 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4195 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4196 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4197 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4198 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4199 assert!(bs_second_commitment_signed.update_fee.is_none());
4200 check_added_monitors!(nodes[1], 1);
4202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4203 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4204 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4205 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4206 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4207 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4208 assert!(as_commitment_signed.update_fee.is_none());
4209 check_added_monitors!(nodes[0], 1);
4211 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4212 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4213 // No commitment_signed so get_event_msg's assert(len == 1) passes
4214 check_added_monitors!(nodes[0], 1);
4216 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4217 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4218 // No commitment_signed so get_event_msg's assert(len == 1) passes
4219 check_added_monitors!(nodes[1], 1);
4221 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4222 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4223 check_added_monitors!(nodes[1], 1);
4225 expect_pending_htlcs_forwardable!(nodes[1]);
4227 let events_5 = nodes[1].node.get_and_clear_pending_events();
4228 assert_eq!(events_5.len(), 1);
4230 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4231 assert_eq!(payment_hash_2, *payment_hash);
4233 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4234 assert!(payment_preimage.is_none());
4235 assert_eq!(payment_secret_2, *payment_secret);
4237 _ => panic!("expected PaymentPurpose::InvoicePayment")
4240 _ => panic!("Unexpected event"),
4243 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4244 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4245 check_added_monitors!(nodes[0], 1);
4247 expect_payment_path_successful!(nodes[0]);
4248 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4251 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4252 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4253 // to avoid our counterparty failing the channel.
4254 let chanmon_cfgs = create_chanmon_cfgs(2);
4255 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4256 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4257 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4259 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4261 let our_payment_hash = if send_partial_mpp {
4262 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4263 // Use the utility function send_payment_along_path to send the payment with MPP data which
4264 // indicates there are more HTLCs coming.
4265 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.
4266 let payment_id = PaymentId([42; 32]);
4267 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();
4268 check_added_monitors!(nodes[0], 1);
4269 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4270 assert_eq!(events.len(), 1);
4271 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4272 // hop should *not* yet generate any PaymentReceived event(s).
4273 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4276 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4279 let mut block = Block {
4280 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4283 connect_block(&nodes[0], &block);
4284 connect_block(&nodes[1], &block);
4285 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4286 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4287 block.header.prev_blockhash = block.block_hash();
4288 connect_block(&nodes[0], &block);
4289 connect_block(&nodes[1], &block);
4292 expect_pending_htlcs_forwardable!(nodes[1]);
4294 check_added_monitors!(nodes[1], 1);
4295 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4296 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4297 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4298 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4299 assert!(htlc_timeout_updates.update_fee.is_none());
4301 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4302 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4303 // 100_000 msat as u64, followed by the height at which we failed back above
4304 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4305 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4306 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4310 fn test_htlc_timeout() {
4311 do_test_htlc_timeout(true);
4312 do_test_htlc_timeout(false);
4315 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4316 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4317 let chanmon_cfgs = create_chanmon_cfgs(3);
4318 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4319 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4320 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4321 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4322 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4324 // Make sure all nodes are at the same starting height
4325 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4326 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4327 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4329 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4330 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4332 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4334 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4335 check_added_monitors!(nodes[1], 1);
4337 // Now attempt to route a second payment, which should be placed in the holding cell
4338 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4339 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4340 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4342 check_added_monitors!(nodes[0], 1);
4343 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4344 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4345 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4346 expect_pending_htlcs_forwardable!(nodes[1]);
4348 check_added_monitors!(nodes[1], 0);
4350 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4351 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4352 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4353 connect_blocks(&nodes[1], 1);
4356 expect_pending_htlcs_forwardable!(nodes[1]);
4357 check_added_monitors!(nodes[1], 1);
4358 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4359 assert_eq!(fail_commit.len(), 1);
4360 match fail_commit[0] {
4361 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4362 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4363 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4365 _ => unreachable!(),
4367 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4369 let events = nodes[1].node.get_and_clear_pending_events();
4370 assert_eq!(events.len(), 2);
4371 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4372 assert_eq!(*payment_hash, second_payment_hash);
4373 } else { panic!("Unexpected event"); }
4374 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4375 assert_eq!(*payment_hash, second_payment_hash);
4376 } else { panic!("Unexpected event"); }
4381 fn test_holding_cell_htlc_add_timeouts() {
4382 do_test_holding_cell_htlc_add_timeouts(false);
4383 do_test_holding_cell_htlc_add_timeouts(true);
4387 fn test_no_txn_manager_serialize_deserialize() {
4388 let chanmon_cfgs = create_chanmon_cfgs(2);
4389 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4390 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4391 let logger: test_utils::TestLogger;
4392 let fee_estimator: test_utils::TestFeeEstimator;
4393 let persister: test_utils::TestPersister;
4394 let new_chain_monitor: test_utils::TestChainMonitor;
4395 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4396 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4398 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4400 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4402 let nodes_0_serialized = nodes[0].node.encode();
4403 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4404 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4405 .write(&mut chan_0_monitor_serialized).unwrap();
4407 logger = test_utils::TestLogger::new();
4408 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4409 persister = test_utils::TestPersister::new();
4410 let keys_manager = &chanmon_cfgs[0].keys_manager;
4411 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4412 nodes[0].chain_monitor = &new_chain_monitor;
4413 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4414 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4415 &mut chan_0_monitor_read, keys_manager).unwrap();
4416 assert!(chan_0_monitor_read.is_empty());
4418 let mut nodes_0_read = &nodes_0_serialized[..];
4419 let config = UserConfig::default();
4420 let (_, nodes_0_deserialized_tmp) = {
4421 let mut channel_monitors = HashMap::new();
4422 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4423 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4424 default_config: config,
4426 fee_estimator: &fee_estimator,
4427 chain_monitor: nodes[0].chain_monitor,
4428 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4433 nodes_0_deserialized = nodes_0_deserialized_tmp;
4434 assert!(nodes_0_read.is_empty());
4436 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4437 nodes[0].node = &nodes_0_deserialized;
4438 assert_eq!(nodes[0].node.list_channels().len(), 1);
4439 check_added_monitors!(nodes[0], 1);
4441 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4442 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4443 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4444 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4446 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4447 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4448 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4449 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4451 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4452 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4453 for node in nodes.iter() {
4454 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4455 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4456 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4459 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4463 fn test_manager_serialize_deserialize_events() {
4464 // This test makes sure the events field in ChannelManager survives de/serialization
4465 let chanmon_cfgs = create_chanmon_cfgs(2);
4466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4468 let fee_estimator: test_utils::TestFeeEstimator;
4469 let persister: test_utils::TestPersister;
4470 let logger: test_utils::TestLogger;
4471 let new_chain_monitor: test_utils::TestChainMonitor;
4472 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4473 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4475 // Start creating a channel, but stop right before broadcasting the funding transaction
4476 let channel_value = 100000;
4477 let push_msat = 10001;
4478 let a_flags = InitFeatures::known();
4479 let b_flags = InitFeatures::known();
4480 let node_a = nodes.remove(0);
4481 let node_b = nodes.remove(0);
4482 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4483 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()));
4484 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()));
4486 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, &node_b.node.get_our_node_id(), channel_value, 42);
4488 node_a.node.funding_transaction_generated(&temporary_channel_id, &node_b.node.get_our_node_id(), tx.clone()).unwrap();
4489 check_added_monitors!(node_a, 0);
4491 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()));
4493 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4494 assert_eq!(added_monitors.len(), 1);
4495 assert_eq!(added_monitors[0].0, funding_output);
4496 added_monitors.clear();
4499 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4500 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4502 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4503 assert_eq!(added_monitors.len(), 1);
4504 assert_eq!(added_monitors[0].0, funding_output);
4505 added_monitors.clear();
4507 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4512 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4513 let nodes_0_serialized = nodes[0].node.encode();
4514 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4515 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4517 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4518 logger = test_utils::TestLogger::new();
4519 persister = test_utils::TestPersister::new();
4520 let keys_manager = &chanmon_cfgs[0].keys_manager;
4521 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4522 nodes[0].chain_monitor = &new_chain_monitor;
4523 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4524 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4525 &mut chan_0_monitor_read, keys_manager).unwrap();
4526 assert!(chan_0_monitor_read.is_empty());
4528 let mut nodes_0_read = &nodes_0_serialized[..];
4529 let config = UserConfig::default();
4530 let (_, nodes_0_deserialized_tmp) = {
4531 let mut channel_monitors = HashMap::new();
4532 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4533 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4534 default_config: config,
4536 fee_estimator: &fee_estimator,
4537 chain_monitor: nodes[0].chain_monitor,
4538 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4543 nodes_0_deserialized = nodes_0_deserialized_tmp;
4544 assert!(nodes_0_read.is_empty());
4546 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4548 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4549 nodes[0].node = &nodes_0_deserialized;
4551 // After deserializing, make sure the funding_transaction is still held by the channel manager
4552 let events_4 = nodes[0].node.get_and_clear_pending_events();
4553 assert_eq!(events_4.len(), 0);
4554 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4555 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4557 // Make sure the channel is functioning as though the de/serialization never happened
4558 assert_eq!(nodes[0].node.list_channels().len(), 1);
4559 check_added_monitors!(nodes[0], 1);
4561 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4562 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4563 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4564 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4566 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4567 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4568 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4569 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4571 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4572 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
4573 for node in nodes.iter() {
4574 assert!(node.gossip_sync.handle_channel_announcement(&announcement).unwrap());
4575 node.gossip_sync.handle_channel_update(&as_update).unwrap();
4576 node.gossip_sync.handle_channel_update(&bs_update).unwrap();
4579 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4583 fn test_simple_manager_serialize_deserialize() {
4584 let chanmon_cfgs = create_chanmon_cfgs(2);
4585 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4586 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4587 let logger: test_utils::TestLogger;
4588 let fee_estimator: test_utils::TestFeeEstimator;
4589 let persister: test_utils::TestPersister;
4590 let new_chain_monitor: test_utils::TestChainMonitor;
4591 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4592 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4593 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4595 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4596 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4598 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4600 let nodes_0_serialized = nodes[0].node.encode();
4601 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4602 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4604 logger = test_utils::TestLogger::new();
4605 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4606 persister = test_utils::TestPersister::new();
4607 let keys_manager = &chanmon_cfgs[0].keys_manager;
4608 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4609 nodes[0].chain_monitor = &new_chain_monitor;
4610 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4611 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4612 &mut chan_0_monitor_read, keys_manager).unwrap();
4613 assert!(chan_0_monitor_read.is_empty());
4615 let mut nodes_0_read = &nodes_0_serialized[..];
4616 let (_, nodes_0_deserialized_tmp) = {
4617 let mut channel_monitors = HashMap::new();
4618 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4619 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4620 default_config: UserConfig::default(),
4622 fee_estimator: &fee_estimator,
4623 chain_monitor: nodes[0].chain_monitor,
4624 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4629 nodes_0_deserialized = nodes_0_deserialized_tmp;
4630 assert!(nodes_0_read.is_empty());
4632 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4633 nodes[0].node = &nodes_0_deserialized;
4634 check_added_monitors!(nodes[0], 1);
4636 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4638 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4639 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4643 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4644 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4645 let chanmon_cfgs = create_chanmon_cfgs(4);
4646 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4647 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4648 let logger: test_utils::TestLogger;
4649 let fee_estimator: test_utils::TestFeeEstimator;
4650 let persister: test_utils::TestPersister;
4651 let new_chain_monitor: test_utils::TestChainMonitor;
4652 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4653 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4654 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4655 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4656 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4658 let mut node_0_stale_monitors_serialized = Vec::new();
4659 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4660 let mut writer = test_utils::TestVecWriter(Vec::new());
4661 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4662 node_0_stale_monitors_serialized.push(writer.0);
4665 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4667 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4668 let nodes_0_serialized = nodes[0].node.encode();
4670 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4671 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4672 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4673 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4675 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4677 let mut node_0_monitors_serialized = Vec::new();
4678 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4679 let mut writer = test_utils::TestVecWriter(Vec::new());
4680 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4681 node_0_monitors_serialized.push(writer.0);
4684 logger = test_utils::TestLogger::new();
4685 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4686 persister = test_utils::TestPersister::new();
4687 let keys_manager = &chanmon_cfgs[0].keys_manager;
4688 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4689 nodes[0].chain_monitor = &new_chain_monitor;
4692 let mut node_0_stale_monitors = Vec::new();
4693 for serialized in node_0_stale_monitors_serialized.iter() {
4694 let mut read = &serialized[..];
4695 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4696 assert!(read.is_empty());
4697 node_0_stale_monitors.push(monitor);
4700 let mut node_0_monitors = Vec::new();
4701 for serialized in node_0_monitors_serialized.iter() {
4702 let mut read = &serialized[..];
4703 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4704 assert!(read.is_empty());
4705 node_0_monitors.push(monitor);
4708 let mut nodes_0_read = &nodes_0_serialized[..];
4709 if let Err(msgs::DecodeError::InvalidValue) =
4710 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4711 default_config: UserConfig::default(),
4713 fee_estimator: &fee_estimator,
4714 chain_monitor: nodes[0].chain_monitor,
4715 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4717 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4719 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4722 let mut nodes_0_read = &nodes_0_serialized[..];
4723 let (_, nodes_0_deserialized_tmp) =
4724 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4725 default_config: UserConfig::default(),
4727 fee_estimator: &fee_estimator,
4728 chain_monitor: nodes[0].chain_monitor,
4729 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4731 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4733 nodes_0_deserialized = nodes_0_deserialized_tmp;
4734 assert!(nodes_0_read.is_empty());
4736 { // Channel close should result in a commitment tx
4737 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4738 assert_eq!(txn.len(), 1);
4739 check_spends!(txn[0], funding_tx);
4740 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4743 for monitor in node_0_monitors.drain(..) {
4744 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4745 check_added_monitors!(nodes[0], 1);
4747 nodes[0].node = &nodes_0_deserialized;
4748 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4750 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4751 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4752 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4753 //... and we can even still claim the payment!
4754 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4756 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4757 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4758 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4759 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4760 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4761 assert_eq!(msg_events.len(), 1);
4762 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4764 &ErrorAction::SendErrorMessage { ref msg } => {
4765 assert_eq!(msg.channel_id, channel_id);
4767 _ => panic!("Unexpected event!"),
4772 macro_rules! check_spendable_outputs {
4773 ($node: expr, $keysinterface: expr) => {
4775 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4776 let mut txn = Vec::new();
4777 let mut all_outputs = Vec::new();
4778 let secp_ctx = Secp256k1::new();
4779 for event in events.drain(..) {
4781 Event::SpendableOutputs { mut outputs } => {
4782 for outp in outputs.drain(..) {
4783 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4784 all_outputs.push(outp);
4787 _ => panic!("Unexpected event"),
4790 if all_outputs.len() > 1 {
4791 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) {
4801 fn test_claim_sizeable_push_msat() {
4802 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4803 let chanmon_cfgs = create_chanmon_cfgs(2);
4804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4806 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4808 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4809 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4810 check_closed_broadcast!(nodes[1], true);
4811 check_added_monitors!(nodes[1], 1);
4812 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4813 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4814 assert_eq!(node_txn.len(), 1);
4815 check_spends!(node_txn[0], chan.3);
4816 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
4818 mine_transaction(&nodes[1], &node_txn[0]);
4819 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4821 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4822 assert_eq!(spend_txn.len(), 1);
4823 assert_eq!(spend_txn[0].input.len(), 1);
4824 check_spends!(spend_txn[0], node_txn[0]);
4825 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4829 fn test_claim_on_remote_sizeable_push_msat() {
4830 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4831 // to_remote output is encumbered by a P2WPKH
4832 let chanmon_cfgs = create_chanmon_cfgs(2);
4833 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4834 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4835 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4837 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4838 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4839 check_closed_broadcast!(nodes[0], true);
4840 check_added_monitors!(nodes[0], 1);
4841 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4843 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4844 assert_eq!(node_txn.len(), 1);
4845 check_spends!(node_txn[0], chan.3);
4846 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
4848 mine_transaction(&nodes[1], &node_txn[0]);
4849 check_closed_broadcast!(nodes[1], true);
4850 check_added_monitors!(nodes[1], 1);
4851 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4852 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4854 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4855 assert_eq!(spend_txn.len(), 1);
4856 check_spends!(spend_txn[0], node_txn[0]);
4860 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4861 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4862 // to_remote output is encumbered by a P2WPKH
4864 let chanmon_cfgs = create_chanmon_cfgs(2);
4865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4869 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4870 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4871 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4872 assert_eq!(revoked_local_txn[0].input.len(), 1);
4873 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4875 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4876 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4877 check_closed_broadcast!(nodes[1], true);
4878 check_added_monitors!(nodes[1], 1);
4879 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4881 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4882 mine_transaction(&nodes[1], &node_txn[0]);
4883 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4885 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4886 assert_eq!(spend_txn.len(), 3);
4887 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4888 check_spends!(spend_txn[1], node_txn[0]);
4889 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4893 fn test_static_spendable_outputs_preimage_tx() {
4894 let chanmon_cfgs = create_chanmon_cfgs(2);
4895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4899 // Create some initial channels
4900 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4902 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4904 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4905 assert_eq!(commitment_tx[0].input.len(), 1);
4906 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4908 // Settle A's commitment tx on B's chain
4909 nodes[1].node.claim_funds(payment_preimage);
4910 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4911 check_added_monitors!(nodes[1], 1);
4912 mine_transaction(&nodes[1], &commitment_tx[0]);
4913 check_added_monitors!(nodes[1], 1);
4914 let events = nodes[1].node.get_and_clear_pending_msg_events();
4916 MessageSendEvent::UpdateHTLCs { .. } => {},
4917 _ => panic!("Unexpected event"),
4920 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4921 _ => panic!("Unexepected event"),
4924 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4925 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4926 assert_eq!(node_txn.len(), 3);
4927 check_spends!(node_txn[0], commitment_tx[0]);
4928 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4929 check_spends!(node_txn[1], chan_1.3);
4930 check_spends!(node_txn[2], node_txn[1]);
4932 mine_transaction(&nodes[1], &node_txn[0]);
4933 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4934 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4936 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4937 assert_eq!(spend_txn.len(), 1);
4938 check_spends!(spend_txn[0], node_txn[0]);
4942 fn test_static_spendable_outputs_timeout_tx() {
4943 let chanmon_cfgs = create_chanmon_cfgs(2);
4944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4946 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4948 // Create some initial channels
4949 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4951 // Rebalance the network a bit by relaying one payment through all the channels ...
4952 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4954 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4956 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4957 assert_eq!(commitment_tx[0].input.len(), 1);
4958 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4960 // Settle A's commitment tx on B' chain
4961 mine_transaction(&nodes[1], &commitment_tx[0]);
4962 check_added_monitors!(nodes[1], 1);
4963 let events = nodes[1].node.get_and_clear_pending_msg_events();
4965 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4966 _ => panic!("Unexpected event"),
4968 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4970 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4971 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4972 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4973 check_spends!(node_txn[0], chan_1.3.clone());
4974 check_spends!(node_txn[1], commitment_tx[0].clone());
4975 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4977 mine_transaction(&nodes[1], &node_txn[1]);
4978 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4979 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4980 expect_payment_failed!(nodes[1], our_payment_hash, true);
4982 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4983 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4984 check_spends!(spend_txn[0], commitment_tx[0]);
4985 check_spends!(spend_txn[1], node_txn[1]);
4986 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4990 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4991 let chanmon_cfgs = create_chanmon_cfgs(2);
4992 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4993 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4994 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4996 // Create some initial channels
4997 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4999 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5000 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5001 assert_eq!(revoked_local_txn[0].input.len(), 1);
5002 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5004 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5006 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5007 check_closed_broadcast!(nodes[1], true);
5008 check_added_monitors!(nodes[1], 1);
5009 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5011 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5012 assert_eq!(node_txn.len(), 2);
5013 assert_eq!(node_txn[0].input.len(), 2);
5014 check_spends!(node_txn[0], revoked_local_txn[0]);
5016 mine_transaction(&nodes[1], &node_txn[0]);
5017 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5019 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5020 assert_eq!(spend_txn.len(), 1);
5021 check_spends!(spend_txn[0], node_txn[0]);
5025 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5026 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5027 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5030 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5032 // Create some initial channels
5033 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5035 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5036 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5037 assert_eq!(revoked_local_txn[0].input.len(), 1);
5038 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5040 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5042 // A will generate HTLC-Timeout from revoked commitment tx
5043 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5044 check_closed_broadcast!(nodes[0], true);
5045 check_added_monitors!(nodes[0], 1);
5046 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5047 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5049 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5050 assert_eq!(revoked_htlc_txn.len(), 2);
5051 check_spends!(revoked_htlc_txn[0], chan_1.3);
5052 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5053 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5054 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5055 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5057 // B will generate justice tx from A's revoked commitment/HTLC tx
5058 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5059 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5060 check_closed_broadcast!(nodes[1], true);
5061 check_added_monitors!(nodes[1], 1);
5062 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5064 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5065 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5066 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5067 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5068 // transactions next...
5069 assert_eq!(node_txn[0].input.len(), 3);
5070 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5072 assert_eq!(node_txn[1].input.len(), 2);
5073 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5074 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5075 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5077 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5078 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5081 assert_eq!(node_txn[2].input.len(), 1);
5082 check_spends!(node_txn[2], chan_1.3);
5084 mine_transaction(&nodes[1], &node_txn[1]);
5085 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5087 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5088 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5089 assert_eq!(spend_txn.len(), 1);
5090 assert_eq!(spend_txn[0].input.len(), 1);
5091 check_spends!(spend_txn[0], node_txn[1]);
5095 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5096 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5097 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5098 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5099 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5100 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5102 // Create some initial channels
5103 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5105 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5106 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5107 assert_eq!(revoked_local_txn[0].input.len(), 1);
5108 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5110 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5111 assert_eq!(revoked_local_txn[0].output.len(), 2);
5113 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5115 // B will generate HTLC-Success from revoked commitment tx
5116 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5117 check_closed_broadcast!(nodes[1], true);
5118 check_added_monitors!(nodes[1], 1);
5119 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5120 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5122 assert_eq!(revoked_htlc_txn.len(), 2);
5123 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5124 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5125 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5127 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5128 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5129 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5131 // A will generate justice tx from B's revoked commitment/HTLC tx
5132 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5133 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5134 check_closed_broadcast!(nodes[0], true);
5135 check_added_monitors!(nodes[0], 1);
5136 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5138 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5139 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5141 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5142 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5143 // transactions next...
5144 assert_eq!(node_txn[0].input.len(), 2);
5145 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5146 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5147 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5149 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5150 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5153 assert_eq!(node_txn[1].input.len(), 1);
5154 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5156 check_spends!(node_txn[2], chan_1.3);
5158 mine_transaction(&nodes[0], &node_txn[1]);
5159 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5161 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5162 // didn't try to generate any new transactions.
5164 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5165 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5166 assert_eq!(spend_txn.len(), 3);
5167 assert_eq!(spend_txn[0].input.len(), 1);
5168 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5169 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5170 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5171 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5175 fn test_onchain_to_onchain_claim() {
5176 // Test that in case of channel closure, we detect the state of output and claim HTLC
5177 // on downstream peer's remote commitment tx.
5178 // First, have C claim an HTLC against its own latest commitment transaction.
5179 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5181 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5184 let chanmon_cfgs = create_chanmon_cfgs(3);
5185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5187 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5189 // Create some initial channels
5190 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5191 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5193 // Ensure all nodes are at the same height
5194 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5195 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5196 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5197 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5199 // Rebalance the network a bit by relaying one payment through all the channels ...
5200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5201 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5203 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
5204 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5205 check_spends!(commitment_tx[0], chan_2.3);
5206 nodes[2].node.claim_funds(payment_preimage);
5207 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
5208 check_added_monitors!(nodes[2], 1);
5209 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5210 assert!(updates.update_add_htlcs.is_empty());
5211 assert!(updates.update_fail_htlcs.is_empty());
5212 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5213 assert!(updates.update_fail_malformed_htlcs.is_empty());
5215 mine_transaction(&nodes[2], &commitment_tx[0]);
5216 check_closed_broadcast!(nodes[2], true);
5217 check_added_monitors!(nodes[2], 1);
5218 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5220 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5221 assert_eq!(c_txn.len(), 3);
5222 assert_eq!(c_txn[0], c_txn[2]);
5223 assert_eq!(commitment_tx[0], c_txn[1]);
5224 check_spends!(c_txn[1], chan_2.3);
5225 check_spends!(c_txn[2], c_txn[1]);
5226 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5227 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5228 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5229 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5231 // 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
5232 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5233 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5234 check_added_monitors!(nodes[1], 1);
5235 let events = nodes[1].node.get_and_clear_pending_events();
5236 assert_eq!(events.len(), 2);
5238 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5239 _ => panic!("Unexpected event"),
5242 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
5243 assert_eq!(fee_earned_msat, Some(1000));
5244 assert_eq!(prev_channel_id, Some(chan_1.2));
5245 assert_eq!(claim_from_onchain_tx, true);
5246 assert_eq!(next_channel_id, Some(chan_2.2));
5248 _ => panic!("Unexpected event"),
5251 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5252 // ChannelMonitor: claim tx
5253 assert_eq!(b_txn.len(), 1);
5254 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5257 check_added_monitors!(nodes[1], 1);
5258 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5259 assert_eq!(msg_events.len(), 3);
5260 match msg_events[0] {
5261 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5262 _ => panic!("Unexpected event"),
5264 match msg_events[1] {
5265 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5266 _ => panic!("Unexpected event"),
5268 match msg_events[2] {
5269 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, .. } } => {
5270 assert!(update_add_htlcs.is_empty());
5271 assert!(update_fail_htlcs.is_empty());
5272 assert_eq!(update_fulfill_htlcs.len(), 1);
5273 assert!(update_fail_malformed_htlcs.is_empty());
5274 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5276 _ => panic!("Unexpected event"),
5278 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5279 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5280 mine_transaction(&nodes[1], &commitment_tx[0]);
5281 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5282 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5283 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5284 assert_eq!(b_txn.len(), 3);
5285 check_spends!(b_txn[1], chan_1.3);
5286 check_spends!(b_txn[2], b_txn[1]);
5287 check_spends!(b_txn[0], commitment_tx[0]);
5288 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5289 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5290 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5292 check_closed_broadcast!(nodes[1], true);
5293 check_added_monitors!(nodes[1], 1);
5297 fn test_duplicate_payment_hash_one_failure_one_success() {
5298 // Topology : A --> B --> C --> D
5299 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5300 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5301 // we forward one of the payments onwards to D.
5302 let chanmon_cfgs = create_chanmon_cfgs(4);
5303 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5304 // When this test was written, the default base fee floated based on the HTLC count.
5305 // It is now fixed, so we simply set the fee to the expected value here.
5306 let mut config = test_default_channel_config();
5307 config.channel_config.forwarding_fee_base_msat = 196;
5308 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5309 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5310 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5312 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5313 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5314 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5316 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5317 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5318 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5319 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5320 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5322 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
5324 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5325 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5326 // script push size limit so that the below script length checks match
5327 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5328 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5329 .with_features(InvoiceFeatures::known());
5330 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5331 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5333 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5334 assert_eq!(commitment_txn[0].input.len(), 1);
5335 check_spends!(commitment_txn[0], chan_2.3);
5337 mine_transaction(&nodes[1], &commitment_txn[0]);
5338 check_closed_broadcast!(nodes[1], true);
5339 check_added_monitors!(nodes[1], 1);
5340 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5341 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5343 let htlc_timeout_tx;
5344 { // Extract one of the two HTLC-Timeout transaction
5345 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5346 // ChannelMonitor: timeout tx * 2-or-3, ChannelManager: local commitment tx
5347 assert!(node_txn.len() == 4 || node_txn.len() == 3);
5348 check_spends!(node_txn[0], chan_2.3);
5350 check_spends!(node_txn[1], commitment_txn[0]);
5351 assert_eq!(node_txn[1].input.len(), 1);
5353 if node_txn.len() > 3 {
5354 check_spends!(node_txn[2], commitment_txn[0]);
5355 assert_eq!(node_txn[2].input.len(), 1);
5356 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5358 check_spends!(node_txn[3], commitment_txn[0]);
5359 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5361 check_spends!(node_txn[2], commitment_txn[0]);
5362 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5365 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5366 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5367 if node_txn.len() > 3 {
5368 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5370 htlc_timeout_tx = node_txn[1].clone();
5373 nodes[2].node.claim_funds(our_payment_preimage);
5374 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5376 mine_transaction(&nodes[2], &commitment_txn[0]);
5377 check_added_monitors!(nodes[2], 2);
5378 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5379 let events = nodes[2].node.get_and_clear_pending_msg_events();
5381 MessageSendEvent::UpdateHTLCs { .. } => {},
5382 _ => panic!("Unexpected event"),
5385 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5386 _ => panic!("Unexepected event"),
5388 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5389 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)
5390 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5391 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5392 assert_eq!(htlc_success_txn[0].input.len(), 1);
5393 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5394 assert_eq!(htlc_success_txn[1].input.len(), 1);
5395 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5396 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5397 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5398 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5399 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5400 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5402 mine_transaction(&nodes[1], &htlc_timeout_tx);
5403 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5404 expect_pending_htlcs_forwardable!(nodes[1]);
5405 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5406 assert!(htlc_updates.update_add_htlcs.is_empty());
5407 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5408 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5409 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5410 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5411 check_added_monitors!(nodes[1], 1);
5413 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5414 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5416 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5418 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5420 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5421 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5422 // and nodes[2] fee) is rounded down and then claimed in full.
5423 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5424 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196*2), true, true);
5425 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5426 assert!(updates.update_add_htlcs.is_empty());
5427 assert!(updates.update_fail_htlcs.is_empty());
5428 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5429 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5430 assert!(updates.update_fail_malformed_htlcs.is_empty());
5431 check_added_monitors!(nodes[1], 1);
5433 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5434 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5436 let events = nodes[0].node.get_and_clear_pending_events();
5438 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5439 assert_eq!(*payment_preimage, our_payment_preimage);
5440 assert_eq!(*payment_hash, duplicate_payment_hash);
5442 _ => panic!("Unexpected event"),
5447 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5448 let chanmon_cfgs = create_chanmon_cfgs(2);
5449 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5450 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5451 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5453 // Create some initial channels
5454 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5456 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5457 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5458 assert_eq!(local_txn.len(), 1);
5459 assert_eq!(local_txn[0].input.len(), 1);
5460 check_spends!(local_txn[0], chan_1.3);
5462 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5463 nodes[1].node.claim_funds(payment_preimage);
5464 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5465 check_added_monitors!(nodes[1], 1);
5467 mine_transaction(&nodes[1], &local_txn[0]);
5468 check_added_monitors!(nodes[1], 1);
5469 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5470 let events = nodes[1].node.get_and_clear_pending_msg_events();
5472 MessageSendEvent::UpdateHTLCs { .. } => {},
5473 _ => panic!("Unexpected event"),
5476 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5477 _ => panic!("Unexepected event"),
5480 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5481 assert_eq!(node_txn.len(), 3);
5482 assert_eq!(node_txn[0], node_txn[2]);
5483 assert_eq!(node_txn[1], local_txn[0]);
5484 assert_eq!(node_txn[0].input.len(), 1);
5485 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5486 check_spends!(node_txn[0], local_txn[0]);
5490 mine_transaction(&nodes[1], &node_tx);
5491 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5493 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5494 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5495 assert_eq!(spend_txn.len(), 1);
5496 assert_eq!(spend_txn[0].input.len(), 1);
5497 check_spends!(spend_txn[0], node_tx);
5498 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5501 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5502 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5503 // unrevoked commitment transaction.
5504 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5505 // a remote RAA before they could be failed backwards (and combinations thereof).
5506 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5507 // use the same payment hashes.
5508 // Thus, we use a six-node network:
5513 // And test where C fails back to A/B when D announces its latest commitment transaction
5514 let chanmon_cfgs = create_chanmon_cfgs(6);
5515 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5516 // When this test was written, the default base fee floated based on the HTLC count.
5517 // It is now fixed, so we simply set the fee to the expected value here.
5518 let mut config = test_default_channel_config();
5519 config.channel_config.forwarding_fee_base_msat = 196;
5520 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5521 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5522 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5524 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5525 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5526 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5527 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5528 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5530 // Rebalance and check output sanity...
5531 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5532 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5533 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5535 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5537 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
5539 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
5540 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5542 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
5544 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
5546 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5548 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5549 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5551 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());
5553 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());
5556 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5558 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5559 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
5562 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
5564 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5565 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());
5567 // Double-check that six of the new HTLC were added
5568 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5569 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5570 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5571 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5573 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5574 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5575 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5576 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5577 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5578 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5579 check_added_monitors!(nodes[4], 0);
5580 expect_pending_htlcs_forwardable!(nodes[4]);
5581 check_added_monitors!(nodes[4], 1);
5583 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5584 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5585 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5586 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5587 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5588 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5590 // Fail 3rd below-dust and 7th above-dust HTLCs
5591 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5592 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5593 check_added_monitors!(nodes[5], 0);
5594 expect_pending_htlcs_forwardable!(nodes[5]);
5595 check_added_monitors!(nodes[5], 1);
5597 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5598 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5599 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5600 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5602 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5604 expect_pending_htlcs_forwardable!(nodes[3]);
5605 check_added_monitors!(nodes[3], 1);
5606 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5607 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5608 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5609 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5610 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5611 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5612 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5613 if deliver_last_raa {
5614 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5616 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5619 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5620 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5621 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5622 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5624 // We now broadcast the latest commitment transaction, which *should* result in failures for
5625 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5626 // the non-broadcast above-dust HTLCs.
5628 // Alternatively, we may broadcast the previous commitment transaction, which should only
5629 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5630 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5632 if announce_latest {
5633 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5635 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5637 let events = nodes[2].node.get_and_clear_pending_events();
5638 let close_event = if deliver_last_raa {
5639 assert_eq!(events.len(), 2);
5642 assert_eq!(events.len(), 1);
5646 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5647 _ => panic!("Unexpected event"),
5650 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5651 check_closed_broadcast!(nodes[2], true);
5652 if deliver_last_raa {
5653 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5655 expect_pending_htlcs_forwardable!(nodes[2]);
5657 check_added_monitors!(nodes[2], 3);
5659 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5660 assert_eq!(cs_msgs.len(), 2);
5661 let mut a_done = false;
5662 for msg in cs_msgs {
5664 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5665 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5666 // should be failed-backwards here.
5667 let target = if *node_id == nodes[0].node.get_our_node_id() {
5668 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5669 for htlc in &updates.update_fail_htlcs {
5670 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 });
5672 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5677 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5678 for htlc in &updates.update_fail_htlcs {
5679 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5681 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5682 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5685 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5686 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5687 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5688 if announce_latest {
5689 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5690 if *node_id == nodes[0].node.get_our_node_id() {
5691 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5694 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5696 _ => panic!("Unexpected event"),
5700 let as_events = nodes[0].node.get_and_clear_pending_events();
5701 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5702 let mut as_failds = HashSet::new();
5703 let mut as_updates = 0;
5704 for event in as_events.iter() {
5705 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5706 assert!(as_failds.insert(*payment_hash));
5707 if *payment_hash != payment_hash_2 {
5708 assert_eq!(*rejected_by_dest, deliver_last_raa);
5710 assert!(!rejected_by_dest);
5712 if network_update.is_some() {
5715 } else { panic!("Unexpected event"); }
5717 assert!(as_failds.contains(&payment_hash_1));
5718 assert!(as_failds.contains(&payment_hash_2));
5719 if announce_latest {
5720 assert!(as_failds.contains(&payment_hash_3));
5721 assert!(as_failds.contains(&payment_hash_5));
5723 assert!(as_failds.contains(&payment_hash_6));
5725 let bs_events = nodes[1].node.get_and_clear_pending_events();
5726 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5727 let mut bs_failds = HashSet::new();
5728 let mut bs_updates = 0;
5729 for event in bs_events.iter() {
5730 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5731 assert!(bs_failds.insert(*payment_hash));
5732 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5733 assert_eq!(*rejected_by_dest, deliver_last_raa);
5735 assert!(!rejected_by_dest);
5737 if network_update.is_some() {
5740 } else { panic!("Unexpected event"); }
5742 assert!(bs_failds.contains(&payment_hash_1));
5743 assert!(bs_failds.contains(&payment_hash_2));
5744 if announce_latest {
5745 assert!(bs_failds.contains(&payment_hash_4));
5747 assert!(bs_failds.contains(&payment_hash_5));
5749 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5750 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5751 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5752 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5753 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5754 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5758 fn test_fail_backwards_latest_remote_announce_a() {
5759 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5763 fn test_fail_backwards_latest_remote_announce_b() {
5764 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5768 fn test_fail_backwards_previous_remote_announce() {
5769 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5770 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5771 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5775 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5776 let chanmon_cfgs = create_chanmon_cfgs(2);
5777 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5778 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5779 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5781 // Create some initial channels
5782 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5784 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5785 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5786 assert_eq!(local_txn[0].input.len(), 1);
5787 check_spends!(local_txn[0], chan_1.3);
5789 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5790 mine_transaction(&nodes[0], &local_txn[0]);
5791 check_closed_broadcast!(nodes[0], true);
5792 check_added_monitors!(nodes[0], 1);
5793 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5794 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5796 let htlc_timeout = {
5797 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5798 assert_eq!(node_txn.len(), 2);
5799 check_spends!(node_txn[0], chan_1.3);
5800 assert_eq!(node_txn[1].input.len(), 1);
5801 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5802 check_spends!(node_txn[1], local_txn[0]);
5806 mine_transaction(&nodes[0], &htlc_timeout);
5807 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5808 expect_payment_failed!(nodes[0], our_payment_hash, true);
5810 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5811 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5812 assert_eq!(spend_txn.len(), 3);
5813 check_spends!(spend_txn[0], local_txn[0]);
5814 assert_eq!(spend_txn[1].input.len(), 1);
5815 check_spends!(spend_txn[1], htlc_timeout);
5816 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5817 assert_eq!(spend_txn[2].input.len(), 2);
5818 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5819 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5820 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5824 fn test_key_derivation_params() {
5825 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5826 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5827 // let us re-derive the channel key set to then derive a delayed_payment_key.
5829 let chanmon_cfgs = create_chanmon_cfgs(3);
5831 // We manually create the node configuration to backup the seed.
5832 let seed = [42; 32];
5833 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5834 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);
5835 let network_graph = NetworkGraph::new(chanmon_cfgs[0].chain_source.genesis_hash, &chanmon_cfgs[0].logger);
5836 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() };
5837 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5838 node_cfgs.remove(0);
5839 node_cfgs.insert(0, node);
5841 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5842 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5844 // Create some initial channels
5845 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5847 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5848 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5849 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5851 // Ensure all nodes are at the same height
5852 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5853 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5854 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5855 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5857 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5858 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5859 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5860 assert_eq!(local_txn_1[0].input.len(), 1);
5861 check_spends!(local_txn_1[0], chan_1.3);
5863 // We check funding pubkey are unique
5864 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]));
5865 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]));
5866 if from_0_funding_key_0 == from_1_funding_key_0
5867 || from_0_funding_key_0 == from_1_funding_key_1
5868 || from_0_funding_key_1 == from_1_funding_key_0
5869 || from_0_funding_key_1 == from_1_funding_key_1 {
5870 panic!("Funding pubkeys aren't unique");
5873 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5874 mine_transaction(&nodes[0], &local_txn_1[0]);
5875 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5876 check_closed_broadcast!(nodes[0], true);
5877 check_added_monitors!(nodes[0], 1);
5878 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5880 let htlc_timeout = {
5881 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5882 assert_eq!(node_txn[1].input.len(), 1);
5883 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5884 check_spends!(node_txn[1], local_txn_1[0]);
5888 mine_transaction(&nodes[0], &htlc_timeout);
5889 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5890 expect_payment_failed!(nodes[0], our_payment_hash, true);
5892 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5893 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5894 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5895 assert_eq!(spend_txn.len(), 3);
5896 check_spends!(spend_txn[0], local_txn_1[0]);
5897 assert_eq!(spend_txn[1].input.len(), 1);
5898 check_spends!(spend_txn[1], htlc_timeout);
5899 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5900 assert_eq!(spend_txn[2].input.len(), 2);
5901 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5902 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5903 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5907 fn test_static_output_closing_tx() {
5908 let chanmon_cfgs = create_chanmon_cfgs(2);
5909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5911 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5913 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5915 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5916 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5918 mine_transaction(&nodes[0], &closing_tx);
5919 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5920 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5922 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5923 assert_eq!(spend_txn.len(), 1);
5924 check_spends!(spend_txn[0], closing_tx);
5926 mine_transaction(&nodes[1], &closing_tx);
5927 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5928 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5930 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5931 assert_eq!(spend_txn.len(), 1);
5932 check_spends!(spend_txn[0], closing_tx);
5935 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5936 let chanmon_cfgs = create_chanmon_cfgs(2);
5937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5939 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5940 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5942 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5944 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5945 // present in B's local commitment transaction, but none of A's commitment transactions.
5946 nodes[1].node.claim_funds(payment_preimage);
5947 check_added_monitors!(nodes[1], 1);
5948 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5950 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5951 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5952 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5954 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5955 check_added_monitors!(nodes[0], 1);
5956 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5957 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5958 check_added_monitors!(nodes[1], 1);
5960 let starting_block = nodes[1].best_block_info();
5961 let mut block = Block {
5962 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5965 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5966 connect_block(&nodes[1], &block);
5967 block.header.prev_blockhash = block.block_hash();
5969 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5970 check_closed_broadcast!(nodes[1], true);
5971 check_added_monitors!(nodes[1], 1);
5972 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5975 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5976 let chanmon_cfgs = create_chanmon_cfgs(2);
5977 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5978 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5979 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5980 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5982 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5983 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5984 check_added_monitors!(nodes[0], 1);
5986 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5988 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5989 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5990 // to "time out" the HTLC.
5992 let starting_block = nodes[1].best_block_info();
5993 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5995 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5996 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5997 header.prev_blockhash = header.block_hash();
5999 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6000 check_closed_broadcast!(nodes[0], true);
6001 check_added_monitors!(nodes[0], 1);
6002 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6005 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6006 let chanmon_cfgs = create_chanmon_cfgs(3);
6007 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6008 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6009 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6010 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6012 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6013 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6014 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6015 // actually revoked.
6016 let htlc_value = if use_dust { 50000 } else { 3000000 };
6017 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6018 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
6019 expect_pending_htlcs_forwardable!(nodes[1]);
6020 check_added_monitors!(nodes[1], 1);
6022 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6023 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6024 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6025 check_added_monitors!(nodes[0], 1);
6026 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6027 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6028 check_added_monitors!(nodes[1], 1);
6029 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6030 check_added_monitors!(nodes[1], 1);
6031 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6033 if check_revoke_no_close {
6034 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6035 check_added_monitors!(nodes[0], 1);
6038 let starting_block = nodes[1].best_block_info();
6039 let mut block = Block {
6040 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6043 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6044 connect_block(&nodes[0], &block);
6045 block.header.prev_blockhash = block.block_hash();
6047 if !check_revoke_no_close {
6048 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6049 check_closed_broadcast!(nodes[0], true);
6050 check_added_monitors!(nodes[0], 1);
6051 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6053 let events = nodes[0].node.get_and_clear_pending_events();
6054 assert_eq!(events.len(), 2);
6055 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
6056 assert_eq!(*payment_hash, our_payment_hash);
6057 } else { panic!("Unexpected event"); }
6058 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
6059 assert_eq!(*payment_hash, our_payment_hash);
6060 } else { panic!("Unexpected event"); }
6064 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6065 // There are only a few cases to test here:
6066 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6067 // broadcastable commitment transactions result in channel closure,
6068 // * its included in an unrevoked-but-previous remote commitment transaction,
6069 // * its included in the latest remote or local commitment transactions.
6070 // We test each of the three possible commitment transactions individually and use both dust and
6072 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6073 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6074 // tested for at least one of the cases in other tests.
6076 fn htlc_claim_single_commitment_only_a() {
6077 do_htlc_claim_local_commitment_only(true);
6078 do_htlc_claim_local_commitment_only(false);
6080 do_htlc_claim_current_remote_commitment_only(true);
6081 do_htlc_claim_current_remote_commitment_only(false);
6085 fn htlc_claim_single_commitment_only_b() {
6086 do_htlc_claim_previous_remote_commitment_only(true, false);
6087 do_htlc_claim_previous_remote_commitment_only(false, false);
6088 do_htlc_claim_previous_remote_commitment_only(true, true);
6089 do_htlc_claim_previous_remote_commitment_only(false, true);
6094 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6095 let chanmon_cfgs = create_chanmon_cfgs(2);
6096 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6097 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6098 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6099 // Force duplicate randomness for every get-random call
6100 for node in nodes.iter() {
6101 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
6104 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6105 let channel_value_satoshis=10000;
6106 let push_msat=10001;
6107 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6108 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6109 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6110 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6112 // Create a second channel with the same random values. This used to panic due to a colliding
6113 // channel_id, but now panics due to a colliding outbound SCID alias.
6114 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6118 fn bolt2_open_channel_sending_node_checks_part2() {
6119 let chanmon_cfgs = create_chanmon_cfgs(2);
6120 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6121 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6122 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6124 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6125 let channel_value_satoshis=2^24;
6126 let push_msat=10001;
6127 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6129 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6130 let channel_value_satoshis=10000;
6131 // Test when push_msat is equal to 1000 * funding_satoshis.
6132 let push_msat=1000*channel_value_satoshis+1;
6133 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6135 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6136 let channel_value_satoshis=10000;
6137 let push_msat=10001;
6138 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
6139 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6140 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6142 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6143 // 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
6144 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6146 // 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.
6147 assert!(BREAKDOWN_TIMEOUT>0);
6148 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6150 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6151 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6152 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6154 // 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.
6155 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6156 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6157 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6158 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6159 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6163 fn bolt2_open_channel_sane_dust_limit() {
6164 let chanmon_cfgs = create_chanmon_cfgs(2);
6165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6169 let channel_value_satoshis=1000000;
6170 let push_msat=10001;
6171 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6172 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6173 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6174 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6176 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6177 let events = nodes[1].node.get_and_clear_pending_msg_events();
6178 let err_msg = match events[0] {
6179 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6182 _ => panic!("Unexpected event"),
6184 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6187 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6188 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6189 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6190 // is no longer affordable once it's freed.
6192 fn test_fail_holding_cell_htlc_upon_free() {
6193 let chanmon_cfgs = create_chanmon_cfgs(2);
6194 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6195 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6196 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6197 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6199 // First nodes[0] generates an update_fee, setting the channel's
6200 // pending_update_fee.
6202 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6203 *feerate_lock += 20;
6205 nodes[0].node.timer_tick_occurred();
6206 check_added_monitors!(nodes[0], 1);
6208 let events = nodes[0].node.get_and_clear_pending_msg_events();
6209 assert_eq!(events.len(), 1);
6210 let (update_msg, commitment_signed) = match events[0] {
6211 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6212 (update_fee.as_ref(), commitment_signed)
6214 _ => panic!("Unexpected event"),
6217 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6219 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6220 let channel_reserve = chan_stat.channel_reserve_msat;
6221 let feerate = get_feerate!(nodes[0], chan.2);
6222 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6224 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6225 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6226 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6228 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6229 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6230 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6231 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6233 // Flush the pending fee update.
6234 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6235 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6236 check_added_monitors!(nodes[1], 1);
6237 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6238 check_added_monitors!(nodes[0], 1);
6240 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6241 // HTLC, but now that the fee has been raised the payment will now fail, causing
6242 // us to surface its failure to the user.
6243 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6244 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6245 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);
6246 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 {}",
6247 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6248 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6250 // Check that the payment failed to be sent out.
6251 let events = nodes[0].node.get_and_clear_pending_events();
6252 assert_eq!(events.len(), 1);
6254 &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, .. } => {
6255 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6256 assert_eq!(our_payment_hash.clone(), *payment_hash);
6257 assert_eq!(*rejected_by_dest, false);
6258 assert_eq!(*all_paths_failed, true);
6259 assert_eq!(*network_update, None);
6260 assert_eq!(*short_channel_id, None);
6261 assert_eq!(*error_code, None);
6262 assert_eq!(*error_data, None);
6264 _ => panic!("Unexpected event"),
6268 // Test that if multiple HTLCs are released from the holding cell and one is
6269 // valid but the other is no longer valid upon release, the valid HTLC can be
6270 // successfully completed while the other one fails as expected.
6272 fn test_free_and_fail_holding_cell_htlcs() {
6273 let chanmon_cfgs = create_chanmon_cfgs(2);
6274 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6275 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6276 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6277 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6279 // First nodes[0] generates an update_fee, setting the channel's
6280 // pending_update_fee.
6282 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6283 *feerate_lock += 200;
6285 nodes[0].node.timer_tick_occurred();
6286 check_added_monitors!(nodes[0], 1);
6288 let events = nodes[0].node.get_and_clear_pending_msg_events();
6289 assert_eq!(events.len(), 1);
6290 let (update_msg, commitment_signed) = match events[0] {
6291 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6292 (update_fee.as_ref(), commitment_signed)
6294 _ => panic!("Unexpected event"),
6297 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6299 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6300 let channel_reserve = chan_stat.channel_reserve_msat;
6301 let feerate = get_feerate!(nodes[0], chan.2);
6302 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6304 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6306 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6307 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6308 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6310 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6311 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6312 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6313 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6314 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6315 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6316 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6318 // Flush the pending fee update.
6319 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6320 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6321 check_added_monitors!(nodes[1], 1);
6322 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6323 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6324 check_added_monitors!(nodes[0], 2);
6326 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6327 // but now that the fee has been raised the second payment will now fail, causing us
6328 // to surface its failure to the user. The first payment should succeed.
6329 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6330 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6331 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);
6332 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 {}",
6333 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6334 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6336 // Check that the second payment failed to be sent out.
6337 let events = nodes[0].node.get_and_clear_pending_events();
6338 assert_eq!(events.len(), 1);
6340 &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, .. } => {
6341 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6342 assert_eq!(payment_hash_2.clone(), *payment_hash);
6343 assert_eq!(*rejected_by_dest, false);
6344 assert_eq!(*all_paths_failed, true);
6345 assert_eq!(*network_update, None);
6346 assert_eq!(*short_channel_id, None);
6347 assert_eq!(*error_code, None);
6348 assert_eq!(*error_data, None);
6350 _ => panic!("Unexpected event"),
6353 // Complete the first payment and the RAA from the fee update.
6354 let (payment_event, send_raa_event) = {
6355 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6356 assert_eq!(msgs.len(), 2);
6357 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6359 let raa = match send_raa_event {
6360 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6361 _ => panic!("Unexpected event"),
6363 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6364 check_added_monitors!(nodes[1], 1);
6365 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6366 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6367 let events = nodes[1].node.get_and_clear_pending_events();
6368 assert_eq!(events.len(), 1);
6370 Event::PendingHTLCsForwardable { .. } => {},
6371 _ => panic!("Unexpected event"),
6373 nodes[1].node.process_pending_htlc_forwards();
6374 let events = nodes[1].node.get_and_clear_pending_events();
6375 assert_eq!(events.len(), 1);
6377 Event::PaymentReceived { .. } => {},
6378 _ => panic!("Unexpected event"),
6380 nodes[1].node.claim_funds(payment_preimage_1);
6381 check_added_monitors!(nodes[1], 1);
6382 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6384 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6385 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6386 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6387 expect_payment_sent!(nodes[0], payment_preimage_1);
6390 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6391 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6392 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6395 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6396 let chanmon_cfgs = create_chanmon_cfgs(3);
6397 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6398 // When this test was written, the default base fee floated based on the HTLC count.
6399 // It is now fixed, so we simply set the fee to the expected value here.
6400 let mut config = test_default_channel_config();
6401 config.channel_config.forwarding_fee_base_msat = 196;
6402 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6403 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6404 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6405 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6407 // First nodes[1] generates an update_fee, setting the channel's
6408 // pending_update_fee.
6410 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6411 *feerate_lock += 20;
6413 nodes[1].node.timer_tick_occurred();
6414 check_added_monitors!(nodes[1], 1);
6416 let events = nodes[1].node.get_and_clear_pending_msg_events();
6417 assert_eq!(events.len(), 1);
6418 let (update_msg, commitment_signed) = match events[0] {
6419 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6420 (update_fee.as_ref(), commitment_signed)
6422 _ => panic!("Unexpected event"),
6425 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6427 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6428 let channel_reserve = chan_stat.channel_reserve_msat;
6429 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6430 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6432 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6434 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6435 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6436 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6437 let payment_event = {
6438 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6439 check_added_monitors!(nodes[0], 1);
6441 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6442 assert_eq!(events.len(), 1);
6444 SendEvent::from_event(events.remove(0))
6446 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6447 check_added_monitors!(nodes[1], 0);
6448 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6449 expect_pending_htlcs_forwardable!(nodes[1]);
6451 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6452 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6454 // Flush the pending fee update.
6455 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6456 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6457 check_added_monitors!(nodes[2], 1);
6458 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6459 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6460 check_added_monitors!(nodes[1], 2);
6462 // A final RAA message is generated to finalize the fee update.
6463 let events = nodes[1].node.get_and_clear_pending_msg_events();
6464 assert_eq!(events.len(), 1);
6466 let raa_msg = match &events[0] {
6467 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6470 _ => panic!("Unexpected event"),
6473 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6474 check_added_monitors!(nodes[2], 1);
6475 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6477 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6478 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6479 assert_eq!(process_htlc_forwards_event.len(), 1);
6480 match &process_htlc_forwards_event[0] {
6481 &Event::PendingHTLCsForwardable { .. } => {},
6482 _ => panic!("Unexpected event"),
6485 // In response, we call ChannelManager's process_pending_htlc_forwards
6486 nodes[1].node.process_pending_htlc_forwards();
6487 check_added_monitors!(nodes[1], 1);
6489 // This causes the HTLC to be failed backwards.
6490 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6491 assert_eq!(fail_event.len(), 1);
6492 let (fail_msg, commitment_signed) = match &fail_event[0] {
6493 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6494 assert_eq!(updates.update_add_htlcs.len(), 0);
6495 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6496 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6497 assert_eq!(updates.update_fail_htlcs.len(), 1);
6498 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6500 _ => panic!("Unexpected event"),
6503 // Pass the failure messages back to nodes[0].
6504 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6505 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6507 // Complete the HTLC failure+removal process.
6508 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6509 check_added_monitors!(nodes[0], 1);
6510 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6511 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6512 check_added_monitors!(nodes[1], 2);
6513 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6514 assert_eq!(final_raa_event.len(), 1);
6515 let raa = match &final_raa_event[0] {
6516 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6517 _ => panic!("Unexpected event"),
6519 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6520 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6521 check_added_monitors!(nodes[0], 1);
6524 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6525 // 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.
6526 //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.
6529 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6530 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6531 let chanmon_cfgs = create_chanmon_cfgs(2);
6532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6534 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6535 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6537 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6538 route.paths[0][0].fee_msat = 100;
6540 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6541 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6542 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6543 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6547 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6548 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6549 let chanmon_cfgs = create_chanmon_cfgs(2);
6550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6552 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6555 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6556 route.paths[0][0].fee_msat = 0;
6557 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6558 assert_eq!(err, "Cannot send 0-msat HTLC"));
6560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6561 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6565 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6566 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6567 let chanmon_cfgs = create_chanmon_cfgs(2);
6568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6570 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6571 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6573 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6574 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6575 check_added_monitors!(nodes[0], 1);
6576 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6577 updates.update_add_htlcs[0].amount_msat = 0;
6579 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6580 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6581 check_closed_broadcast!(nodes[1], true).unwrap();
6582 check_added_monitors!(nodes[1], 1);
6583 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6587 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6588 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6589 //It is enforced when constructing a route.
6590 let chanmon_cfgs = create_chanmon_cfgs(2);
6591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6593 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6594 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6596 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6597 .with_features(InvoiceFeatures::known());
6598 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6599 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6600 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6601 assert_eq!(err, &"Channel CLTV overflowed?"));
6605 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6606 //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.
6607 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6608 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6609 let chanmon_cfgs = create_chanmon_cfgs(2);
6610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6613 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6614 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6616 for i in 0..max_accepted_htlcs {
6617 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6618 let payment_event = {
6619 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6620 check_added_monitors!(nodes[0], 1);
6622 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6623 assert_eq!(events.len(), 1);
6624 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6625 assert_eq!(htlcs[0].htlc_id, i);
6629 SendEvent::from_event(events.remove(0))
6631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6632 check_added_monitors!(nodes[1], 0);
6633 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6635 expect_pending_htlcs_forwardable!(nodes[1]);
6636 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6638 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6639 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6640 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6642 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6643 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6647 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6648 //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.
6649 let chanmon_cfgs = create_chanmon_cfgs(2);
6650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653 let channel_value = 100000;
6654 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6655 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6657 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6659 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6660 // Manually create a route over our max in flight (which our router normally automatically
6662 route.paths[0][0].fee_msat = max_in_flight + 1;
6663 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6664 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)));
6666 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6667 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);
6669 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6672 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6674 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6675 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6676 let chanmon_cfgs = create_chanmon_cfgs(2);
6677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6679 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6680 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6681 let htlc_minimum_msat: u64;
6683 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6684 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6685 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6688 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6689 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6690 check_added_monitors!(nodes[0], 1);
6691 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6692 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6693 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6694 assert!(nodes[1].node.list_channels().is_empty());
6695 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6696 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()));
6697 check_added_monitors!(nodes[1], 1);
6698 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6702 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6703 //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
6704 let chanmon_cfgs = create_chanmon_cfgs(2);
6705 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6706 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6707 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6708 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6710 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6711 let channel_reserve = chan_stat.channel_reserve_msat;
6712 let feerate = get_feerate!(nodes[0], chan.2);
6713 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6714 // The 2* and +1 are for the fee spike reserve.
6715 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6717 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6718 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6719 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6720 check_added_monitors!(nodes[0], 1);
6721 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6723 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6724 // at this time channel-initiatee receivers are not required to enforce that senders
6725 // respect the fee_spike_reserve.
6726 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6727 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6729 assert!(nodes[1].node.list_channels().is_empty());
6730 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6731 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6732 check_added_monitors!(nodes[1], 1);
6733 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6737 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6738 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6739 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6740 let chanmon_cfgs = create_chanmon_cfgs(2);
6741 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6742 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6743 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6746 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6747 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6748 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6749 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6750 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6751 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6753 let mut msg = msgs::UpdateAddHTLC {
6757 payment_hash: our_payment_hash,
6758 cltv_expiry: htlc_cltv,
6759 onion_routing_packet: onion_packet.clone(),
6762 for i in 0..super::channel::OUR_MAX_HTLCS {
6763 msg.htlc_id = i as u64;
6764 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6766 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6767 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6769 assert!(nodes[1].node.list_channels().is_empty());
6770 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6771 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6772 check_added_monitors!(nodes[1], 1);
6773 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6777 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6778 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6779 let chanmon_cfgs = create_chanmon_cfgs(2);
6780 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6781 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6782 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6783 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6785 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6786 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6787 check_added_monitors!(nodes[0], 1);
6788 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6789 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6790 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6792 assert!(nodes[1].node.list_channels().is_empty());
6793 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6794 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6795 check_added_monitors!(nodes[1], 1);
6796 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6800 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6801 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6802 let chanmon_cfgs = create_chanmon_cfgs(2);
6803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6805 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6807 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6808 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6809 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6810 check_added_monitors!(nodes[0], 1);
6811 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6812 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6813 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6815 assert!(nodes[1].node.list_channels().is_empty());
6816 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6817 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6818 check_added_monitors!(nodes[1], 1);
6819 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6823 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6824 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6825 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6826 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6827 let chanmon_cfgs = create_chanmon_cfgs(2);
6828 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6829 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6830 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6832 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6833 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6834 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6835 check_added_monitors!(nodes[0], 1);
6836 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6837 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6839 //Disconnect and Reconnect
6840 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6841 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6842 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6843 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6844 assert_eq!(reestablish_1.len(), 1);
6845 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6846 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6847 assert_eq!(reestablish_2.len(), 1);
6848 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6849 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6850 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6851 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6855 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6856 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6857 check_added_monitors!(nodes[1], 1);
6858 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6860 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6862 assert!(nodes[1].node.list_channels().is_empty());
6863 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6864 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6865 check_added_monitors!(nodes[1], 1);
6866 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6870 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6871 //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.
6873 let chanmon_cfgs = create_chanmon_cfgs(2);
6874 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6875 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6876 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6877 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6878 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6879 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6881 check_added_monitors!(nodes[0], 1);
6882 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6883 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6885 let update_msg = msgs::UpdateFulfillHTLC{
6888 payment_preimage: our_payment_preimage,
6891 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6893 assert!(nodes[0].node.list_channels().is_empty());
6894 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6895 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()));
6896 check_added_monitors!(nodes[0], 1);
6897 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6901 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6902 //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.
6904 let chanmon_cfgs = create_chanmon_cfgs(2);
6905 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6906 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6907 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6908 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6910 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6911 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6912 check_added_monitors!(nodes[0], 1);
6913 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6914 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6916 let update_msg = msgs::UpdateFailHTLC{
6919 reason: msgs::OnionErrorPacket { data: Vec::new()},
6922 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6924 assert!(nodes[0].node.list_channels().is_empty());
6925 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6926 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()));
6927 check_added_monitors!(nodes[0], 1);
6928 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6932 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6933 //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.
6935 let chanmon_cfgs = create_chanmon_cfgs(2);
6936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6938 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6939 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6941 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6942 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6943 check_added_monitors!(nodes[0], 1);
6944 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6945 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6946 let update_msg = msgs::UpdateFailMalformedHTLC{
6949 sha256_of_onion: [1; 32],
6950 failure_code: 0x8000,
6953 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6955 assert!(nodes[0].node.list_channels().is_empty());
6956 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6957 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()));
6958 check_added_monitors!(nodes[0], 1);
6959 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6963 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6964 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6966 let chanmon_cfgs = create_chanmon_cfgs(2);
6967 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6968 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6969 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6970 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6972 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6974 nodes[1].node.claim_funds(our_payment_preimage);
6975 check_added_monitors!(nodes[1], 1);
6976 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6978 let events = nodes[1].node.get_and_clear_pending_msg_events();
6979 assert_eq!(events.len(), 1);
6980 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6982 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, .. } } => {
6983 assert!(update_add_htlcs.is_empty());
6984 assert_eq!(update_fulfill_htlcs.len(), 1);
6985 assert!(update_fail_htlcs.is_empty());
6986 assert!(update_fail_malformed_htlcs.is_empty());
6987 assert!(update_fee.is_none());
6988 update_fulfill_htlcs[0].clone()
6990 _ => panic!("Unexpected event"),
6994 update_fulfill_msg.htlc_id = 1;
6996 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6998 assert!(nodes[0].node.list_channels().is_empty());
6999 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7000 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7001 check_added_monitors!(nodes[0], 1);
7002 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7006 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7007 //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.
7009 let chanmon_cfgs = create_chanmon_cfgs(2);
7010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7012 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7013 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7015 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
7017 nodes[1].node.claim_funds(our_payment_preimage);
7018 check_added_monitors!(nodes[1], 1);
7019 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
7021 let events = nodes[1].node.get_and_clear_pending_msg_events();
7022 assert_eq!(events.len(), 1);
7023 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7025 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, .. } } => {
7026 assert!(update_add_htlcs.is_empty());
7027 assert_eq!(update_fulfill_htlcs.len(), 1);
7028 assert!(update_fail_htlcs.is_empty());
7029 assert!(update_fail_malformed_htlcs.is_empty());
7030 assert!(update_fee.is_none());
7031 update_fulfill_htlcs[0].clone()
7033 _ => panic!("Unexpected event"),
7037 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7039 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7041 assert!(nodes[0].node.list_channels().is_empty());
7042 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7043 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7044 check_added_monitors!(nodes[0], 1);
7045 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7049 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7050 //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.
7052 let chanmon_cfgs = create_chanmon_cfgs(2);
7053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7055 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7056 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7058 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
7059 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7060 check_added_monitors!(nodes[0], 1);
7062 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7063 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7065 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7066 check_added_monitors!(nodes[1], 0);
7067 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7069 let events = nodes[1].node.get_and_clear_pending_msg_events();
7071 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7073 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, .. } } => {
7074 assert!(update_add_htlcs.is_empty());
7075 assert!(update_fulfill_htlcs.is_empty());
7076 assert!(update_fail_htlcs.is_empty());
7077 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7078 assert!(update_fee.is_none());
7079 update_fail_malformed_htlcs[0].clone()
7081 _ => panic!("Unexpected event"),
7084 update_msg.failure_code &= !0x8000;
7085 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7087 assert!(nodes[0].node.list_channels().is_empty());
7088 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7089 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7090 check_added_monitors!(nodes[0], 1);
7091 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
7095 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7096 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7097 // * 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.
7099 let chanmon_cfgs = create_chanmon_cfgs(3);
7100 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7101 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7102 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7103 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7104 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7106 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
7109 let mut payment_event = {
7110 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7111 check_added_monitors!(nodes[0], 1);
7112 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7113 assert_eq!(events.len(), 1);
7114 SendEvent::from_event(events.remove(0))
7116 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7117 check_added_monitors!(nodes[1], 0);
7118 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7119 expect_pending_htlcs_forwardable!(nodes[1]);
7120 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7121 assert_eq!(events_2.len(), 1);
7122 check_added_monitors!(nodes[1], 1);
7123 payment_event = SendEvent::from_event(events_2.remove(0));
7124 assert_eq!(payment_event.msgs.len(), 1);
7127 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7128 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7129 check_added_monitors!(nodes[2], 0);
7130 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7132 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7133 assert_eq!(events_3.len(), 1);
7134 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7136 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 } } => {
7137 assert!(update_add_htlcs.is_empty());
7138 assert!(update_fulfill_htlcs.is_empty());
7139 assert!(update_fail_htlcs.is_empty());
7140 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7141 assert!(update_fee.is_none());
7142 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7144 _ => panic!("Unexpected event"),
7148 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7150 check_added_monitors!(nodes[1], 0);
7151 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7152 expect_pending_htlcs_forwardable!(nodes[1]);
7153 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7154 assert_eq!(events_4.len(), 1);
7156 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7158 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, .. } } => {
7159 assert!(update_add_htlcs.is_empty());
7160 assert!(update_fulfill_htlcs.is_empty());
7161 assert_eq!(update_fail_htlcs.len(), 1);
7162 assert!(update_fail_malformed_htlcs.is_empty());
7163 assert!(update_fee.is_none());
7165 _ => panic!("Unexpected event"),
7168 check_added_monitors!(nodes[1], 1);
7171 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7172 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7173 // 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
7174 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7176 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7177 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7180 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7181 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7183 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7185 // We route 2 dust-HTLCs between A and B
7186 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7187 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7188 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7190 // Cache one local commitment tx as previous
7191 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7193 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7194 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7195 check_added_monitors!(nodes[1], 0);
7196 expect_pending_htlcs_forwardable!(nodes[1]);
7197 check_added_monitors!(nodes[1], 1);
7199 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7200 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7201 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7202 check_added_monitors!(nodes[0], 1);
7204 // Cache one local commitment tx as lastest
7205 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7207 let events = nodes[0].node.get_and_clear_pending_msg_events();
7209 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7210 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7212 _ => panic!("Unexpected event"),
7215 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7216 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7218 _ => panic!("Unexpected event"),
7221 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7222 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7223 if announce_latest {
7224 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7226 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7229 check_closed_broadcast!(nodes[0], true);
7230 check_added_monitors!(nodes[0], 1);
7231 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7233 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7234 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7235 let events = nodes[0].node.get_and_clear_pending_events();
7236 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7237 assert_eq!(events.len(), 2);
7238 let mut first_failed = false;
7239 for event in events {
7241 Event::PaymentPathFailed { payment_hash, .. } => {
7242 if payment_hash == payment_hash_1 {
7243 assert!(!first_failed);
7244 first_failed = true;
7246 assert_eq!(payment_hash, payment_hash_2);
7249 _ => panic!("Unexpected event"),
7255 fn test_failure_delay_dust_htlc_local_commitment() {
7256 do_test_failure_delay_dust_htlc_local_commitment(true);
7257 do_test_failure_delay_dust_htlc_local_commitment(false);
7260 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7261 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7262 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7263 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7264 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7265 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7266 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7268 let chanmon_cfgs = create_chanmon_cfgs(3);
7269 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7270 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7271 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7272 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7274 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7276 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7277 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7279 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7280 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7282 // We revoked bs_commitment_tx
7284 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7285 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7288 let mut timeout_tx = Vec::new();
7290 // We fail dust-HTLC 1 by broadcast of local commitment tx
7291 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7292 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7293 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7294 expect_payment_failed!(nodes[0], dust_hash, true);
7296 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7297 check_closed_broadcast!(nodes[0], true);
7298 check_added_monitors!(nodes[0], 1);
7299 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7300 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7301 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7302 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7303 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7304 mine_transaction(&nodes[0], &timeout_tx[0]);
7305 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7306 expect_payment_failed!(nodes[0], non_dust_hash, true);
7308 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7309 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7310 check_closed_broadcast!(nodes[0], true);
7311 check_added_monitors!(nodes[0], 1);
7312 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7313 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7315 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7316 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7317 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7318 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7319 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7320 // dust HTLC should have been failed.
7321 expect_payment_failed!(nodes[0], dust_hash, true);
7324 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7326 assert_eq!(timeout_tx[0].lock_time, 0);
7328 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7329 mine_transaction(&nodes[0], &timeout_tx[0]);
7330 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7331 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7332 expect_payment_failed!(nodes[0], non_dust_hash, true);
7337 fn test_sweep_outbound_htlc_failure_update() {
7338 do_test_sweep_outbound_htlc_failure_update(false, true);
7339 do_test_sweep_outbound_htlc_failure_update(false, false);
7340 do_test_sweep_outbound_htlc_failure_update(true, false);
7344 fn test_user_configurable_csv_delay() {
7345 // We test our channel constructors yield errors when we pass them absurd csv delay
7347 let mut low_our_to_self_config = UserConfig::default();
7348 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7349 let mut high_their_to_self_config = UserConfig::default();
7350 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7351 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7352 let chanmon_cfgs = create_chanmon_cfgs(2);
7353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7357 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7358 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7359 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7360 &low_our_to_self_config, 0, 42)
7363 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())); },
7364 _ => panic!("Unexpected event"),
7366 } else { assert!(false) }
7368 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7369 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7370 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7371 open_channel.to_self_delay = 200;
7372 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7373 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7374 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7377 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())); },
7378 _ => panic!("Unexpected event"),
7380 } else { assert!(false); }
7382 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7383 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7384 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()));
7385 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7386 accept_channel.to_self_delay = 200;
7387 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7389 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7391 &ErrorAction::SendErrorMessage { ref msg } => {
7392 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()));
7393 reason_msg = msg.data.clone();
7397 } else { panic!(); }
7398 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7400 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7401 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7402 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7403 open_channel.to_self_delay = 200;
7404 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7405 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7406 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7409 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())); },
7410 _ => panic!("Unexpected event"),
7412 } else { assert!(false); }
7415 fn do_test_data_loss_protect(reconnect_panicing: bool) {
7416 // When we get a data_loss_protect proving we're behind, we immediately panic as the
7417 // chain::Watch API requirements have been violated (e.g. the user restored from a backup). The
7418 // panic message informs the user they should force-close without broadcasting, which is tested
7419 // if `reconnect_panicing` is not set.
7425 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7426 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7427 // during signing due to revoked tx
7428 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7429 let keys_manager = &chanmon_cfgs[0].keys_manager;
7432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7434 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7436 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7438 // Cache node A state before any channel update
7439 let previous_node_state = nodes[0].node.encode();
7440 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7441 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7443 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7444 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7446 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7447 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7449 // Restore node A from previous state
7450 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7451 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7452 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7453 tx_broadcaster = test_utils::TestBroadcaster { txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new())) };
7454 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7455 persister = test_utils::TestPersister::new();
7456 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7458 let mut channel_monitors = HashMap::new();
7459 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7460 <(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 {
7461 keys_manager: keys_manager,
7462 fee_estimator: &fee_estimator,
7463 chain_monitor: &monitor,
7465 tx_broadcaster: &tx_broadcaster,
7466 default_config: UserConfig::default(),
7470 nodes[0].node = &node_state_0;
7471 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7472 nodes[0].chain_monitor = &monitor;
7473 nodes[0].chain_source = &chain_source;
7475 check_added_monitors!(nodes[0], 1);
7477 if reconnect_panicing {
7478 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7479 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7481 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7483 // Check we close channel detecting A is fallen-behind
7484 // Check that we sent the warning message when we detected that A has fallen behind,
7485 // and give the possibility for A to recover from the warning.
7486 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7487 let warn_msg = "Peer attempted to reestablish channel with a very old local commitment transaction".to_owned();
7488 assert!(check_warn_msg!(nodes[1], nodes[0].node.get_our_node_id(), chan.2).contains(&warn_msg));
7491 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7492 // The node B should not broadcast the transaction to force close the channel!
7493 assert!(node_txn.is_empty());
7496 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7497 // Check A panics upon seeing proof it has fallen behind.
7498 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7499 return; // By this point we should have panic'ed!
7502 nodes[0].node.force_close_without_broadcasting_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
7503 check_added_monitors!(nodes[0], 1);
7504 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
7506 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7507 assert_eq!(node_txn.len(), 0);
7510 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7511 if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7512 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7514 &ErrorAction::SendErrorMessage { ref msg } => {
7515 assert_eq!(msg.data, "Channel force-closed");
7517 _ => panic!("Unexpected event!"),
7520 panic!("Unexpected event {:?}", msg)
7524 // after the warning message sent by B, we should not able to
7525 // use the channel, or reconnect with success to the channel.
7526 assert!(nodes[0].node.list_usable_channels().is_empty());
7527 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7528 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7529 let retry_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7531 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &retry_reestablish[0]);
7532 let mut err_msgs_0 = Vec::with_capacity(1);
7533 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7534 if let MessageSendEvent::HandleError { ref action, .. } = msg {
7536 &ErrorAction::SendErrorMessage { ref msg } => {
7537 assert_eq!(msg.data, "Failed to find corresponding channel");
7538 err_msgs_0.push(msg.clone());
7540 _ => panic!("Unexpected event!"),
7543 panic!("Unexpected event!");
7546 assert_eq!(err_msgs_0.len(), 1);
7547 nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), &err_msgs_0[0]);
7548 assert!(nodes[1].node.list_usable_channels().is_empty());
7549 check_added_monitors!(nodes[1], 1);
7550 check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Failed to find corresponding channel".to_owned() });
7551 check_closed_broadcast!(nodes[1], false);
7556 fn test_data_loss_protect_showing_stale_state_panics() {
7557 do_test_data_loss_protect(true);
7561 fn test_force_close_without_broadcast() {
7562 do_test_data_loss_protect(false);
7566 fn test_check_htlc_underpaying() {
7567 // Send payment through A -> B but A is maliciously
7568 // sending a probe payment (i.e less than expected value0
7569 // to B, B should refuse payment.
7571 let chanmon_cfgs = create_chanmon_cfgs(2);
7572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7574 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7576 // Create some initial channels
7577 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7579 let scorer = test_utils::TestScorer::with_penalty(0);
7580 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7581 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7582 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();
7583 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7584 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7585 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7586 check_added_monitors!(nodes[0], 1);
7588 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7589 assert_eq!(events.len(), 1);
7590 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7592 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7594 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7595 // and then will wait a second random delay before failing the HTLC back:
7596 expect_pending_htlcs_forwardable!(nodes[1]);
7597 expect_pending_htlcs_forwardable!(nodes[1]);
7599 // Node 3 is expecting payment of 100_000 but received 10_000,
7600 // it should fail htlc like we didn't know the preimage.
7601 nodes[1].node.process_pending_htlc_forwards();
7603 let events = nodes[1].node.get_and_clear_pending_msg_events();
7604 assert_eq!(events.len(), 1);
7605 let (update_fail_htlc, commitment_signed) = match events[0] {
7606 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 } } => {
7607 assert!(update_add_htlcs.is_empty());
7608 assert!(update_fulfill_htlcs.is_empty());
7609 assert_eq!(update_fail_htlcs.len(), 1);
7610 assert!(update_fail_malformed_htlcs.is_empty());
7611 assert!(update_fee.is_none());
7612 (update_fail_htlcs[0].clone(), commitment_signed)
7614 _ => panic!("Unexpected event"),
7616 check_added_monitors!(nodes[1], 1);
7618 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7619 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7621 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7622 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7623 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7624 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7628 fn test_announce_disable_channels() {
7629 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7630 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7632 let chanmon_cfgs = create_chanmon_cfgs(2);
7633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7637 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7638 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7639 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7642 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7643 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7645 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7646 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7647 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7648 assert_eq!(msg_events.len(), 3);
7649 let mut chans_disabled = HashMap::new();
7650 for e in msg_events {
7652 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7653 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7654 // Check that each channel gets updated exactly once
7655 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7656 panic!("Generated ChannelUpdate for wrong chan!");
7659 _ => panic!("Unexpected event"),
7663 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7664 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7665 assert_eq!(reestablish_1.len(), 3);
7666 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7667 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7668 assert_eq!(reestablish_2.len(), 3);
7670 // Reestablish chan_1
7671 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7672 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7673 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7674 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7675 // Reestablish chan_2
7676 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7677 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7678 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7679 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7680 // Reestablish chan_3
7681 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7682 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7683 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7684 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7686 nodes[0].node.timer_tick_occurred();
7687 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7688 nodes[0].node.timer_tick_occurred();
7689 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7690 assert_eq!(msg_events.len(), 3);
7691 for e in msg_events {
7693 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7694 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7695 match chans_disabled.remove(&msg.contents.short_channel_id) {
7696 // Each update should have a higher timestamp than the previous one, replacing
7698 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7699 None => panic!("Generated ChannelUpdate for wrong chan!"),
7702 _ => panic!("Unexpected event"),
7705 // Check that each channel gets updated exactly once
7706 assert!(chans_disabled.is_empty());
7710 fn test_bump_penalty_txn_on_revoked_commitment() {
7711 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7712 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7714 let chanmon_cfgs = create_chanmon_cfgs(2);
7715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7717 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7719 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7721 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7722 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7723 .with_features(InvoiceFeatures::known());
7724 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7725 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7727 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7728 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7729 assert_eq!(revoked_txn[0].output.len(), 4);
7730 assert_eq!(revoked_txn[0].input.len(), 1);
7731 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7732 let revoked_txid = revoked_txn[0].txid();
7734 let mut penalty_sum = 0;
7735 for outp in revoked_txn[0].output.iter() {
7736 if outp.script_pubkey.is_v0_p2wsh() {
7737 penalty_sum += outp.value;
7741 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7742 let header_114 = connect_blocks(&nodes[1], 14);
7744 // Actually revoke tx by claiming a HTLC
7745 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7746 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7747 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7748 check_added_monitors!(nodes[1], 1);
7750 // One or more justice tx should have been broadcast, check it
7754 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7755 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7756 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7757 assert_eq!(node_txn[0].output.len(), 1);
7758 check_spends!(node_txn[0], revoked_txn[0]);
7759 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7760 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7761 penalty_1 = node_txn[0].txid();
7765 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7766 connect_blocks(&nodes[1], 15);
7767 let mut penalty_2 = penalty_1;
7768 let mut feerate_2 = 0;
7770 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7771 assert_eq!(node_txn.len(), 1);
7772 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7773 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7774 assert_eq!(node_txn[0].output.len(), 1);
7775 check_spends!(node_txn[0], revoked_txn[0]);
7776 penalty_2 = node_txn[0].txid();
7777 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7778 assert_ne!(penalty_2, penalty_1);
7779 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7780 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7781 // Verify 25% bump heuristic
7782 assert!(feerate_2 * 100 >= feerate_1 * 125);
7786 assert_ne!(feerate_2, 0);
7788 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7789 connect_blocks(&nodes[1], 1);
7791 let mut feerate_3 = 0;
7793 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7794 assert_eq!(node_txn.len(), 1);
7795 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7796 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7797 assert_eq!(node_txn[0].output.len(), 1);
7798 check_spends!(node_txn[0], revoked_txn[0]);
7799 penalty_3 = node_txn[0].txid();
7800 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7801 assert_ne!(penalty_3, penalty_2);
7802 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7803 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7804 // Verify 25% bump heuristic
7805 assert!(feerate_3 * 100 >= feerate_2 * 125);
7809 assert_ne!(feerate_3, 0);
7811 nodes[1].node.get_and_clear_pending_events();
7812 nodes[1].node.get_and_clear_pending_msg_events();
7816 fn test_bump_penalty_txn_on_revoked_htlcs() {
7817 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7818 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7820 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7821 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7826 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7827 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7828 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7829 let scorer = test_utils::TestScorer::with_penalty(0);
7830 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7831 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7832 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7833 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7834 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7835 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7836 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7837 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7839 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7840 assert_eq!(revoked_local_txn[0].input.len(), 1);
7841 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7843 // Revoke local commitment tx
7844 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7846 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7847 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7848 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7849 check_closed_broadcast!(nodes[1], true);
7850 check_added_monitors!(nodes[1], 1);
7851 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7852 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7854 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855 assert_eq!(revoked_htlc_txn.len(), 3);
7856 check_spends!(revoked_htlc_txn[1], chan.3);
7858 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7859 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7860 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7862 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7863 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7864 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7865 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7867 // Broadcast set of revoked txn on A
7868 let hash_128 = connect_blocks(&nodes[0], 40);
7869 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7870 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7871 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7872 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7873 let events = nodes[0].node.get_and_clear_pending_events();
7874 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7876 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7877 _ => panic!("Unexpected event"),
7883 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7884 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7885 // Verify claim tx are spending revoked HTLC txn
7887 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7888 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7889 // which are included in the same block (they are broadcasted because we scan the
7890 // transactions linearly and generate claims as we go, they likely should be removed in the
7892 assert_eq!(node_txn[0].input.len(), 1);
7893 check_spends!(node_txn[0], revoked_local_txn[0]);
7894 assert_eq!(node_txn[1].input.len(), 1);
7895 check_spends!(node_txn[1], revoked_local_txn[0]);
7896 assert_eq!(node_txn[2].input.len(), 1);
7897 check_spends!(node_txn[2], revoked_local_txn[0]);
7899 // Each of the three justice transactions claim a separate (single) output of the three
7900 // available, which we check here:
7901 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7902 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7903 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7905 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7906 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7908 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7909 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7910 // a remote commitment tx has already been confirmed).
7911 check_spends!(node_txn[3], chan.3);
7913 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7914 // output, checked above).
7915 assert_eq!(node_txn[4].input.len(), 2);
7916 assert_eq!(node_txn[4].output.len(), 1);
7917 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7919 first = node_txn[4].txid();
7920 // Store both feerates for later comparison
7921 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7922 feerate_1 = fee_1 * 1000 / node_txn[4].weight() as u64;
7923 penalty_txn = vec![node_txn[2].clone()];
7927 // Connect one more block to see if bumped penalty are issued for HTLC txn
7928 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7929 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7930 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7931 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7933 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7934 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7936 check_spends!(node_txn[0], revoked_local_txn[0]);
7937 check_spends!(node_txn[1], revoked_local_txn[0]);
7938 // Note that these are both bogus - they spend outputs already claimed in block 129:
7939 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7940 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7942 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7943 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7949 // Few more blocks to confirm penalty txn
7950 connect_blocks(&nodes[0], 4);
7951 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7952 let header_144 = connect_blocks(&nodes[0], 9);
7954 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7955 assert_eq!(node_txn.len(), 1);
7957 assert_eq!(node_txn[0].input.len(), 2);
7958 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7959 // Verify bumped tx is different and 25% bump heuristic
7960 assert_ne!(first, node_txn[0].txid());
7961 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7962 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7963 assert!(feerate_2 * 100 > feerate_1 * 125);
7964 let txn = vec![node_txn[0].clone()];
7968 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7969 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7970 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7971 connect_blocks(&nodes[0], 20);
7973 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7974 // We verify than no new transaction has been broadcast because previously
7975 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7976 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7977 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7978 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7979 // up bumped justice generation.
7980 assert_eq!(node_txn.len(), 0);
7983 check_closed_broadcast!(nodes[0], true);
7984 check_added_monitors!(nodes[0], 1);
7988 fn test_bump_penalty_txn_on_remote_commitment() {
7989 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7990 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7993 // Provide preimage for one
7994 // Check aggregation
7996 let chanmon_cfgs = create_chanmon_cfgs(2);
7997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8001 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8002 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
8003 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8005 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8006 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8007 assert_eq!(remote_txn[0].output.len(), 4);
8008 assert_eq!(remote_txn[0].input.len(), 1);
8009 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8011 // Claim a HTLC without revocation (provide B monitor with preimage)
8012 nodes[1].node.claim_funds(payment_preimage);
8013 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
8014 mine_transaction(&nodes[1], &remote_txn[0]);
8015 check_added_monitors!(nodes[1], 2);
8016 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8018 // One or more claim tx should have been broadcast, check it
8022 let feerate_timeout;
8023 let feerate_preimage;
8025 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8026 // 9 transactions including:
8027 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8028 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8029 // 2 * HTLC-Success (one RBF bump we'll check later)
8031 assert_eq!(node_txn.len(), 8);
8032 assert_eq!(node_txn[0].input.len(), 1);
8033 assert_eq!(node_txn[6].input.len(), 1);
8034 check_spends!(node_txn[0], remote_txn[0]);
8035 check_spends!(node_txn[6], remote_txn[0]);
8037 check_spends!(node_txn[1], chan.3);
8038 check_spends!(node_txn[2], node_txn[1]);
8040 if node_txn[0].input[0].previous_output == node_txn[3].input[0].previous_output {
8041 preimage_bump = node_txn[3].clone();
8042 check_spends!(node_txn[3], remote_txn[0]);
8044 assert_eq!(node_txn[1], node_txn[4]);
8045 assert_eq!(node_txn[2], node_txn[5]);
8047 preimage_bump = node_txn[7].clone();
8048 check_spends!(node_txn[7], remote_txn[0]);
8049 assert_eq!(node_txn[0].input[0].previous_output, node_txn[7].input[0].previous_output);
8051 assert_eq!(node_txn[1], node_txn[3]);
8052 assert_eq!(node_txn[2], node_txn[4]);
8055 timeout = node_txn[6].txid();
8056 let index = node_txn[6].input[0].previous_output.vout;
8057 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8058 feerate_timeout = fee * 1000 / node_txn[6].weight() as u64;
8060 preimage = node_txn[0].txid();
8061 let index = node_txn[0].input[0].previous_output.vout;
8062 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8063 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
8067 assert_ne!(feerate_timeout, 0);
8068 assert_ne!(feerate_preimage, 0);
8070 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8071 connect_blocks(&nodes[1], 15);
8073 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8074 assert_eq!(node_txn.len(), 1);
8075 assert_eq!(node_txn[0].input.len(), 1);
8076 assert_eq!(preimage_bump.input.len(), 1);
8077 check_spends!(node_txn[0], remote_txn[0]);
8078 check_spends!(preimage_bump, remote_txn[0]);
8080 let index = preimage_bump.input[0].previous_output.vout;
8081 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8082 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
8083 assert!(new_feerate * 100 > feerate_timeout * 125);
8084 assert_ne!(timeout, preimage_bump.txid());
8086 let index = node_txn[0].input[0].previous_output.vout;
8087 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8088 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
8089 assert!(new_feerate * 100 > feerate_preimage * 125);
8090 assert_ne!(preimage, node_txn[0].txid());
8095 nodes[1].node.get_and_clear_pending_events();
8096 nodes[1].node.get_and_clear_pending_msg_events();
8100 fn test_counterparty_raa_skip_no_crash() {
8101 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8102 // commitment transaction, we would have happily carried on and provided them the next
8103 // commitment transaction based on one RAA forward. This would probably eventually have led to
8104 // channel closure, but it would not have resulted in funds loss. Still, our
8105 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8106 // check simply that the channel is closed in response to such an RAA, but don't check whether
8107 // we decide to punish our counterparty for revoking their funds (as we don't currently
8109 let chanmon_cfgs = create_chanmon_cfgs(2);
8110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8112 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8113 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8115 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8116 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8118 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8120 // Make signer believe we got a counterparty signature, so that it allows the revocation
8121 keys.get_enforcement_state().last_holder_commitment -= 1;
8122 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8124 // Must revoke without gaps
8125 keys.get_enforcement_state().last_holder_commitment -= 1;
8126 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8128 keys.get_enforcement_state().last_holder_commitment -= 1;
8129 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8130 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8132 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8133 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8134 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8135 check_added_monitors!(nodes[1], 1);
8136 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8140 fn test_bump_txn_sanitize_tracking_maps() {
8141 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8142 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8144 let chanmon_cfgs = create_chanmon_cfgs(2);
8145 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8146 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8147 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8149 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8150 // Lock HTLC in both directions
8151 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8152 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8154 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8155 assert_eq!(revoked_local_txn[0].input.len(), 1);
8156 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8158 // Revoke local commitment tx
8159 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8161 // Broadcast set of revoked txn on A
8162 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8163 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8164 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8166 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8167 check_closed_broadcast!(nodes[0], true);
8168 check_added_monitors!(nodes[0], 1);
8169 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8171 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8172 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8173 check_spends!(node_txn[0], revoked_local_txn[0]);
8174 check_spends!(node_txn[1], revoked_local_txn[0]);
8175 check_spends!(node_txn[2], revoked_local_txn[0]);
8176 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8180 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8181 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8182 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8184 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8185 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8186 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8191 fn test_pending_claimed_htlc_no_balance_underflow() {
8192 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8193 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8194 let chanmon_cfgs = create_chanmon_cfgs(2);
8195 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8196 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8197 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8198 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8200 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
8201 nodes[1].node.claim_funds(payment_preimage);
8202 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
8203 check_added_monitors!(nodes[1], 1);
8204 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8206 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8207 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8208 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8209 check_added_monitors!(nodes[0], 1);
8210 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8212 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8213 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8214 // can get our balance.
8216 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8217 // the public key of the only hop. This works around ChannelDetails not showing the
8218 // almost-claimed HTLC as available balance.
8219 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8220 route.payment_params = None; // This is all wrong, but unnecessary
8221 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8222 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8223 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8225 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8229 fn test_channel_conf_timeout() {
8230 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8231 // confirm within 2016 blocks, as recommended by BOLT 2.
8232 let chanmon_cfgs = create_chanmon_cfgs(2);
8233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8237 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8239 // The outbound node should wait forever for confirmation:
8240 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8241 // copied here instead of directly referencing the constant.
8242 connect_blocks(&nodes[0], 2016);
8243 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8245 // The inbound node should fail the channel after exactly 2016 blocks
8246 connect_blocks(&nodes[1], 2015);
8247 check_added_monitors!(nodes[1], 0);
8248 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8250 connect_blocks(&nodes[1], 1);
8251 check_added_monitors!(nodes[1], 1);
8252 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8253 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8254 assert_eq!(close_ev.len(), 1);
8256 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8257 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8258 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8260 _ => panic!("Unexpected event"),
8265 fn test_override_channel_config() {
8266 let chanmon_cfgs = create_chanmon_cfgs(2);
8267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8271 // Node0 initiates a channel to node1 using the override config.
8272 let mut override_config = UserConfig::default();
8273 override_config.channel_handshake_config.our_to_self_delay = 200;
8275 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8277 // Assert the channel created by node0 is using the override config.
8278 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8279 assert_eq!(res.channel_flags, 0);
8280 assert_eq!(res.to_self_delay, 200);
8284 fn test_override_0msat_htlc_minimum() {
8285 let mut zero_config = UserConfig::default();
8286 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
8287 let chanmon_cfgs = create_chanmon_cfgs(2);
8288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8290 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8292 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8293 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8294 assert_eq!(res.htlc_minimum_msat, 1);
8296 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8297 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8298 assert_eq!(res.htlc_minimum_msat, 1);
8302 fn test_channel_update_has_correct_htlc_maximum_msat() {
8303 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
8304 // Bolt 7 specifies that if present `htlc_maximum_msat`:
8305 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
8306 // 90% of the `channel_value`.
8307 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
8309 let mut config_30_percent = UserConfig::default();
8310 config_30_percent.channel_handshake_config.announced_channel = true;
8311 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
8312 let mut config_50_percent = UserConfig::default();
8313 config_50_percent.channel_handshake_config.announced_channel = true;
8314 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
8315 let mut config_95_percent = UserConfig::default();
8316 config_95_percent.channel_handshake_config.announced_channel = true;
8317 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
8318 let mut config_100_percent = UserConfig::default();
8319 config_100_percent.channel_handshake_config.announced_channel = true;
8320 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
8322 let chanmon_cfgs = create_chanmon_cfgs(4);
8323 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8324 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)]);
8325 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8327 let channel_value_satoshis = 100000;
8328 let channel_value_msat = channel_value_satoshis * 1000;
8329 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
8330 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
8331 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
8333 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());
8334 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());
8336 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
8337 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
8338 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_50_percent_msat));
8339 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
8340 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
8341 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_30_percent_msat));
8343 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8344 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
8346 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8347 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
8348 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
8350 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, OptionalField::Present(channel_value_90_percent_msat));
8354 fn test_manually_accept_inbound_channel_request() {
8355 let mut manually_accept_conf = UserConfig::default();
8356 manually_accept_conf.manually_accept_inbound_channels = true;
8357 let chanmon_cfgs = create_chanmon_cfgs(2);
8358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8360 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8362 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8363 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8365 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8367 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8368 // accepting the inbound channel request.
8369 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8371 let events = nodes[1].node.get_and_clear_pending_events();
8373 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8374 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8376 _ => panic!("Unexpected event"),
8379 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8380 assert_eq!(accept_msg_ev.len(), 1);
8382 match accept_msg_ev[0] {
8383 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8384 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8386 _ => panic!("Unexpected event"),
8389 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8391 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8392 assert_eq!(close_msg_ev.len(), 1);
8394 let events = nodes[1].node.get_and_clear_pending_events();
8396 Event::ChannelClosed { user_channel_id, .. } => {
8397 assert_eq!(user_channel_id, 23);
8399 _ => panic!("Unexpected event"),
8404 fn test_manually_reject_inbound_channel_request() {
8405 let mut manually_accept_conf = UserConfig::default();
8406 manually_accept_conf.manually_accept_inbound_channels = true;
8407 let chanmon_cfgs = create_chanmon_cfgs(2);
8408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8410 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8412 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8413 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8415 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8417 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8418 // rejecting the inbound channel request.
8419 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8421 let events = nodes[1].node.get_and_clear_pending_events();
8423 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8424 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8426 _ => panic!("Unexpected event"),
8429 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8430 assert_eq!(close_msg_ev.len(), 1);
8432 match close_msg_ev[0] {
8433 MessageSendEvent::HandleError { ref node_id, .. } => {
8434 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8436 _ => panic!("Unexpected event"),
8438 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8442 fn test_reject_funding_before_inbound_channel_accepted() {
8443 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8444 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8445 // the node operator before the counterparty sends a `FundingCreated` message. If a
8446 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8447 // and the channel should be closed.
8448 let mut manually_accept_conf = UserConfig::default();
8449 manually_accept_conf.manually_accept_inbound_channels = true;
8450 let chanmon_cfgs = create_chanmon_cfgs(2);
8451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8453 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8455 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8456 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8457 let temp_channel_id = res.temporary_channel_id;
8459 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8461 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8462 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8464 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8465 nodes[1].node.get_and_clear_pending_events();
8467 // Get the `AcceptChannel` message of `nodes[1]` without calling
8468 // `ChannelManager::accept_inbound_channel`, which generates a
8469 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8470 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8471 // succeed when `nodes[0]` is passed to it.
8474 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8475 let accept_chan_msg = channel.get_accept_channel_message();
8476 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8479 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8481 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8482 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8484 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8485 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8487 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8488 assert_eq!(close_msg_ev.len(), 1);
8490 let expected_err = "FundingCreated message received before the channel was accepted";
8491 match close_msg_ev[0] {
8492 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8493 assert_eq!(msg.channel_id, temp_channel_id);
8494 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8495 assert_eq!(msg.data, expected_err);
8497 _ => panic!("Unexpected event"),
8500 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8504 fn test_can_not_accept_inbound_channel_twice() {
8505 let mut manually_accept_conf = UserConfig::default();
8506 manually_accept_conf.manually_accept_inbound_channels = true;
8507 let chanmon_cfgs = create_chanmon_cfgs(2);
8508 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8509 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8510 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8512 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8513 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8515 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8517 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8518 // accepting the inbound channel request.
8519 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8521 let events = nodes[1].node.get_and_clear_pending_events();
8523 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8524 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8525 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8527 Err(APIError::APIMisuseError { err }) => {
8528 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8530 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8531 Err(_) => panic!("Unexpected Error"),
8534 _ => panic!("Unexpected event"),
8537 // Ensure that the channel wasn't closed after attempting to accept it twice.
8538 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8539 assert_eq!(accept_msg_ev.len(), 1);
8541 match accept_msg_ev[0] {
8542 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8543 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8545 _ => panic!("Unexpected event"),
8550 fn test_can_not_accept_unknown_inbound_channel() {
8551 let chanmon_cfg = create_chanmon_cfgs(2);
8552 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8553 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8554 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8556 let unknown_channel_id = [0; 32];
8557 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8559 Err(APIError::ChannelUnavailable { err }) => {
8560 assert_eq!(err, "Can't accept a channel that doesn't exist");
8562 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8563 Err(_) => panic!("Unexpected Error"),
8568 fn test_simple_mpp() {
8569 // Simple test of sending a multi-path payment.
8570 let chanmon_cfgs = create_chanmon_cfgs(4);
8571 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8572 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8573 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8575 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8576 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8577 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8578 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8580 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8581 let path = route.paths[0].clone();
8582 route.paths.push(path);
8583 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8584 route.paths[0][0].short_channel_id = chan_1_id;
8585 route.paths[0][1].short_channel_id = chan_3_id;
8586 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8587 route.paths[1][0].short_channel_id = chan_2_id;
8588 route.paths[1][1].short_channel_id = chan_4_id;
8589 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8590 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8594 fn test_preimage_storage() {
8595 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8596 let chanmon_cfgs = create_chanmon_cfgs(2);
8597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8599 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8601 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8604 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8605 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8606 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8607 check_added_monitors!(nodes[0], 1);
8608 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8609 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8610 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8611 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8613 // Note that after leaving the above scope we have no knowledge of any arguments or return
8614 // values from previous calls.
8615 expect_pending_htlcs_forwardable!(nodes[1]);
8616 let events = nodes[1].node.get_and_clear_pending_events();
8617 assert_eq!(events.len(), 1);
8619 Event::PaymentReceived { ref purpose, .. } => {
8621 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8622 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8624 _ => panic!("expected PaymentPurpose::InvoicePayment")
8627 _ => panic!("Unexpected event"),
8632 #[allow(deprecated)]
8633 fn test_secret_timeout() {
8634 // Simple test of payment secret storage time outs. After
8635 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8636 let chanmon_cfgs = create_chanmon_cfgs(2);
8637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8641 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8643 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8645 // We should fail to register the same payment hash twice, at least until we've connected a
8646 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8647 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8648 assert_eq!(err, "Duplicate payment hash");
8649 } else { panic!(); }
8651 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8653 header: BlockHeader {
8655 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8656 merkle_root: Default::default(),
8657 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8661 connect_block(&nodes[1], &block);
8662 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8663 assert_eq!(err, "Duplicate payment hash");
8664 } else { panic!(); }
8666 // If we then connect the second block, we should be able to register the same payment hash
8667 // again (this time getting a new payment secret).
8668 block.header.prev_blockhash = block.header.block_hash();
8669 block.header.time += 1;
8670 connect_block(&nodes[1], &block);
8671 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8672 assert_ne!(payment_secret_1, our_payment_secret);
8675 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8676 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8677 check_added_monitors!(nodes[0], 1);
8678 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8679 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8680 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8681 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8683 // Note that after leaving the above scope we have no knowledge of any arguments or return
8684 // values from previous calls.
8685 expect_pending_htlcs_forwardable!(nodes[1]);
8686 let events = nodes[1].node.get_and_clear_pending_events();
8687 assert_eq!(events.len(), 1);
8689 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8690 assert!(payment_preimage.is_none());
8691 assert_eq!(payment_secret, our_payment_secret);
8692 // We don't actually have the payment preimage with which to claim this payment!
8694 _ => panic!("Unexpected event"),
8699 fn test_bad_secret_hash() {
8700 // Simple test of unregistered payment hash/invalid payment secret handling
8701 let chanmon_cfgs = create_chanmon_cfgs(2);
8702 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8703 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8704 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8706 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8708 let random_payment_hash = PaymentHash([42; 32]);
8709 let random_payment_secret = PaymentSecret([43; 32]);
8710 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8711 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8713 // All the below cases should end up being handled exactly identically, so we macro the
8714 // resulting events.
8715 macro_rules! handle_unknown_invalid_payment_data {
8717 check_added_monitors!(nodes[0], 1);
8718 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8719 let payment_event = SendEvent::from_event(events.pop().unwrap());
8720 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8721 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8723 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8724 // again to process the pending backwards-failure of the HTLC
8725 expect_pending_htlcs_forwardable!(nodes[1]);
8726 expect_pending_htlcs_forwardable!(nodes[1]);
8727 check_added_monitors!(nodes[1], 1);
8729 // We should fail the payment back
8730 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8731 match events.pop().unwrap() {
8732 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8733 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8734 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8736 _ => panic!("Unexpected event"),
8741 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8742 // Error data is the HTLC value (100,000) and current block height
8743 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8745 // Send a payment with the right payment hash but the wrong payment secret
8746 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8747 handle_unknown_invalid_payment_data!();
8748 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8750 // Send a payment with a random payment hash, but the right payment secret
8751 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8752 handle_unknown_invalid_payment_data!();
8753 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8755 // Send a payment with a random payment hash and random payment secret
8756 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8757 handle_unknown_invalid_payment_data!();
8758 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8762 fn test_update_err_monitor_lockdown() {
8763 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8764 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8765 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8767 // This scenario may happen in a watchtower setup, where watchtower process a block height
8768 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8769 // commitment at same time.
8771 let chanmon_cfgs = create_chanmon_cfgs(2);
8772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8774 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8776 // Create some initial channel
8777 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8778 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8780 // Rebalance the network to generate htlc in the two directions
8781 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8783 // Route a HTLC from node 0 to node 1 (but don't settle)
8784 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8786 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8787 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8788 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8789 let persister = test_utils::TestPersister::new();
8791 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8792 let mut w = test_utils::TestVecWriter(Vec::new());
8793 monitor.write(&mut w).unwrap();
8794 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8795 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8796 assert!(new_monitor == *monitor);
8797 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);
8798 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8801 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8802 let block = Block { header, txdata: vec![] };
8803 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8804 // transaction lock time requirements here.
8805 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8806 watchtower.chain_monitor.block_connected(&block, 200);
8808 // Try to update ChannelMonitor
8809 nodes[1].node.claim_funds(preimage);
8810 check_added_monitors!(nodes[1], 1);
8811 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8813 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8814 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8815 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8816 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8817 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8818 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8819 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8820 } else { assert!(false); }
8821 } else { assert!(false); };
8822 // Our local monitor is in-sync and hasn't processed yet timeout
8823 check_added_monitors!(nodes[0], 1);
8824 let events = nodes[0].node.get_and_clear_pending_events();
8825 assert_eq!(events.len(), 1);
8829 fn test_concurrent_monitor_claim() {
8830 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8831 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8832 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8833 // state N+1 confirms. Alice claims output from state N+1.
8835 let chanmon_cfgs = create_chanmon_cfgs(2);
8836 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8837 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8838 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8840 // Create some initial channel
8841 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8842 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8844 // Rebalance the network to generate htlc in the two directions
8845 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8847 // Route a HTLC from node 0 to node 1 (but don't settle)
8848 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8850 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8851 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8852 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8853 let persister = test_utils::TestPersister::new();
8854 let watchtower_alice = {
8855 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8856 let mut w = test_utils::TestVecWriter(Vec::new());
8857 monitor.write(&mut w).unwrap();
8858 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8859 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8860 assert!(new_monitor == *monitor);
8861 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);
8862 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8865 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8866 let block = Block { header, txdata: vec![] };
8867 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8868 // transaction lock time requirements here.
8869 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));
8870 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8872 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8874 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8875 assert_eq!(txn.len(), 2);
8879 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8880 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8881 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8882 let persister = test_utils::TestPersister::new();
8883 let watchtower_bob = {
8884 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8885 let mut w = test_utils::TestVecWriter(Vec::new());
8886 monitor.write(&mut w).unwrap();
8887 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8888 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8889 assert!(new_monitor == *monitor);
8890 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);
8891 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8894 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8895 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8897 // Route another payment to generate another update with still previous HTLC pending
8898 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8900 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8902 check_added_monitors!(nodes[1], 1);
8904 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8905 assert_eq!(updates.update_add_htlcs.len(), 1);
8906 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8907 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8908 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8909 // Watchtower Alice should already have seen the block and reject the update
8910 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8911 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8912 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8913 } else { assert!(false); }
8914 } else { assert!(false); };
8915 // Our local monitor is in-sync and hasn't processed yet timeout
8916 check_added_monitors!(nodes[0], 1);
8918 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8919 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8920 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8922 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8925 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8926 assert_eq!(txn.len(), 2);
8927 bob_state_y = txn[0].clone();
8931 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8932 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8933 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);
8935 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8936 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8937 // the onchain detection of the HTLC output
8938 assert_eq!(htlc_txn.len(), 2);
8939 check_spends!(htlc_txn[0], bob_state_y);
8940 check_spends!(htlc_txn[1], bob_state_y);
8945 fn test_pre_lockin_no_chan_closed_update() {
8946 // Test that if a peer closes a channel in response to a funding_created message we don't
8947 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8950 // Doing so would imply a channel monitor update before the initial channel monitor
8951 // registration, violating our API guarantees.
8953 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8954 // then opening a second channel with the same funding output as the first (which is not
8955 // rejected because the first channel does not exist in the ChannelManager) and closing it
8956 // before receiving funding_signed.
8957 let chanmon_cfgs = create_chanmon_cfgs(2);
8958 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8959 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8960 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8962 // Create an initial channel
8963 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8964 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8965 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8966 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8967 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8969 // Move the first channel through the funding flow...
8970 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8972 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8973 check_added_monitors!(nodes[0], 0);
8975 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8976 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8977 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8978 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8979 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8983 fn test_htlc_no_detection() {
8984 // This test is a mutation to underscore the detection logic bug we had
8985 // before #653. HTLC value routed is above the remaining balance, thus
8986 // inverting HTLC and `to_remote` output. HTLC will come second and
8987 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8988 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8989 // outputs order detection for correct spending children filtring.
8991 let chanmon_cfgs = create_chanmon_cfgs(2);
8992 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8993 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8994 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8996 // Create some initial channels
8997 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8999 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
9000 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
9001 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
9002 assert_eq!(local_txn[0].input.len(), 1);
9003 assert_eq!(local_txn[0].output.len(), 3);
9004 check_spends!(local_txn[0], chan_1.3);
9006 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
9007 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9008 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
9009 // We deliberately connect the local tx twice as this should provoke a failure calling
9010 // this test before #653 fix.
9011 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);
9012 check_closed_broadcast!(nodes[0], true);
9013 check_added_monitors!(nodes[0], 1);
9014 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
9015 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
9017 let htlc_timeout = {
9018 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
9019 assert_eq!(node_txn[1].input.len(), 1);
9020 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9021 check_spends!(node_txn[1], local_txn[0]);
9025 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
9026 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
9027 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
9028 expect_payment_failed!(nodes[0], our_payment_hash, true);
9031 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
9032 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
9033 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
9034 // Carol, Alice would be the upstream node, and Carol the downstream.)
9036 // Steps of the test:
9037 // 1) Alice sends a HTLC to Carol through Bob.
9038 // 2) Carol doesn't settle the HTLC.
9039 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
9040 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
9041 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
9042 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
9043 // 5) Carol release the preimage to Bob off-chain.
9044 // 6) Bob claims the offered output on the broadcasted commitment.
9045 let chanmon_cfgs = create_chanmon_cfgs(3);
9046 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9047 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9048 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9050 // Create some initial channels
9051 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9052 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9054 // Steps (1) and (2):
9055 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
9056 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
9058 // Check that Alice's commitment transaction now contains an output for this HTLC.
9059 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
9060 check_spends!(alice_txn[0], chan_ab.3);
9061 assert_eq!(alice_txn[0].output.len(), 2);
9062 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
9063 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
9064 assert_eq!(alice_txn.len(), 2);
9066 // Steps (3) and (4):
9067 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
9068 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
9069 let mut force_closing_node = 0; // Alice force-closes
9070 let mut counterparty_node = 1; // Bob if Alice force-closes
9073 if !broadcast_alice {
9074 force_closing_node = 1;
9075 counterparty_node = 0;
9077 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
9078 check_closed_broadcast!(nodes[force_closing_node], true);
9079 check_added_monitors!(nodes[force_closing_node], 1);
9080 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
9081 if go_onchain_before_fulfill {
9082 let txn_to_broadcast = match broadcast_alice {
9083 true => alice_txn.clone(),
9084 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
9086 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9087 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9088 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9089 if broadcast_alice {
9090 check_closed_broadcast!(nodes[1], true);
9091 check_added_monitors!(nodes[1], 1);
9092 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9094 assert_eq!(bob_txn.len(), 1);
9095 check_spends!(bob_txn[0], chan_ab.3);
9099 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
9100 // process of removing the HTLC from their commitment transactions.
9101 nodes[2].node.claim_funds(payment_preimage);
9102 check_added_monitors!(nodes[2], 1);
9103 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
9105 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
9106 assert!(carol_updates.update_add_htlcs.is_empty());
9107 assert!(carol_updates.update_fail_htlcs.is_empty());
9108 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
9109 assert!(carol_updates.update_fee.is_none());
9110 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
9112 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
9113 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
9114 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
9115 if !go_onchain_before_fulfill && broadcast_alice {
9116 let events = nodes[1].node.get_and_clear_pending_msg_events();
9117 assert_eq!(events.len(), 1);
9119 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
9120 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9122 _ => panic!("Unexpected event"),
9125 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
9126 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
9127 // Carol<->Bob's updated commitment transaction info.
9128 check_added_monitors!(nodes[1], 2);
9130 let events = nodes[1].node.get_and_clear_pending_msg_events();
9131 assert_eq!(events.len(), 2);
9132 let bob_revocation = match events[0] {
9133 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9134 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9137 _ => panic!("Unexpected event"),
9139 let bob_updates = match events[1] {
9140 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
9141 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
9144 _ => panic!("Unexpected event"),
9147 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
9148 check_added_monitors!(nodes[2], 1);
9149 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
9150 check_added_monitors!(nodes[2], 1);
9152 let events = nodes[2].node.get_and_clear_pending_msg_events();
9153 assert_eq!(events.len(), 1);
9154 let carol_revocation = match events[0] {
9155 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9156 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9159 _ => panic!("Unexpected event"),
9161 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9162 check_added_monitors!(nodes[1], 1);
9164 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9165 // here's where we put said channel's commitment tx on-chain.
9166 let mut txn_to_broadcast = alice_txn.clone();
9167 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9168 if !go_onchain_before_fulfill {
9169 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9170 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9171 // If Bob was the one to force-close, he will have already passed these checks earlier.
9172 if broadcast_alice {
9173 check_closed_broadcast!(nodes[1], true);
9174 check_added_monitors!(nodes[1], 1);
9175 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9177 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9178 if broadcast_alice {
9179 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9180 // new block being connected. The ChannelManager being notified triggers a monitor update,
9181 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9182 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9184 assert_eq!(bob_txn.len(), 3);
9185 check_spends!(bob_txn[1], chan_ab.3);
9187 assert_eq!(bob_txn.len(), 2);
9188 check_spends!(bob_txn[0], chan_ab.3);
9193 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9194 // broadcasted commitment transaction.
9196 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9197 if go_onchain_before_fulfill {
9198 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9199 assert_eq!(bob_txn.len(), 2);
9201 let script_weight = match broadcast_alice {
9202 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9203 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9205 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9206 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9207 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9208 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9209 if broadcast_alice && !go_onchain_before_fulfill {
9210 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9211 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9213 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9214 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9220 fn test_onchain_htlc_settlement_after_close() {
9221 do_test_onchain_htlc_settlement_after_close(true, true);
9222 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9223 do_test_onchain_htlc_settlement_after_close(true, false);
9224 do_test_onchain_htlc_settlement_after_close(false, false);
9228 fn test_duplicate_chan_id() {
9229 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9230 // already open we reject it and keep the old channel.
9232 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9233 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9234 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9235 // updating logic for the existing channel.
9236 let chanmon_cfgs = create_chanmon_cfgs(2);
9237 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9238 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9239 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9241 // Create an initial channel
9242 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9243 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9244 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9245 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()));
9247 // Try to create a second channel with the same temporary_channel_id as the first and check
9248 // that it is rejected.
9249 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9251 let events = nodes[1].node.get_and_clear_pending_msg_events();
9252 assert_eq!(events.len(), 1);
9254 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9255 // Technically, at this point, nodes[1] would be justified in thinking both the
9256 // first (valid) and second (invalid) channels are closed, given they both have
9257 // the same non-temporary channel_id. However, currently we do not, so we just
9258 // move forward with it.
9259 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9260 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9262 _ => panic!("Unexpected event"),
9266 // Move the first channel through the funding flow...
9267 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9269 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9270 check_added_monitors!(nodes[0], 0);
9272 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9273 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9275 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9276 assert_eq!(added_monitors.len(), 1);
9277 assert_eq!(added_monitors[0].0, funding_output);
9278 added_monitors.clear();
9280 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9282 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9283 let channel_id = funding_outpoint.to_channel_id();
9285 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9288 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9289 // Technically this is allowed by the spec, but we don't support it and there's little reason
9290 // to. Still, it shouldn't cause any other issues.
9291 open_chan_msg.temporary_channel_id = channel_id;
9292 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9294 let events = nodes[1].node.get_and_clear_pending_msg_events();
9295 assert_eq!(events.len(), 1);
9297 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9298 // Technically, at this point, nodes[1] would be justified in thinking both
9299 // channels are closed, but currently we do not, so we just move forward with it.
9300 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9301 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9303 _ => panic!("Unexpected event"),
9307 // Now try to create a second channel which has a duplicate funding output.
9308 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9309 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9310 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9311 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()));
9312 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9314 let funding_created = {
9315 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9316 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
9317 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9318 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9319 // channelmanager in a possibly nonsense state instead).
9320 let mut as_chan = a_channel_lock.by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
9321 let logger = test_utils::TestLogger::new();
9322 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9324 check_added_monitors!(nodes[0], 0);
9325 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9326 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9327 // still needs to be cleared here.
9328 check_added_monitors!(nodes[1], 1);
9330 // ...still, nodes[1] will reject the duplicate channel.
9332 let events = nodes[1].node.get_and_clear_pending_msg_events();
9333 assert_eq!(events.len(), 1);
9335 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9336 // Technically, at this point, nodes[1] would be justified in thinking both
9337 // channels are closed, but currently we do not, so we just move forward with it.
9338 assert_eq!(msg.channel_id, channel_id);
9339 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9341 _ => panic!("Unexpected event"),
9345 // finally, finish creating the original channel and send a payment over it to make sure
9346 // everything is functional.
9347 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9349 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9350 assert_eq!(added_monitors.len(), 1);
9351 assert_eq!(added_monitors[0].0, funding_output);
9352 added_monitors.clear();
9355 let events_4 = nodes[0].node.get_and_clear_pending_events();
9356 assert_eq!(events_4.len(), 0);
9357 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9358 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9360 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9361 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9362 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9363 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9367 fn test_error_chans_closed() {
9368 // Test that we properly handle error messages, closing appropriate channels.
9370 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9371 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9372 // we can test various edge cases around it to ensure we don't regress.
9373 let chanmon_cfgs = create_chanmon_cfgs(3);
9374 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9375 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9376 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9378 // Create some initial channels
9379 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9380 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9381 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9383 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9384 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9385 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9387 // Closing a channel from a different peer has no effect
9388 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9389 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9391 // Closing one channel doesn't impact others
9392 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9393 check_added_monitors!(nodes[0], 1);
9394 check_closed_broadcast!(nodes[0], false);
9395 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9396 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9397 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9398 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);
9399 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);
9401 // A null channel ID should close all channels
9402 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9403 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9404 check_added_monitors!(nodes[0], 2);
9405 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9406 let events = nodes[0].node.get_and_clear_pending_msg_events();
9407 assert_eq!(events.len(), 2);
9409 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9410 assert_eq!(msg.contents.flags & 2, 2);
9412 _ => panic!("Unexpected event"),
9415 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9416 assert_eq!(msg.contents.flags & 2, 2);
9418 _ => panic!("Unexpected event"),
9420 // Note that at this point users of a standard PeerHandler will end up calling
9421 // peer_disconnected with no_connection_possible set to false, duplicating the
9422 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9423 // users with their own peer handling logic. We duplicate the call here, however.
9424 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9425 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9427 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9428 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9429 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9433 fn test_invalid_funding_tx() {
9434 // Test that we properly handle invalid funding transactions sent to us from a peer.
9436 // Previously, all other major lightning implementations had failed to properly sanitize
9437 // funding transactions from their counterparties, leading to a multi-implementation critical
9438 // security vulnerability (though we always sanitized properly, we've previously had
9439 // un-released crashes in the sanitization process).
9441 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9442 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9443 // gave up on it. We test this here by generating such a transaction.
9444 let chanmon_cfgs = create_chanmon_cfgs(2);
9445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9447 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9449 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9450 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()));
9451 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()));
9453 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9455 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9456 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9457 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9459 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9460 assert!(chan_utils::HTLCType::scriptlen_to_htlctype(wit_program.len()).unwrap() ==
9461 chan_utils::HTLCType::AcceptedHTLC);
9463 let wit_program_script: Script = wit_program.clone().into();
9464 for output in tx.output.iter_mut() {
9465 // Make the confirmed funding transaction have a bogus script_pubkey
9466 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9469 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9470 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()));
9471 check_added_monitors!(nodes[1], 1);
9473 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()));
9474 check_added_monitors!(nodes[0], 1);
9476 let events_1 = nodes[0].node.get_and_clear_pending_events();
9477 assert_eq!(events_1.len(), 0);
9479 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9480 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9481 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9483 let expected_err = "funding tx had wrong script/value or output index";
9484 confirm_transaction_at(&nodes[1], &tx, 1);
9485 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9486 check_added_monitors!(nodes[1], 1);
9487 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9488 assert_eq!(events_2.len(), 1);
9489 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9490 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9491 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9492 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9493 } else { panic!(); }
9494 } else { panic!(); }
9495 assert_eq!(nodes[1].node.list_channels().len(), 0);
9497 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9498 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9499 // as its not 32 bytes long.
9500 let mut spend_tx = Transaction {
9501 version: 2i32, lock_time: 0,
9502 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9503 previous_output: BitcoinOutPoint {
9507 script_sig: Script::new(),
9508 sequence: 0xfffffffd,
9509 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9511 output: vec![TxOut {
9513 script_pubkey: Script::new(),
9516 check_spends!(spend_tx, tx);
9517 mine_transaction(&nodes[1], &spend_tx);
9520 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9521 // In the first version of the chain::Confirm interface, after a refactor was made to not
9522 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9523 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9524 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9525 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9526 // spending transaction until height N+1 (or greater). This was due to the way
9527 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9528 // spending transaction at the height the input transaction was confirmed at, not whether we
9529 // should broadcast a spending transaction at the current height.
9530 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9531 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9532 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9533 // until we learned about an additional block.
9535 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9536 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9537 let chanmon_cfgs = create_chanmon_cfgs(3);
9538 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9539 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9540 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9541 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9543 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9544 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9545 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9546 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9547 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9549 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9550 check_closed_broadcast!(nodes[1], true);
9551 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9552 check_added_monitors!(nodes[1], 1);
9553 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9554 assert_eq!(node_txn.len(), 1);
9556 let conf_height = nodes[1].best_block_info().1;
9557 if !test_height_before_timelock {
9558 connect_blocks(&nodes[1], 24 * 6);
9560 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9561 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9562 if test_height_before_timelock {
9563 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9564 // generate any events or broadcast any transactions
9565 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9566 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9568 // We should broadcast an HTLC transaction spending our funding transaction first
9569 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9570 assert_eq!(spending_txn.len(), 2);
9571 assert_eq!(spending_txn[0], node_txn[0]);
9572 check_spends!(spending_txn[1], node_txn[0]);
9573 // We should also generate a SpendableOutputs event with the to_self output (as its
9575 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9576 assert_eq!(descriptor_spend_txn.len(), 1);
9578 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9579 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9580 // additional block built on top of the current chain.
9581 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9582 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9583 expect_pending_htlcs_forwardable!(nodes[1]);
9584 check_added_monitors!(nodes[1], 1);
9586 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9587 assert!(updates.update_add_htlcs.is_empty());
9588 assert!(updates.update_fulfill_htlcs.is_empty());
9589 assert_eq!(updates.update_fail_htlcs.len(), 1);
9590 assert!(updates.update_fail_malformed_htlcs.is_empty());
9591 assert!(updates.update_fee.is_none());
9592 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9593 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9594 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9599 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9600 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9601 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9605 fn test_forwardable_regen() {
9606 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9607 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9609 // We test it for both payment receipt and payment forwarding.
9611 let chanmon_cfgs = create_chanmon_cfgs(3);
9612 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9613 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9614 let persister: test_utils::TestPersister;
9615 let new_chain_monitor: test_utils::TestChainMonitor;
9616 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9617 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9618 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9619 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9621 // First send a payment to nodes[1]
9622 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9623 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9624 check_added_monitors!(nodes[0], 1);
9626 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9627 assert_eq!(events.len(), 1);
9628 let payment_event = SendEvent::from_event(events.pop().unwrap());
9629 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9630 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9632 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9634 // Next send a payment which is forwarded by nodes[1]
9635 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9636 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9637 check_added_monitors!(nodes[0], 1);
9639 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9640 assert_eq!(events.len(), 1);
9641 let payment_event = SendEvent::from_event(events.pop().unwrap());
9642 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9643 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9645 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9647 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9649 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9650 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9651 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9653 let nodes_1_serialized = nodes[1].node.encode();
9654 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9655 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9656 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9657 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9659 persister = test_utils::TestPersister::new();
9660 let keys_manager = &chanmon_cfgs[1].keys_manager;
9661 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);
9662 nodes[1].chain_monitor = &new_chain_monitor;
9664 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9665 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9666 &mut chan_0_monitor_read, keys_manager).unwrap();
9667 assert!(chan_0_monitor_read.is_empty());
9668 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9669 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9670 &mut chan_1_monitor_read, keys_manager).unwrap();
9671 assert!(chan_1_monitor_read.is_empty());
9673 let mut nodes_1_read = &nodes_1_serialized[..];
9674 let (_, nodes_1_deserialized_tmp) = {
9675 let mut channel_monitors = HashMap::new();
9676 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9677 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9678 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9679 default_config: UserConfig::default(),
9681 fee_estimator: node_cfgs[1].fee_estimator,
9682 chain_monitor: nodes[1].chain_monitor,
9683 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9684 logger: nodes[1].logger,
9688 nodes_1_deserialized = nodes_1_deserialized_tmp;
9689 assert!(nodes_1_read.is_empty());
9691 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9692 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9693 nodes[1].node = &nodes_1_deserialized;
9694 check_added_monitors!(nodes[1], 2);
9696 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9697 // Note that nodes[1] and nodes[2] resend their channel_ready here since they haven't updated
9698 // the commitment state.
9699 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9701 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9703 expect_pending_htlcs_forwardable!(nodes[1]);
9704 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9705 check_added_monitors!(nodes[1], 1);
9707 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9708 assert_eq!(events.len(), 1);
9709 let payment_event = SendEvent::from_event(events.pop().unwrap());
9710 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9711 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9712 expect_pending_htlcs_forwardable!(nodes[2]);
9713 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9715 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9716 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9719 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9720 let chanmon_cfgs = create_chanmon_cfgs(2);
9721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9723 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9725 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9727 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9728 .with_features(InvoiceFeatures::known());
9729 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9731 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9734 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9735 check_added_monitors!(nodes[0], 1);
9736 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9737 assert_eq!(events.len(), 1);
9738 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9739 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9740 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9742 expect_pending_htlcs_forwardable!(nodes[1]);
9743 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
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);
9753 // At this point, nodes[1] would notice it has too much value for the payment. It will
9754 // assume the second is a privacy attack (no longer particularly relevant
9755 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9756 // the first HTLC delivered above.
9759 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9760 nodes[1].node.process_pending_htlc_forwards();
9762 if test_for_second_fail_panic {
9763 // Now we go fail back the first HTLC from the user end.
9764 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9766 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9767 nodes[1].node.process_pending_htlc_forwards();
9769 check_added_monitors!(nodes[1], 1);
9770 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9771 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9773 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9774 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9775 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9777 let failure_events = nodes[0].node.get_and_clear_pending_events();
9778 assert_eq!(failure_events.len(), 2);
9779 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9780 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9782 // Let the second HTLC fail and claim the first
9783 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9784 nodes[1].node.process_pending_htlc_forwards();
9786 check_added_monitors!(nodes[1], 1);
9787 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9788 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9789 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9791 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9793 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9798 fn test_dup_htlc_second_fail_panic() {
9799 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9800 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9801 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9802 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9803 do_test_dup_htlc_second_rejected(true);
9807 fn test_dup_htlc_second_rejected() {
9808 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9809 // simply reject the second HTLC but are still able to claim the first HTLC.
9810 do_test_dup_htlc_second_rejected(false);
9814 fn test_inconsistent_mpp_params() {
9815 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9816 // such HTLC and allow the second to stay.
9817 let chanmon_cfgs = create_chanmon_cfgs(4);
9818 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9819 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9820 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9822 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9823 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9824 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9825 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9827 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
9828 .with_features(InvoiceFeatures::known());
9829 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9830 assert_eq!(route.paths.len(), 2);
9831 route.paths.sort_by(|path_a, _| {
9832 // Sort the path so that the path through nodes[1] comes first
9833 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9834 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9836 let payment_params_opt = Some(payment_params);
9838 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9840 let cur_height = nodes[0].best_block_info().1;
9841 let payment_id = PaymentId([42; 32]);
9843 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();
9844 check_added_monitors!(nodes[0], 1);
9846 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9847 assert_eq!(events.len(), 1);
9848 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9850 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9853 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();
9854 check_added_monitors!(nodes[0], 1);
9856 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9857 assert_eq!(events.len(), 1);
9858 let payment_event = SendEvent::from_event(events.pop().unwrap());
9860 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9861 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9863 expect_pending_htlcs_forwardable!(nodes[2]);
9864 check_added_monitors!(nodes[2], 1);
9866 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9867 assert_eq!(events.len(), 1);
9868 let payment_event = SendEvent::from_event(events.pop().unwrap());
9870 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9871 check_added_monitors!(nodes[3], 0);
9872 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9874 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9875 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9876 // post-payment_secrets) and fail back the new HTLC.
9878 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9879 nodes[3].node.process_pending_htlc_forwards();
9880 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9881 nodes[3].node.process_pending_htlc_forwards();
9883 check_added_monitors!(nodes[3], 1);
9885 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9886 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9887 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9889 expect_pending_htlcs_forwardable!(nodes[2]);
9890 check_added_monitors!(nodes[2], 1);
9892 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9893 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9894 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9896 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9898 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();
9899 check_added_monitors!(nodes[0], 1);
9901 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9902 assert_eq!(events.len(), 1);
9903 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9905 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9909 fn test_keysend_payments_to_public_node() {
9910 let chanmon_cfgs = create_chanmon_cfgs(2);
9911 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9912 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9913 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9915 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9916 let network_graph = nodes[0].network_graph;
9917 let payer_pubkey = nodes[0].node.get_our_node_id();
9918 let payee_pubkey = nodes[1].node.get_our_node_id();
9919 let route_params = RouteParameters {
9920 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9921 final_value_msat: 10000,
9922 final_cltv_expiry_delta: 40,
9924 let scorer = test_utils::TestScorer::with_penalty(0);
9925 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9926 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9928 let test_preimage = PaymentPreimage([42; 32]);
9929 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9930 check_added_monitors!(nodes[0], 1);
9931 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9932 assert_eq!(events.len(), 1);
9933 let event = events.pop().unwrap();
9934 let path = vec![&nodes[1]];
9935 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9936 claim_payment(&nodes[0], &path, test_preimage);
9940 fn test_keysend_payments_to_private_node() {
9941 let chanmon_cfgs = create_chanmon_cfgs(2);
9942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9944 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9946 let payer_pubkey = nodes[0].node.get_our_node_id();
9947 let payee_pubkey = nodes[1].node.get_our_node_id();
9948 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9949 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9951 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9952 let route_params = RouteParameters {
9953 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9954 final_value_msat: 10000,
9955 final_cltv_expiry_delta: 40,
9957 let network_graph = nodes[0].network_graph;
9958 let first_hops = nodes[0].node.list_usable_channels();
9959 let scorer = test_utils::TestScorer::with_penalty(0);
9960 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9961 let route = find_route(
9962 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9963 nodes[0].logger, &scorer, &random_seed_bytes
9966 let test_preimage = PaymentPreimage([42; 32]);
9967 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9968 check_added_monitors!(nodes[0], 1);
9969 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9970 assert_eq!(events.len(), 1);
9971 let event = events.pop().unwrap();
9972 let path = vec![&nodes[1]];
9973 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9974 claim_payment(&nodes[0], &path, test_preimage);
9978 fn test_double_partial_claim() {
9979 // Test what happens if a node receives a payment, generates a PaymentReceived event, the HTLCs
9980 // time out, the sender resends only some of the MPP parts, then the user processes the
9981 // PaymentReceived event, ensuring they don't inadvertently claim only part of the full payment
9983 let chanmon_cfgs = create_chanmon_cfgs(4);
9984 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9985 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9986 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9988 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9989 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9990 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9991 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
9993 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9994 assert_eq!(route.paths.len(), 2);
9995 route.paths.sort_by(|path_a, _| {
9996 // Sort the path so that the path through nodes[1] comes first
9997 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9998 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10001 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
10002 // nodes[3] has now received a PaymentReceived event...which it will take some (exorbitant)
10003 // amount of time to respond to.
10005 // Connect some blocks to time out the payment
10006 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
10007 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
10009 expect_pending_htlcs_forwardable!(nodes[3]);
10011 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
10013 // nodes[1] now retries one of the two paths...
10014 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10015 check_added_monitors!(nodes[0], 2);
10017 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10018 assert_eq!(events.len(), 2);
10019 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
10021 // At this point nodes[3] has received one half of the payment, and the user goes to handle
10022 // that PaymentReceived event they got hours ago and never handled...we should refuse to claim.
10023 nodes[3].node.claim_funds(payment_preimage);
10024 check_added_monitors!(nodes[3], 0);
10025 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
10028 fn do_test_partial_claim_before_restart(persist_both_monitors: bool) {
10029 // Test what happens if a node receives an MPP payment, claims it, but crashes before
10030 // persisting the ChannelManager. If `persist_both_monitors` is false, also crash after only
10031 // updating one of the two channels' ChannelMonitors. As a result, on startup, we'll (a) still
10032 // have the PaymentReceived event, (b) have one (or two) channel(s) that goes on chain with the
10033 // HTLC preimage in them, and (c) optionally have one channel that is live off-chain but does
10034 // not have the preimage tied to the still-pending HTLC.
10036 // To get to the correct state, on startup we should propagate the preimage to the
10037 // still-off-chain channel, claiming the HTLC as soon as the peer connects, with the monitor
10038 // receiving the preimage without a state update.
10040 // Further, we should generate a `PaymentClaimed` event to inform the user that the payment was
10041 // definitely claimed.
10042 let chanmon_cfgs = create_chanmon_cfgs(4);
10043 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
10044 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
10046 let persister: test_utils::TestPersister;
10047 let new_chain_monitor: test_utils::TestChainMonitor;
10048 let nodes_3_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
10050 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
10052 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10053 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0, InitFeatures::known(), InitFeatures::known());
10054 let chan_id_persisted = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10055 let chan_id_not_persisted = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known()).2;
10057 // Create an MPP route for 15k sats, more than the default htlc-max of 10%
10058 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
10059 assert_eq!(route.paths.len(), 2);
10060 route.paths.sort_by(|path_a, _| {
10061 // Sort the path so that the path through nodes[1] comes first
10062 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
10063 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
10066 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10067 check_added_monitors!(nodes[0], 2);
10069 // Send the payment through to nodes[3] *without* clearing the PaymentReceived event
10070 let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
10071 assert_eq!(send_events.len(), 2);
10072 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);
10073 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);
10075 // Now that we have an MPP payment pending, get the latest encoded copies of nodes[3]'s
10076 // monitors and ChannelManager, for use later, if we don't want to persist both monitors.
10077 let mut original_monitor = test_utils::TestVecWriter(Vec::new());
10078 if !persist_both_monitors {
10079 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10080 if outpoint.to_channel_id() == chan_id_not_persisted {
10081 assert!(original_monitor.0.is_empty());
10082 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10087 let mut original_manager = test_utils::TestVecWriter(Vec::new());
10088 nodes[3].node.write(&mut original_manager).unwrap();
10090 expect_payment_received!(nodes[3], payment_hash, payment_secret, 15_000_000);
10092 nodes[3].node.claim_funds(payment_preimage);
10093 check_added_monitors!(nodes[3], 2);
10094 expect_payment_claimed!(nodes[3], payment_hash, 15_000_000);
10096 // Now fetch one of the two updated ChannelMonitors from nodes[3], and restart pretending we
10097 // crashed in between the two persistence calls - using one old ChannelMonitor and one new one,
10098 // with the old ChannelManager.
10099 let mut updated_monitor = test_utils::TestVecWriter(Vec::new());
10100 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10101 if outpoint.to_channel_id() == chan_id_persisted {
10102 assert!(updated_monitor.0.is_empty());
10103 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut updated_monitor).unwrap();
10106 // If `persist_both_monitors` is set, get the second monitor here as well
10107 if persist_both_monitors {
10108 for outpoint in nodes[3].chain_monitor.chain_monitor.list_monitors() {
10109 if outpoint.to_channel_id() == chan_id_not_persisted {
10110 assert!(original_monitor.0.is_empty());
10111 nodes[3].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap().write(&mut original_monitor).unwrap();
10116 // Now restart nodes[3].
10117 persister = test_utils::TestPersister::new();
10118 let keys_manager = &chanmon_cfgs[3].keys_manager;
10119 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);
10120 nodes[3].chain_monitor = &new_chain_monitor;
10121 let mut monitors = Vec::new();
10122 for mut monitor_data in [original_monitor, updated_monitor].iter() {
10123 let (_, mut deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut &monitor_data.0[..], keys_manager).unwrap();
10124 monitors.push(deserialized_monitor);
10127 let config = UserConfig::default();
10128 nodes_3_deserialized = {
10129 let mut channel_monitors = HashMap::new();
10130 for monitor in monitors.iter_mut() {
10131 channel_monitors.insert(monitor.get_funding_txo().0, monitor);
10133 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut &original_manager.0[..], ChannelManagerReadArgs {
10134 default_config: config,
10136 fee_estimator: node_cfgs[3].fee_estimator,
10137 chain_monitor: nodes[3].chain_monitor,
10138 tx_broadcaster: nodes[3].tx_broadcaster.clone(),
10139 logger: nodes[3].logger,
10143 nodes[3].node = &nodes_3_deserialized;
10145 for monitor in monitors {
10146 // On startup the preimage should have been copied into the non-persisted monitor:
10147 assert!(monitor.get_stored_preimages().contains_key(&payment_hash));
10148 nodes[3].chain_monitor.watch_channel(monitor.get_funding_txo().0.clone(), monitor).unwrap();
10150 check_added_monitors!(nodes[3], 2);
10152 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10153 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), false);
10155 // During deserialization, we should have closed one channel and broadcast its latest
10156 // commitment transaction. We should also still have the original PaymentReceived event we
10157 // never finished processing.
10158 let events = nodes[3].node.get_and_clear_pending_events();
10159 assert_eq!(events.len(), if persist_both_monitors { 4 } else { 3 });
10160 if let Event::PaymentReceived { amount_msat: 15_000_000, .. } = events[0] { } else { panic!(); }
10161 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[1] { } else { panic!(); }
10162 if persist_both_monitors {
10163 if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[2] { } else { panic!(); }
10166 // On restart, we should also get a duplicate PaymentClaimed event as we persisted the
10167 // ChannelManager prior to handling the original one.
10168 if let Event::PaymentClaimed { payment_hash: our_payment_hash, amount_msat: 15_000_000, .. } =
10169 events[if persist_both_monitors { 3 } else { 2 }]
10171 assert_eq!(payment_hash, our_payment_hash);
10172 } else { panic!(); }
10174 assert_eq!(nodes[3].node.list_channels().len(), if persist_both_monitors { 0 } else { 1 });
10175 if !persist_both_monitors {
10176 // If one of the two channels is still live, reveal the payment preimage over it.
10178 nodes[3].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10179 let reestablish_1 = get_chan_reestablish_msgs!(nodes[3], nodes[2]);
10180 nodes[2].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
10181 let reestablish_2 = get_chan_reestablish_msgs!(nodes[2], nodes[3]);
10183 nodes[2].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish_1[0]);
10184 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
10185 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
10187 nodes[3].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &reestablish_2[0]);
10189 // Once we call `get_and_clear_pending_msg_events` the holding cell is cleared and the HTLC
10190 // claim should fly.
10191 let ds_msgs = nodes[3].node.get_and_clear_pending_msg_events();
10192 check_added_monitors!(nodes[3], 1);
10193 assert_eq!(ds_msgs.len(), 2);
10194 if let MessageSendEvent::SendChannelUpdate { .. } = ds_msgs[1] {} else { panic!(); }
10196 let cs_updates = match ds_msgs[0] {
10197 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
10198 nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
10199 check_added_monitors!(nodes[2], 1);
10200 let cs_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
10201 expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
10202 commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
10208 nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &cs_updates.update_fulfill_htlcs[0]);
10209 commitment_signed_dance!(nodes[0], nodes[2], cs_updates.commitment_signed, false, true);
10210 expect_payment_sent!(nodes[0], payment_preimage);
10215 fn test_partial_claim_before_restart() {
10216 do_test_partial_claim_before_restart(false);
10217 do_test_partial_claim_before_restart(true);
10220 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
10221 #[derive(Clone, Copy, PartialEq)]
10222 enum ExposureEvent {
10223 /// Breach occurs at HTLC forwarding (see `send_htlc`)
10225 /// Breach occurs at HTLC reception (see `update_add_htlc`)
10227 /// Breach occurs at outbound update_fee (see `send_update_fee`)
10228 AtUpdateFeeOutbound,
10231 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
10232 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
10235 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
10236 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
10237 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
10238 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
10239 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
10240 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
10241 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
10242 // might be available again for HTLC processing once the dust bandwidth has cleared up.
10244 let chanmon_cfgs = create_chanmon_cfgs(2);
10245 let mut config = test_default_channel_config();
10246 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
10247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
10249 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10251 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
10252 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10253 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
10254 open_channel.max_accepted_htlcs = 60;
10256 open_channel.dust_limit_satoshis = 546;
10258 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
10259 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10260 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
10262 let opt_anchors = false;
10264 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
10267 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
10268 chan.holder_dust_limit_satoshis = 546;
10272 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
10273 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()));
10274 check_added_monitors!(nodes[1], 1);
10276 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()));
10277 check_added_monitors!(nodes[0], 1);
10279 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
10280 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
10281 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
10283 let dust_buffer_feerate = {
10284 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
10285 let chan = chan_lock.by_id.get(&channel_id).unwrap();
10286 chan.get_dust_buffer_feerate(None) as u64
10288 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;
10289 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
10291 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;
10292 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
10294 let dust_htlc_on_counterparty_tx: u64 = 25;
10295 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
10298 if dust_outbound_balance {
10299 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10300 // Outbound dust balance: 4372 sats
10301 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
10302 for i in 0..dust_outbound_htlc_on_holder_tx {
10303 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
10304 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10307 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
10308 // Inbound dust balance: 4372 sats
10309 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
10310 for _ in 0..dust_inbound_htlc_on_holder_tx {
10311 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
10315 if dust_outbound_balance {
10316 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10317 // Outbound dust balance: 5000 sats
10318 for i in 0..dust_htlc_on_counterparty_tx {
10319 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
10320 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
10323 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
10324 // Inbound dust balance: 5000 sats
10325 for _ in 0..dust_htlc_on_counterparty_tx {
10326 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
10331 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
10332 if exposure_breach_event == ExposureEvent::AtHTLCForward {
10333 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 });
10334 let mut config = UserConfig::default();
10335 // With default dust exposure: 5000 sats
10337 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
10338 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
10339 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)));
10341 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)));
10343 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
10344 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 });
10345 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
10346 check_added_monitors!(nodes[1], 1);
10347 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
10348 assert_eq!(events.len(), 1);
10349 let payment_event = SendEvent::from_event(events.remove(0));
10350 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
10351 // With default dust exposure: 5000 sats
10353 // Outbound dust balance: 6399 sats
10354 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
10355 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
10356 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);
10358 // Outbound dust balance: 5200 sats
10359 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);
10361 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
10362 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
10363 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
10365 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10366 *feerate_lock = *feerate_lock * 10;
10368 nodes[0].node.timer_tick_occurred();
10369 check_added_monitors!(nodes[0], 1);
10370 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);
10373 let _ = nodes[0].node.get_and_clear_pending_msg_events();
10374 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
10375 added_monitors.clear();
10379 fn test_max_dust_htlc_exposure() {
10380 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
10381 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
10382 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
10383 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
10384 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
10385 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
10386 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
10387 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
10388 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
10389 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
10390 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
10391 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
10395 fn test_non_final_funding_tx() {
10396 let chanmon_cfgs = create_chanmon_cfgs(2);
10397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10399 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10401 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
10402 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10403 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
10404 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10405 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
10407 let best_height = nodes[0].node.best_block.read().unwrap().height();
10409 let chan_id = *nodes[0].network_chan_count.borrow();
10410 let events = nodes[0].node.get_and_clear_pending_events();
10411 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: 0x1, witness: Witness::from_vec(vec!(vec!(1))) };
10412 assert_eq!(events.len(), 1);
10413 let mut tx = match events[0] {
10414 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10415 // Timelock the transaction _beyond_ the best client height + 2.
10416 Transaction { version: chan_id as i32, lock_time: best_height + 3, input: vec![input], output: vec![TxOut {
10417 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10420 _ => panic!("Unexpected event"),
10422 // Transaction should fail as it's evaluated as non-final for propagation.
10423 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10424 Err(APIError::APIMisuseError { err }) => {
10425 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10430 // However, transaction should be accepted if it's in a +2 headroom from best block.
10432 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10433 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());