1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
59 fn test_insane_channel_opens() {
60 // Stand up a network of 2 nodes
61 let chanmon_cfgs = create_chanmon_cfgs(2);
62 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
63 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
64 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
66 // Instantiate channel parameters where we push the maximum msats given our
68 let channel_value_sat = 31337; // same as funding satoshis
69 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
70 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
72 // Have node0 initiate a channel to node1 with aforementioned parameters
73 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
75 // Extract the channel open message from node0 to node1
76 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
78 // Test helper that asserts we get the correct error string given a mutator
79 // that supposedly makes the channel open message insane
80 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
81 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
82 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
83 assert_eq!(msg_events.len(), 1);
84 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
85 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
87 &ErrorAction::SendErrorMessage { .. } => {
88 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
90 _ => panic!("unexpected event!"),
92 } else { assert!(false); }
95 use ln::channel::MAX_FUNDING_SATOSHIS;
96 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
98 // Test all mutations that would make the channel open message insane
99 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
101 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
103 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
105 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
107 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 });
109 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 });
111 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
113 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
116 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
117 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
118 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
119 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
120 // in normal testing, we test it explicitly here.
121 let chanmon_cfgs = create_chanmon_cfgs(2);
122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126 // Have node0 initiate a channel to node1 with aforementioned parameters
127 let mut push_amt = 100_000_000;
128 let feerate_per_kw = 253;
129 let opt_anchors = false;
130 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
131 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
133 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();
134 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
135 if !send_from_initiator {
136 open_channel_message.channel_reserve_satoshis = 0;
137 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
139 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
141 // Extract the channel accept message from node1 to node0
142 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
143 if send_from_initiator {
144 accept_channel_message.channel_reserve_satoshis = 0;
145 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
147 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
150 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
151 chan.holder_selected_channel_reserve_satoshis = 0;
152 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
155 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
156 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
157 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
159 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
160 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
161 if send_from_initiator {
162 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
163 // Note that for outbound channels we have to consider the commitment tx fee and the
164 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
165 // well as an additional HTLC.
166 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
168 send_payment(&nodes[1], &[&nodes[0]], push_amt);
173 fn test_counterparty_no_reserve() {
174 do_test_counterparty_no_reserve(true);
175 do_test_counterparty_no_reserve(false);
179 fn test_async_inbound_update_fee() {
180 let chanmon_cfgs = create_chanmon_cfgs(2);
181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
184 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
187 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
191 // send (1) commitment_signed -.
192 // <- update_add_htlc/commitment_signed
193 // send (2) RAA (awaiting remote revoke) -.
194 // (1) commitment_signed is delivered ->
195 // .- send (3) RAA (awaiting remote revoke)
196 // (2) RAA is delivered ->
197 // .- send (4) commitment_signed
198 // <- (3) RAA is delivered
199 // send (5) commitment_signed -.
200 // <- (4) commitment_signed is delivered
202 // (5) commitment_signed is delivered ->
204 // (6) RAA is delivered ->
206 // First nodes[0] generates an update_fee
208 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
211 nodes[0].node.timer_tick_occurred();
212 check_added_monitors!(nodes[0], 1);
214 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
215 assert_eq!(events_0.len(), 1);
216 let (update_msg, commitment_signed) = match events_0[0] { // (1)
217 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
218 (update_fee.as_ref(), commitment_signed)
220 _ => panic!("Unexpected event"),
223 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
225 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
226 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
227 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
228 check_added_monitors!(nodes[1], 1);
230 let payment_event = {
231 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
232 assert_eq!(events_1.len(), 1);
233 SendEvent::from_event(events_1.remove(0))
235 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
236 assert_eq!(payment_event.msgs.len(), 1);
238 // ...now when the messages get delivered everyone should be happy
239 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
240 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
241 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
242 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
243 check_added_monitors!(nodes[0], 1);
245 // deliver(1), generate (3):
246 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
247 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
248 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
249 check_added_monitors!(nodes[1], 1);
251 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
252 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
253 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
254 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
255 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
256 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
257 assert!(bs_update.update_fee.is_none()); // (4)
258 check_added_monitors!(nodes[1], 1);
260 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
261 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
262 assert!(as_update.update_add_htlcs.is_empty()); // (5)
263 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
264 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
265 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
266 assert!(as_update.update_fee.is_none()); // (5)
267 check_added_monitors!(nodes[0], 1);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
270 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // only (6) so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
275 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
276 check_added_monitors!(nodes[1], 1);
278 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
279 check_added_monitors!(nodes[0], 1);
281 let events_2 = nodes[0].node.get_and_clear_pending_events();
282 assert_eq!(events_2.len(), 1);
284 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
285 _ => panic!("Unexpected event"),
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
289 check_added_monitors!(nodes[1], 1);
293 fn test_update_fee_unordered_raa() {
294 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
295 // crash in an earlier version of the update_fee patch)
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
303 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
305 // First nodes[0] generates an update_fee
307 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
310 nodes[0].node.timer_tick_occurred();
311 check_added_monitors!(nodes[0], 1);
313 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
314 assert_eq!(events_0.len(), 1);
315 let update_msg = match events_0[0] { // (1)
316 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
319 _ => panic!("Unexpected event"),
322 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
324 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
325 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
326 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
327 check_added_monitors!(nodes[1], 1);
329 let payment_event = {
330 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
331 assert_eq!(events_1.len(), 1);
332 SendEvent::from_event(events_1.remove(0))
334 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
335 assert_eq!(payment_event.msgs.len(), 1);
337 // ...now when the messages get delivered everyone should be happy
338 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
339 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
340 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
341 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
342 check_added_monitors!(nodes[0], 1);
344 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
345 check_added_monitors!(nodes[1], 1);
347 // We can't continue, sadly, because our (1) now has a bogus signature
351 fn test_multi_flight_update_fee() {
352 let chanmon_cfgs = create_chanmon_cfgs(2);
353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
356 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
359 // update_fee/commitment_signed ->
360 // .- send (1) RAA and (2) commitment_signed
361 // update_fee (never committed) ->
363 // We have to manually generate the above update_fee, it is allowed by the protocol but we
364 // don't track which updates correspond to which revoke_and_ack responses so we're in
365 // AwaitingRAA mode and will not generate the update_fee yet.
366 // <- (1) RAA delivered
367 // (3) is generated and send (4) CS -.
368 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
369 // know the per_commitment_point to use for it.
370 // <- (2) commitment_signed delivered
372 // B should send no response here
373 // (4) commitment_signed delivered ->
374 // <- RAA/commitment_signed delivered
377 // First nodes[0] generates an update_fee
380 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
381 initial_feerate = *feerate_lock;
382 *feerate_lock = initial_feerate + 20;
384 nodes[0].node.timer_tick_occurred();
385 check_added_monitors!(nodes[0], 1);
387 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
388 assert_eq!(events_0.len(), 1);
389 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
390 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
391 (update_fee.as_ref().unwrap(), commitment_signed)
393 _ => panic!("Unexpected event"),
396 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
397 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
398 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
399 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
400 check_added_monitors!(nodes[1], 1);
402 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
405 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406 *feerate_lock = initial_feerate + 40;
408 nodes[0].node.timer_tick_occurred();
409 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
410 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
412 // Create the (3) update_fee message that nodes[0] will generate before it does...
413 let mut update_msg_2 = msgs::UpdateFee {
414 channel_id: update_msg_1.channel_id.clone(),
415 feerate_per_kw: (initial_feerate + 30) as u32,
418 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
420 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
422 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
424 // Deliver (1), generating (3) and (4)
425 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
426 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
427 check_added_monitors!(nodes[0], 1);
428 assert!(as_second_update.update_add_htlcs.is_empty());
429 assert!(as_second_update.update_fulfill_htlcs.is_empty());
430 assert!(as_second_update.update_fail_htlcs.is_empty());
431 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
432 // Check that the update_fee newly generated matches what we delivered:
433 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
434 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
436 // Deliver (2) commitment_signed
437 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
438 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
439 check_added_monitors!(nodes[0], 1);
440 // No commitment_signed so get_event_msg's assert(len == 1) passes
442 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
443 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
444 check_added_monitors!(nodes[1], 1);
447 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
448 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
449 check_added_monitors!(nodes[1], 1);
451 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
452 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
453 check_added_monitors!(nodes[0], 1);
455 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
456 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
457 // No commitment_signed so get_event_msg's assert(len == 1) passes
458 check_added_monitors!(nodes[0], 1);
460 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
461 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
462 check_added_monitors!(nodes[1], 1);
465 fn do_test_sanity_on_in_flight_opens(steps: u8) {
466 // Previously, we had issues deserializing channels when we hadn't connected the first block
467 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
468 // serialization round-trips and simply do steps towards opening a channel and then drop the
471 let chanmon_cfgs = create_chanmon_cfgs(2);
472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
476 if steps & 0b1000_0000 != 0{
478 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
481 connect_block(&nodes[0], &block);
482 connect_block(&nodes[1], &block);
485 if steps & 0x0f == 0 { return; }
486 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
487 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
489 if steps & 0x0f == 1 { return; }
490 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
491 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
493 if steps & 0x0f == 2 { return; }
494 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
496 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
498 if steps & 0x0f == 3 { return; }
499 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
500 check_added_monitors!(nodes[0], 0);
501 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
503 if steps & 0x0f == 4 { return; }
504 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
506 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
507 assert_eq!(added_monitors.len(), 1);
508 assert_eq!(added_monitors[0].0, funding_output);
509 added_monitors.clear();
511 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
513 if steps & 0x0f == 5 { return; }
514 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
516 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
517 assert_eq!(added_monitors.len(), 1);
518 assert_eq!(added_monitors[0].0, funding_output);
519 added_monitors.clear();
522 let events_4 = nodes[0].node.get_and_clear_pending_events();
523 assert_eq!(events_4.len(), 0);
525 if steps & 0x0f == 6 { return; }
526 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
528 if steps & 0x0f == 7 { return; }
529 confirm_transaction_at(&nodes[0], &tx, 2);
530 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
531 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
535 fn test_sanity_on_in_flight_opens() {
536 do_test_sanity_on_in_flight_opens(0);
537 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
538 do_test_sanity_on_in_flight_opens(1);
539 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
540 do_test_sanity_on_in_flight_opens(2);
541 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
542 do_test_sanity_on_in_flight_opens(3);
543 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
544 do_test_sanity_on_in_flight_opens(4);
545 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
546 do_test_sanity_on_in_flight_opens(5);
547 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
548 do_test_sanity_on_in_flight_opens(6);
549 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
550 do_test_sanity_on_in_flight_opens(7);
551 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
552 do_test_sanity_on_in_flight_opens(8);
553 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
557 fn test_update_fee_vanilla() {
558 let chanmon_cfgs = create_chanmon_cfgs(2);
559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
562 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
565 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
568 nodes[0].node.timer_tick_occurred();
569 check_added_monitors!(nodes[0], 1);
571 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
572 assert_eq!(events_0.len(), 1);
573 let (update_msg, commitment_signed) = match events_0[0] {
574 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 } } => {
575 (update_fee.as_ref(), commitment_signed)
577 _ => panic!("Unexpected event"),
579 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
581 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
582 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
583 check_added_monitors!(nodes[1], 1);
585 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
586 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
587 check_added_monitors!(nodes[0], 1);
589 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
590 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
591 // No commitment_signed so get_event_msg's assert(len == 1) passes
592 check_added_monitors!(nodes[0], 1);
594 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
595 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
596 check_added_monitors!(nodes[1], 1);
600 fn test_update_fee_that_funder_cannot_afford() {
601 let chanmon_cfgs = create_chanmon_cfgs(2);
602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605 let channel_value = 5000;
607 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
608 let channel_id = chan.2;
609 let secp_ctx = Secp256k1::new();
610 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
612 let opt_anchors = false;
614 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
615 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
616 // calculate two different feerates here - the expected local limit as well as the expected
618 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;
619 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
621 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
622 *feerate_lock = feerate;
624 nodes[0].node.timer_tick_occurred();
625 check_added_monitors!(nodes[0], 1);
626 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
628 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
630 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
632 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
634 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
636 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
637 assert_eq!(commitment_tx.output.len(), 2);
638 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
639 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
640 actual_fee = channel_value - actual_fee;
641 assert_eq!(total_fee, actual_fee);
645 // Increment the feerate by a small constant, accounting for rounding errors
646 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
649 nodes[0].node.timer_tick_occurred();
650 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
651 check_added_monitors!(nodes[0], 0);
653 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
655 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
656 // needed to sign the new commitment tx and (2) sign the new commitment tx.
657 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
658 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
659 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
660 let chan_signer = local_chan.get_signer();
661 let pubkeys = chan_signer.pubkeys();
662 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
663 pubkeys.funding_pubkey)
665 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
666 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
667 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
668 let chan_signer = remote_chan.get_signer();
669 let pubkeys = chan_signer.pubkeys();
670 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
671 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
672 pubkeys.funding_pubkey)
675 // Assemble the set of keys we can use for signatures for our commitment_signed message.
676 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
677 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
680 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
681 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
682 let local_chan_signer = local_chan.get_signer();
683 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
684 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
685 INITIAL_COMMITMENT_NUMBER - 1,
687 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
688 opt_anchors, local_funding, remote_funding,
689 commit_tx_keys.clone(),
690 non_buffer_feerate + 4,
692 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
694 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
697 let commit_signed_msg = msgs::CommitmentSigned {
700 htlc_signatures: res.1
703 let update_fee = msgs::UpdateFee {
705 feerate_per_kw: non_buffer_feerate + 4,
708 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
710 //While producing the commitment_signed response after handling a received update_fee request the
711 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
712 //Should produce and error.
713 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
714 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
715 check_added_monitors!(nodes[1], 1);
716 check_closed_broadcast!(nodes[1], true);
717 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
721 fn test_update_fee_with_fundee_update_add_htlc() {
722 let chanmon_cfgs = create_chanmon_cfgs(2);
723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
725 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
726 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
729 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
732 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
735 nodes[0].node.timer_tick_occurred();
736 check_added_monitors!(nodes[0], 1);
738 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
739 assert_eq!(events_0.len(), 1);
740 let (update_msg, commitment_signed) = match events_0[0] {
741 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 } } => {
742 (update_fee.as_ref(), commitment_signed)
744 _ => panic!("Unexpected event"),
746 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
748 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
749 check_added_monitors!(nodes[1], 1);
751 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
753 // nothing happens since node[1] is in AwaitingRemoteRevoke
754 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
756 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
757 assert_eq!(added_monitors.len(), 0);
758 added_monitors.clear();
760 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
761 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762 // node[1] has nothing to do
764 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
765 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
766 check_added_monitors!(nodes[0], 1);
768 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
769 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
770 // No commitment_signed so get_event_msg's assert(len == 1) passes
771 check_added_monitors!(nodes[0], 1);
772 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
773 check_added_monitors!(nodes[1], 1);
774 // AwaitingRemoteRevoke ends here
776 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
777 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
778 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
779 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
780 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
781 assert_eq!(commitment_update.update_fee.is_none(), true);
783 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
784 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
785 check_added_monitors!(nodes[0], 1);
786 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
788 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
789 check_added_monitors!(nodes[1], 1);
790 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
792 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
793 check_added_monitors!(nodes[1], 1);
794 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
795 // No commitment_signed so get_event_msg's assert(len == 1) passes
797 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
798 check_added_monitors!(nodes[0], 1);
799 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
801 expect_pending_htlcs_forwardable!(nodes[0]);
803 let events = nodes[0].node.get_and_clear_pending_events();
804 assert_eq!(events.len(), 1);
806 Event::PaymentReceived { .. } => { },
807 _ => panic!("Unexpected event"),
810 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
812 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
813 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
814 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
815 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
816 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
820 fn test_update_fee() {
821 let chanmon_cfgs = create_chanmon_cfgs(2);
822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
825 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
826 let channel_id = chan.2;
829 // (1) update_fee/commitment_signed ->
830 // <- (2) revoke_and_ack
831 // .- send (3) commitment_signed
832 // (4) update_fee/commitment_signed ->
833 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
834 // <- (3) commitment_signed delivered
835 // send (6) revoke_and_ack -.
836 // <- (5) deliver revoke_and_ack
837 // (6) deliver revoke_and_ack ->
838 // .- send (7) commitment_signed in response to (4)
839 // <- (7) deliver commitment_signed
842 // Create and deliver (1)...
845 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
846 feerate = *feerate_lock;
847 *feerate_lock = feerate + 20;
849 nodes[0].node.timer_tick_occurred();
850 check_added_monitors!(nodes[0], 1);
852 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
853 assert_eq!(events_0.len(), 1);
854 let (update_msg, commitment_signed) = match events_0[0] {
855 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 } } => {
856 (update_fee.as_ref(), commitment_signed)
858 _ => panic!("Unexpected event"),
860 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
862 // Generate (2) and (3):
863 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
864 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
865 check_added_monitors!(nodes[1], 1);
868 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 check_added_monitors!(nodes[0], 1);
872 // Create and deliver (4)...
874 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
875 *feerate_lock = feerate + 30;
877 nodes[0].node.timer_tick_occurred();
878 check_added_monitors!(nodes[0], 1);
879 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
880 assert_eq!(events_0.len(), 1);
881 let (update_msg, commitment_signed) = match events_0[0] {
882 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
883 (update_fee.as_ref(), commitment_signed)
885 _ => panic!("Unexpected event"),
888 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
890 check_added_monitors!(nodes[1], 1);
892 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
893 // No commitment_signed so get_event_msg's assert(len == 1) passes
895 // Handle (3), creating (6):
896 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
897 check_added_monitors!(nodes[0], 1);
898 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
899 // No commitment_signed so get_event_msg's assert(len == 1) passes
902 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
903 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
904 check_added_monitors!(nodes[0], 1);
906 // Deliver (6), creating (7):
907 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
908 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
909 assert!(commitment_update.update_add_htlcs.is_empty());
910 assert!(commitment_update.update_fulfill_htlcs.is_empty());
911 assert!(commitment_update.update_fail_htlcs.is_empty());
912 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
913 assert!(commitment_update.update_fee.is_none());
914 check_added_monitors!(nodes[1], 1);
917 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
918 check_added_monitors!(nodes[0], 1);
919 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
920 // No commitment_signed so get_event_msg's assert(len == 1) passes
922 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
923 check_added_monitors!(nodes[1], 1);
924 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
926 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
927 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
928 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
929 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
930 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
934 fn fake_network_test() {
935 // Simple test which builds a network of ChannelManagers, connects them to each other, and
936 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
937 let chanmon_cfgs = create_chanmon_cfgs(4);
938 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
939 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
940 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
942 // Create some initial channels
943 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
944 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
945 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
947 // Rebalance the network a bit by relaying one payment through all the channels...
948 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
949 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
950 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
951 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
953 // Send some more payments
954 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
955 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
956 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
958 // Test failure packets
959 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
960 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
962 // Add a new channel that skips 3
963 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
965 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
966 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
967 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
968 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
969 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
970 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
971 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
973 // Do some rebalance loop payments, simultaneously
974 let mut hops = Vec::with_capacity(3);
976 pubkey: nodes[2].node.get_our_node_id(),
977 node_features: NodeFeatures::empty(),
978 short_channel_id: chan_2.0.contents.short_channel_id,
979 channel_features: ChannelFeatures::empty(),
981 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
984 pubkey: nodes[3].node.get_our_node_id(),
985 node_features: NodeFeatures::empty(),
986 short_channel_id: chan_3.0.contents.short_channel_id,
987 channel_features: ChannelFeatures::empty(),
989 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
992 pubkey: nodes[1].node.get_our_node_id(),
993 node_features: NodeFeatures::known(),
994 short_channel_id: chan_4.0.contents.short_channel_id,
995 channel_features: ChannelFeatures::known(),
997 cltv_expiry_delta: TEST_FINAL_CLTV,
999 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;
1000 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;
1001 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;
1003 let mut hops = Vec::with_capacity(3);
1004 hops.push(RouteHop {
1005 pubkey: nodes[3].node.get_our_node_id(),
1006 node_features: NodeFeatures::empty(),
1007 short_channel_id: chan_4.0.contents.short_channel_id,
1008 channel_features: ChannelFeatures::empty(),
1010 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1012 hops.push(RouteHop {
1013 pubkey: nodes[2].node.get_our_node_id(),
1014 node_features: NodeFeatures::empty(),
1015 short_channel_id: chan_3.0.contents.short_channel_id,
1016 channel_features: ChannelFeatures::empty(),
1018 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1020 hops.push(RouteHop {
1021 pubkey: nodes[1].node.get_our_node_id(),
1022 node_features: NodeFeatures::known(),
1023 short_channel_id: chan_2.0.contents.short_channel_id,
1024 channel_features: ChannelFeatures::known(),
1026 cltv_expiry_delta: TEST_FINAL_CLTV,
1028 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;
1029 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;
1030 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;
1032 // Claim the rebalances...
1033 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1034 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1036 // Add a duplicate new channel from 2 to 4
1037 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1039 // Send some payments across both channels
1040 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1041 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1042 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1045 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1046 let events = nodes[0].node.get_and_clear_pending_msg_events();
1047 assert_eq!(events.len(), 0);
1048 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);
1050 //TODO: Test that routes work again here as we've been notified that the channel is full
1052 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1053 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1054 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1056 // Close down the channels...
1057 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1058 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1059 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1060 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1061 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1062 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1063 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1064 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1065 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1066 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1067 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1068 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1069 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1070 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1075 fn holding_cell_htlc_counting() {
1076 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1077 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1078 // commitment dance rounds.
1079 let chanmon_cfgs = create_chanmon_cfgs(3);
1080 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1081 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1082 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1083 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1084 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1086 let mut payments = Vec::new();
1087 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1088 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1089 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1090 payments.push((payment_preimage, payment_hash));
1092 check_added_monitors!(nodes[1], 1);
1094 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1095 assert_eq!(events.len(), 1);
1096 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1097 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1099 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1100 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1102 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1104 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1105 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1106 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1110 // This should also be true if we try to forward a payment.
1111 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1113 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1114 check_added_monitors!(nodes[0], 1);
1117 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1122 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1123 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1124 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1125 // fails), the second will process the resulting failure and fail the HTLC backward.
1126 expect_pending_htlcs_forwardable!(nodes[1]);
1127 expect_pending_htlcs_forwardable!(nodes[1]);
1128 check_added_monitors!(nodes[1], 1);
1130 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1131 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1132 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1134 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1136 // Now forward all the pending HTLCs and claim them back
1137 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1138 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1139 check_added_monitors!(nodes[2], 1);
1141 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1142 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1143 check_added_monitors!(nodes[1], 1);
1144 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1146 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1147 check_added_monitors!(nodes[1], 1);
1148 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1150 for ref update in as_updates.update_add_htlcs.iter() {
1151 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1153 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1154 check_added_monitors!(nodes[2], 1);
1155 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1156 check_added_monitors!(nodes[2], 1);
1157 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1159 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1160 check_added_monitors!(nodes[1], 1);
1161 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162 check_added_monitors!(nodes[1], 1);
1163 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1165 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1166 check_added_monitors!(nodes[2], 1);
1168 expect_pending_htlcs_forwardable!(nodes[2]);
1170 let events = nodes[2].node.get_and_clear_pending_events();
1171 assert_eq!(events.len(), payments.len());
1172 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1174 &Event::PaymentReceived { ref payment_hash, .. } => {
1175 assert_eq!(*payment_hash, *hash);
1177 _ => panic!("Unexpected event"),
1181 for (preimage, _) in payments.drain(..) {
1182 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1185 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1189 fn duplicate_htlc_test() {
1190 // Test that we accept duplicate payment_hash HTLCs across the network and that
1191 // claiming/failing them are all separate and don't affect each other
1192 let chanmon_cfgs = create_chanmon_cfgs(6);
1193 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1194 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1195 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1197 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1198 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1199 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1200 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1201 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1202 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1204 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1206 *nodes[0].network_payment_count.borrow_mut() -= 1;
1207 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1209 *nodes[0].network_payment_count.borrow_mut() -= 1;
1210 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1212 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1213 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1214 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1218 fn test_duplicate_htlc_different_direction_onchain() {
1219 // Test that ChannelMonitor doesn't generate 2 preimage txn
1220 // when we have 2 HTLCs with same preimage that go across a node
1221 // in opposite directions, even with the same payment secret.
1222 let chanmon_cfgs = create_chanmon_cfgs(2);
1223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1225 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1227 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1230 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1232 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1234 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1235 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1236 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1238 // Provide preimage to node 0 by claiming payment
1239 nodes[0].node.claim_funds(payment_preimage);
1240 check_added_monitors!(nodes[0], 1);
1242 // Broadcast node 1 commitment txn
1243 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1245 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1246 let mut has_both_htlcs = 0; // check htlcs match ones committed
1247 for outp in remote_txn[0].output.iter() {
1248 if outp.value == 800_000 / 1000 {
1249 has_both_htlcs += 1;
1250 } else if outp.value == 900_000 / 1000 {
1251 has_both_htlcs += 1;
1254 assert_eq!(has_both_htlcs, 2);
1256 mine_transaction(&nodes[0], &remote_txn[0]);
1257 check_added_monitors!(nodes[0], 1);
1258 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1259 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1261 // Check we only broadcast 1 timeout tx
1262 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1263 assert_eq!(claim_txn.len(), 8);
1264 assert_eq!(claim_txn[1], claim_txn[4]);
1265 assert_eq!(claim_txn[2], claim_txn[5]);
1266 check_spends!(claim_txn[1], chan_1.3);
1267 check_spends!(claim_txn[2], claim_txn[1]);
1268 check_spends!(claim_txn[7], claim_txn[1]);
1270 assert_eq!(claim_txn[0].input.len(), 1);
1271 assert_eq!(claim_txn[3].input.len(), 1);
1272 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1274 assert_eq!(claim_txn[0].input.len(), 1);
1275 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1276 check_spends!(claim_txn[0], remote_txn[0]);
1277 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1278 assert_eq!(claim_txn[6].input.len(), 1);
1279 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1280 check_spends!(claim_txn[6], remote_txn[0]);
1281 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1283 let events = nodes[0].node.get_and_clear_pending_msg_events();
1284 assert_eq!(events.len(), 3);
1287 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1288 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1289 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1290 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1292 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, .. } } => {
1293 assert!(update_add_htlcs.is_empty());
1294 assert!(update_fail_htlcs.is_empty());
1295 assert_eq!(update_fulfill_htlcs.len(), 1);
1296 assert!(update_fail_malformed_htlcs.is_empty());
1297 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1299 _ => panic!("Unexpected event"),
1305 fn test_basic_channel_reserve() {
1306 let chanmon_cfgs = create_chanmon_cfgs(2);
1307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1309 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1310 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1312 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1313 let channel_reserve = chan_stat.channel_reserve_msat;
1315 // The 2* and +1 are for the fee spike reserve.
1316 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1317 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1318 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1319 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1321 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1323 &APIError::ChannelUnavailable{ref err} =>
1324 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1325 _ => panic!("Unexpected error variant"),
1328 _ => panic!("Unexpected error variant"),
1330 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1331 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);
1333 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1337 fn test_fee_spike_violation_fails_htlc() {
1338 let chanmon_cfgs = create_chanmon_cfgs(2);
1339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1342 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1344 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1345 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1346 let secp_ctx = Secp256k1::new();
1347 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1349 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1351 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1352 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1353 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1354 let msg = msgs::UpdateAddHTLC {
1357 amount_msat: htlc_msat,
1358 payment_hash: payment_hash,
1359 cltv_expiry: htlc_cltv,
1360 onion_routing_packet: onion_packet,
1363 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1365 // Now manually create the commitment_signed message corresponding to the update_add
1366 // nodes[0] just sent. In the code for construction of this message, "local" refers
1367 // to the sender of the message, and "remote" refers to the receiver.
1369 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1371 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1373 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1374 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1375 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1376 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1377 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1378 let chan_signer = local_chan.get_signer();
1379 // Make the signer believe we validated another commitment, so we can release the secret
1380 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1382 let pubkeys = chan_signer.pubkeys();
1383 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1384 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1385 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1386 chan_signer.pubkeys().funding_pubkey)
1388 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1389 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1390 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1391 let chan_signer = remote_chan.get_signer();
1392 let pubkeys = chan_signer.pubkeys();
1393 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1394 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1395 chan_signer.pubkeys().funding_pubkey)
1398 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1399 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1400 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1402 // Build the remote commitment transaction so we can sign it, and then later use the
1403 // signature for the commitment_signed message.
1404 let local_chan_balance = 1313;
1406 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1408 amount_msat: 3460001,
1409 cltv_expiry: htlc_cltv,
1411 transaction_output_index: Some(1),
1414 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1417 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1418 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1419 let local_chan_signer = local_chan.get_signer();
1420 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1424 local_chan.opt_anchors(), local_funding, remote_funding,
1425 commit_tx_keys.clone(),
1427 &mut vec![(accepted_htlc_info, ())],
1428 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1430 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1433 let commit_signed_msg = msgs::CommitmentSigned {
1436 htlc_signatures: res.1
1439 // Send the commitment_signed message to the nodes[1].
1440 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1441 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1443 // Send the RAA to nodes[1].
1444 let raa_msg = msgs::RevokeAndACK {
1446 per_commitment_secret: local_secret,
1447 next_per_commitment_point: next_local_point
1449 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1451 let events = nodes[1].node.get_and_clear_pending_msg_events();
1452 assert_eq!(events.len(), 1);
1453 // Make sure the HTLC failed in the way we expect.
1455 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1456 assert_eq!(update_fail_htlcs.len(), 1);
1457 update_fail_htlcs[0].clone()
1459 _ => panic!("Unexpected event"),
1461 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1462 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1464 check_added_monitors!(nodes[1], 2);
1468 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1469 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1470 // Set the fee rate for the channel very high, to the point where the fundee
1471 // sending any above-dust amount would result in a channel reserve violation.
1472 // In this test we check that we would be prevented from sending an HTLC in
1474 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1479 let opt_anchors = false;
1481 let mut push_amt = 100_000_000;
1482 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1483 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1485 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1487 // Sending exactly enough to hit the reserve amount should be accepted
1488 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1489 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1492 // However one more HTLC should be significantly over the reserve amount and fail.
1493 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1494 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1495 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1496 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1497 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);
1501 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1502 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1503 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1506 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1508 let opt_anchors = false;
1510 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1511 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1512 // transaction fee with 0 HTLCs (183 sats)).
1513 let mut push_amt = 100_000_000;
1514 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1515 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1516 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1518 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1519 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1520 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1523 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1524 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1525 let secp_ctx = Secp256k1::new();
1526 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1527 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1528 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1529 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1530 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1531 let msg = msgs::UpdateAddHTLC {
1533 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1534 amount_msat: htlc_msat,
1535 payment_hash: payment_hash,
1536 cltv_expiry: htlc_cltv,
1537 onion_routing_packet: onion_packet,
1540 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1541 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1542 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);
1543 assert_eq!(nodes[0].node.list_channels().len(), 0);
1544 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1545 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1546 check_added_monitors!(nodes[0], 1);
1547 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() });
1551 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1552 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1553 // calculating our commitment transaction fee (this was previously broken).
1554 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1555 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1561 let opt_anchors = false;
1563 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1564 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1565 // transaction fee with 0 HTLCs (183 sats)).
1566 let mut push_amt = 100_000_000;
1567 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1568 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1569 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1571 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1572 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1573 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1574 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1575 // commitment transaction fee.
1576 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1578 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1579 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1580 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1583 // One more than the dust amt should fail, however.
1584 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1585 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1586 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1590 fn test_chan_init_feerate_unaffordability() {
1591 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1592 // channel reserve and feerate requirements.
1593 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1594 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1599 let opt_anchors = false;
1601 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1603 let mut push_amt = 100_000_000;
1604 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1605 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1606 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1608 // During open, we don't have a "counterparty channel reserve" to check against, so that
1609 // requirement only comes into play on the open_channel handling side.
1610 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1611 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1612 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1613 open_channel_msg.push_msat += 1;
1614 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1616 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1617 assert_eq!(msg_events.len(), 1);
1618 match msg_events[0] {
1619 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1620 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1622 _ => panic!("Unexpected event"),
1627 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1628 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1629 // calculating our counterparty's commitment transaction fee (this was previously broken).
1630 let chanmon_cfgs = create_chanmon_cfgs(2);
1631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1633 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1634 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1636 let payment_amt = 46000; // Dust amount
1637 // In the previous code, these first four payments would succeed.
1638 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1639 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1640 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1641 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1643 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1644 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1645 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1646 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1647 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1648 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1650 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1651 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1652 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1653 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1658 let chanmon_cfgs = create_chanmon_cfgs(3);
1659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1661 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1662 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1663 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1666 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1667 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1668 let feerate = get_feerate!(nodes[0], chan.2);
1669 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1671 // Add a 2* and +1 for the fee spike reserve.
1672 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1673 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;
1674 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1676 // Add a pending HTLC.
1677 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1678 let payment_event_1 = {
1679 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1680 check_added_monitors!(nodes[0], 1);
1682 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1683 assert_eq!(events.len(), 1);
1684 SendEvent::from_event(events.remove(0))
1686 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1688 // Attempt to trigger a channel reserve violation --> payment failure.
1689 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1690 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;
1691 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1692 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1694 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1695 let secp_ctx = Secp256k1::new();
1696 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1697 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1698 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1699 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1700 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1701 let msg = msgs::UpdateAddHTLC {
1704 amount_msat: htlc_msat + 1,
1705 payment_hash: our_payment_hash_1,
1706 cltv_expiry: htlc_cltv,
1707 onion_routing_packet: onion_packet,
1710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1711 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1712 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1713 assert_eq!(nodes[1].node.list_channels().len(), 1);
1714 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1715 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1716 check_added_monitors!(nodes[1], 1);
1717 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1721 fn test_inbound_outbound_capacity_is_not_zero() {
1722 let chanmon_cfgs = create_chanmon_cfgs(2);
1723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1726 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1727 let channels0 = node_chanmgrs[0].list_channels();
1728 let channels1 = node_chanmgrs[1].list_channels();
1729 assert_eq!(channels0.len(), 1);
1730 assert_eq!(channels1.len(), 1);
1732 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1733 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1734 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1736 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1737 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1740 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1741 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1745 fn test_channel_reserve_holding_cell_htlcs() {
1746 let chanmon_cfgs = create_chanmon_cfgs(3);
1747 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1748 // When this test was written, the default base fee floated based on the HTLC count.
1749 // It is now fixed, so we simply set the fee to the expected value here.
1750 let mut config = test_default_channel_config();
1751 config.channel_options.forwarding_fee_base_msat = 239;
1752 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1753 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1754 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1755 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1757 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1758 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1760 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1761 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1763 macro_rules! expect_forward {
1765 let mut events = $node.node.get_and_clear_pending_msg_events();
1766 assert_eq!(events.len(), 1);
1767 check_added_monitors!($node, 1);
1768 let payment_event = SendEvent::from_event(events.remove(0));
1773 let feemsat = 239; // set above
1774 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1775 let feerate = get_feerate!(nodes[0], chan_1.2);
1776 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1778 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1780 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1782 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1783 route.paths[0].last_mut().unwrap().fee_msat += 1;
1784 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1785 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1786 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)));
1787 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1788 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);
1791 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1792 // nodes[0]'s wealth
1794 let amt_msat = recv_value_0 + total_fee_msat;
1795 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1796 // Also, ensure that each payment has enough to be over the dust limit to
1797 // ensure it'll be included in each commit tx fee calculation.
1798 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1799 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1800 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1803 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1805 let (stat01_, stat11_, stat12_, stat22_) = (
1806 get_channel_value_stat!(nodes[0], chan_1.2),
1807 get_channel_value_stat!(nodes[1], chan_1.2),
1808 get_channel_value_stat!(nodes[1], chan_2.2),
1809 get_channel_value_stat!(nodes[2], chan_2.2),
1812 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1813 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1814 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1815 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1816 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1819 // adding pending output.
1820 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1821 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1822 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1823 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1824 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1825 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1826 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1827 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1828 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1830 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1831 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1832 let amt_msat_1 = recv_value_1 + total_fee_msat;
1834 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);
1835 let payment_event_1 = {
1836 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1837 check_added_monitors!(nodes[0], 1);
1839 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1840 assert_eq!(events.len(), 1);
1841 SendEvent::from_event(events.remove(0))
1843 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1845 // channel reserve test with htlc pending output > 0
1846 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1848 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1849 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1850 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1851 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1854 // split the rest to test holding cell
1855 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1856 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1857 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1858 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1860 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1861 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);
1864 // now see if they go through on both sides
1865 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);
1866 // but this will stuck in the holding cell
1867 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1868 check_added_monitors!(nodes[0], 0);
1869 let events = nodes[0].node.get_and_clear_pending_events();
1870 assert_eq!(events.len(), 0);
1872 // test with outbound holding cell amount > 0
1874 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1875 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1876 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1877 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1878 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);
1881 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);
1882 // this will also stuck in the holding cell
1883 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1884 check_added_monitors!(nodes[0], 0);
1885 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1888 // flush the pending htlc
1889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1890 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1891 check_added_monitors!(nodes[1], 1);
1893 // the pending htlc should be promoted to committed
1894 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1895 check_added_monitors!(nodes[0], 1);
1896 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1898 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1899 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1900 // No commitment_signed so get_event_msg's assert(len == 1) passes
1901 check_added_monitors!(nodes[0], 1);
1903 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1905 check_added_monitors!(nodes[1], 1);
1907 expect_pending_htlcs_forwardable!(nodes[1]);
1909 let ref payment_event_11 = expect_forward!(nodes[1]);
1910 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1911 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1913 expect_pending_htlcs_forwardable!(nodes[2]);
1914 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1916 // flush the htlcs in the holding cell
1917 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1918 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1920 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1921 expect_pending_htlcs_forwardable!(nodes[1]);
1923 let ref payment_event_3 = expect_forward!(nodes[1]);
1924 assert_eq!(payment_event_3.msgs.len(), 2);
1925 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1926 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1928 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1929 expect_pending_htlcs_forwardable!(nodes[2]);
1931 let events = nodes[2].node.get_and_clear_pending_events();
1932 assert_eq!(events.len(), 2);
1934 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1935 assert_eq!(our_payment_hash_21, *payment_hash);
1936 assert_eq!(recv_value_21, amt);
1938 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1939 assert!(payment_preimage.is_none());
1940 assert_eq!(our_payment_secret_21, *payment_secret);
1942 _ => panic!("expected PaymentPurpose::InvoicePayment")
1945 _ => panic!("Unexpected event"),
1948 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1949 assert_eq!(our_payment_hash_22, *payment_hash);
1950 assert_eq!(recv_value_22, amt);
1952 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1953 assert!(payment_preimage.is_none());
1954 assert_eq!(our_payment_secret_22, *payment_secret);
1956 _ => panic!("expected PaymentPurpose::InvoicePayment")
1959 _ => panic!("Unexpected event"),
1962 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1963 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1964 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1966 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1967 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1968 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1970 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1971 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);
1972 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1973 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1974 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1976 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1977 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1981 fn channel_reserve_in_flight_removes() {
1982 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1983 // can send to its counterparty, but due to update ordering, the other side may not yet have
1984 // considered those HTLCs fully removed.
1985 // This tests that we don't count HTLCs which will not be included in the next remote
1986 // commitment transaction towards the reserve value (as it implies no commitment transaction
1987 // will be generated which violates the remote reserve value).
1988 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1990 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1991 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1992 // you only consider the value of the first HTLC, it may not),
1993 // * start routing a third HTLC from A to B,
1994 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1995 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1996 // * deliver the first fulfill from B
1997 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1999 // * deliver A's response CS and RAA.
2000 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2001 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2002 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2003 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2004 let chanmon_cfgs = create_chanmon_cfgs(2);
2005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2007 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2008 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2010 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2011 // Route the first two HTLCs.
2012 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2013 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2015 // Start routing the third HTLC (this is just used to get everyone in the right state).
2016 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2018 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2019 check_added_monitors!(nodes[0], 1);
2020 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2021 assert_eq!(events.len(), 1);
2022 SendEvent::from_event(events.remove(0))
2025 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2026 // initial fulfill/CS.
2027 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2028 check_added_monitors!(nodes[1], 1);
2029 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2031 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2032 // remove the second HTLC when we send the HTLC back from B to A.
2033 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2034 check_added_monitors!(nodes[1], 1);
2035 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2037 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2039 check_added_monitors!(nodes[0], 1);
2040 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2041 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2044 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2045 check_added_monitors!(nodes[1], 1);
2046 // B is already AwaitingRAA, so cant generate a CS here
2047 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2049 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2050 check_added_monitors!(nodes[1], 1);
2051 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2053 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2054 check_added_monitors!(nodes[0], 1);
2055 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2057 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2058 check_added_monitors!(nodes[1], 1);
2059 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2061 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2062 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2063 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2064 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2065 // on-chain as necessary).
2066 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2068 check_added_monitors!(nodes[0], 1);
2069 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2070 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2072 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2073 check_added_monitors!(nodes[1], 1);
2074 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2076 expect_pending_htlcs_forwardable!(nodes[1]);
2077 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2079 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2080 // resolve the second HTLC from A's point of view.
2081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082 check_added_monitors!(nodes[0], 1);
2083 expect_payment_path_successful!(nodes[0]);
2084 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2087 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2088 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2090 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2091 check_added_monitors!(nodes[1], 1);
2092 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2093 assert_eq!(events.len(), 1);
2094 SendEvent::from_event(events.remove(0))
2097 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2098 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
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());
2102 // Now just resolve all the outstanding messages/HTLCs for completeness...
2104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105 check_added_monitors!(nodes[1], 1);
2106 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2108 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2109 check_added_monitors!(nodes[1], 1);
2111 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2112 check_added_monitors!(nodes[0], 1);
2113 expect_payment_path_successful!(nodes[0]);
2114 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2116 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2117 check_added_monitors!(nodes[1], 1);
2118 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2120 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121 check_added_monitors!(nodes[0], 1);
2123 expect_pending_htlcs_forwardable!(nodes[0]);
2124 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2126 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2127 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2131 fn channel_monitor_network_test() {
2132 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2133 // tests that ChannelMonitor is able to recover from various states.
2134 let chanmon_cfgs = create_chanmon_cfgs(5);
2135 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2136 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2137 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2139 // Create some initial channels
2140 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2141 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2142 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2143 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2145 // Make sure all nodes are at the same starting height
2146 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2147 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2148 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2149 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2150 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2152 // Rebalance the network a bit by relaying one payment through all the channels...
2153 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2154 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2155 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2156 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2158 // Simple case with no pending HTLCs:
2159 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2160 check_added_monitors!(nodes[1], 1);
2161 check_closed_broadcast!(nodes[1], false);
2163 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2164 assert_eq!(node_txn.len(), 1);
2165 mine_transaction(&nodes[0], &node_txn[0]);
2166 check_added_monitors!(nodes[0], 1);
2167 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2169 check_closed_broadcast!(nodes[0], true);
2170 assert_eq!(nodes[0].node.list_channels().len(), 0);
2171 assert_eq!(nodes[1].node.list_channels().len(), 1);
2172 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2173 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2175 // One pending HTLC is discarded by the force-close:
2176 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2178 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2179 // broadcasted until we reach the timelock time).
2180 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2181 check_closed_broadcast!(nodes[1], false);
2182 check_added_monitors!(nodes[1], 1);
2184 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2185 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2186 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2187 mine_transaction(&nodes[2], &node_txn[0]);
2188 check_added_monitors!(nodes[2], 1);
2189 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2191 check_closed_broadcast!(nodes[2], true);
2192 assert_eq!(nodes[1].node.list_channels().len(), 0);
2193 assert_eq!(nodes[2].node.list_channels().len(), 1);
2194 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2195 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2197 macro_rules! claim_funds {
2198 ($node: expr, $prev_node: expr, $preimage: expr) => {
2200 assert!($node.node.claim_funds($preimage));
2201 check_added_monitors!($node, 1);
2203 let events = $node.node.get_and_clear_pending_msg_events();
2204 assert_eq!(events.len(), 1);
2206 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2207 assert!(update_add_htlcs.is_empty());
2208 assert!(update_fail_htlcs.is_empty());
2209 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2211 _ => panic!("Unexpected event"),
2217 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2218 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2219 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2220 check_added_monitors!(nodes[2], 1);
2221 check_closed_broadcast!(nodes[2], false);
2222 let node2_commitment_txid;
2224 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2225 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2226 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2227 node2_commitment_txid = node_txn[0].txid();
2229 // Claim the payment on nodes[3], giving it knowledge of the preimage
2230 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2231 mine_transaction(&nodes[3], &node_txn[0]);
2232 check_added_monitors!(nodes[3], 1);
2233 check_preimage_claim(&nodes[3], &node_txn);
2235 check_closed_broadcast!(nodes[3], true);
2236 assert_eq!(nodes[2].node.list_channels().len(), 0);
2237 assert_eq!(nodes[3].node.list_channels().len(), 1);
2238 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2239 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2241 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2242 // confusing us in the following tests.
2243 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2245 // One pending HTLC to time out:
2246 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2247 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2250 let (close_chan_update_1, close_chan_update_2) = {
2251 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2252 let events = nodes[3].node.get_and_clear_pending_msg_events();
2253 assert_eq!(events.len(), 2);
2254 let close_chan_update_1 = match events[0] {
2255 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2258 _ => panic!("Unexpected event"),
2261 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2262 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2264 _ => panic!("Unexpected event"),
2266 check_added_monitors!(nodes[3], 1);
2268 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2270 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2271 node_txn.retain(|tx| {
2272 if tx.input[0].previous_output.txid == node2_commitment_txid {
2278 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2280 // Claim the payment on nodes[4], giving it knowledge of the preimage
2281 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2283 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2284 let events = nodes[4].node.get_and_clear_pending_msg_events();
2285 assert_eq!(events.len(), 2);
2286 let close_chan_update_2 = match events[0] {
2287 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2290 _ => panic!("Unexpected event"),
2293 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2294 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2296 _ => panic!("Unexpected event"),
2298 check_added_monitors!(nodes[4], 1);
2299 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2301 mine_transaction(&nodes[4], &node_txn[0]);
2302 check_preimage_claim(&nodes[4], &node_txn);
2303 (close_chan_update_1, close_chan_update_2)
2305 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2306 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2307 assert_eq!(nodes[3].node.list_channels().len(), 0);
2308 assert_eq!(nodes[4].node.list_channels().len(), 0);
2310 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2311 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2312 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2316 fn test_justice_tx() {
2317 // Test justice txn built on revoked HTLC-Success tx, against both sides
2318 let mut alice_config = UserConfig::default();
2319 alice_config.channel_options.announced_channel = true;
2320 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2321 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2322 let mut bob_config = UserConfig::default();
2323 bob_config.channel_options.announced_channel = true;
2324 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2325 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2326 let user_cfgs = [Some(alice_config), Some(bob_config)];
2327 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2328 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2329 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2333 // Create some new channels:
2334 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2336 // A pending HTLC which will be revoked:
2337 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338 // Get the will-be-revoked local txn from nodes[0]
2339 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2340 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2341 assert_eq!(revoked_local_txn[0].input.len(), 1);
2342 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2343 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2344 assert_eq!(revoked_local_txn[1].input.len(), 1);
2345 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2346 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2347 // Revoke the old state
2348 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2351 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2353 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2354 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2355 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2357 check_spends!(node_txn[0], revoked_local_txn[0]);
2358 node_txn.swap_remove(0);
2359 node_txn.truncate(1);
2361 check_added_monitors!(nodes[1], 1);
2362 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2363 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2365 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2366 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2367 // Verify broadcast of revoked HTLC-timeout
2368 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2369 check_added_monitors!(nodes[0], 1);
2370 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2371 // Broadcast revoked HTLC-timeout on node 1
2372 mine_transaction(&nodes[1], &node_txn[1]);
2373 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2375 get_announce_close_broadcast_events(&nodes, 0, 1);
2377 assert_eq!(nodes[0].node.list_channels().len(), 0);
2378 assert_eq!(nodes[1].node.list_channels().len(), 0);
2380 // We test justice_tx build by A on B's revoked HTLC-Success tx
2381 // Create some new channels:
2382 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2384 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2388 // A pending HTLC which will be revoked:
2389 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2390 // Get the will-be-revoked local txn from B
2391 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2392 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2393 assert_eq!(revoked_local_txn[0].input.len(), 1);
2394 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2395 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2396 // Revoke the old state
2397 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2399 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2401 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2402 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2403 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2405 check_spends!(node_txn[0], revoked_local_txn[0]);
2406 node_txn.swap_remove(0);
2408 check_added_monitors!(nodes[0], 1);
2409 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2411 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2412 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2414 check_added_monitors!(nodes[1], 1);
2415 mine_transaction(&nodes[0], &node_txn[1]);
2416 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2417 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2419 get_announce_close_broadcast_events(&nodes, 0, 1);
2420 assert_eq!(nodes[0].node.list_channels().len(), 0);
2421 assert_eq!(nodes[1].node.list_channels().len(), 0);
2425 fn revoked_output_claim() {
2426 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2427 // transaction is broadcast by its counterparty
2428 let chanmon_cfgs = create_chanmon_cfgs(2);
2429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2434 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2435 assert_eq!(revoked_local_txn.len(), 1);
2436 // Only output is the full channel value back to nodes[0]:
2437 assert_eq!(revoked_local_txn[0].output.len(), 1);
2438 // Send a payment through, updating everyone's latest commitment txn
2439 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2441 // Inform nodes[1] that nodes[0] broadcast a stale tx
2442 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443 check_added_monitors!(nodes[1], 1);
2444 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2445 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2446 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2448 check_spends!(node_txn[0], revoked_local_txn[0]);
2449 check_spends!(node_txn[1], chan_1.3);
2451 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2452 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453 get_announce_close_broadcast_events(&nodes, 0, 1);
2454 check_added_monitors!(nodes[0], 1);
2455 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2459 fn claim_htlc_outputs_shared_tx() {
2460 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2461 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2462 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2467 // Create some new channel:
2468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2470 // Rebalance the network to generate htlc in the two directions
2471 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2472 // 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
2473 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2476 // Get the will-be-revoked local txn from node[0]
2477 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2478 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2479 assert_eq!(revoked_local_txn[0].input.len(), 1);
2480 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2481 assert_eq!(revoked_local_txn[1].input.len(), 1);
2482 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2483 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2484 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2486 //Revoke the old state
2487 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2490 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2491 check_added_monitors!(nodes[0], 1);
2492 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2493 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2494 check_added_monitors!(nodes[1], 1);
2495 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2496 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2497 expect_payment_failed!(nodes[1], payment_hash_2, true);
2499 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2500 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2502 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2503 check_spends!(node_txn[0], revoked_local_txn[0]);
2505 let mut witness_lens = BTreeSet::new();
2506 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2507 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2508 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2509 assert_eq!(witness_lens.len(), 3);
2510 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2511 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2512 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2514 // Next nodes[1] broadcasts its current local tx state:
2515 assert_eq!(node_txn[1].input.len(), 1);
2516 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2518 get_announce_close_broadcast_events(&nodes, 0, 1);
2519 assert_eq!(nodes[0].node.list_channels().len(), 0);
2520 assert_eq!(nodes[1].node.list_channels().len(), 0);
2524 fn claim_htlc_outputs_single_tx() {
2525 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2526 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2527 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2532 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2534 // Rebalance the network to generate htlc in the two directions
2535 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2536 // 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
2537 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2538 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2539 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2541 // Get the will-be-revoked local txn from node[0]
2542 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2544 //Revoke the old state
2545 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2548 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2549 check_added_monitors!(nodes[0], 1);
2550 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2551 check_added_monitors!(nodes[1], 1);
2552 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2553 let mut events = nodes[0].node.get_and_clear_pending_events();
2554 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2556 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2557 _ => panic!("Unexpected event"),
2560 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2561 expect_payment_failed!(nodes[1], payment_hash_2, true);
2563 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564 assert_eq!(node_txn.len(), 9);
2565 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2566 // ChannelManager: local commmitment + local HTLC-timeout (2)
2567 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2568 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2570 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2571 assert_eq!(node_txn[0].input.len(), 1);
2572 check_spends!(node_txn[0], chan_1.3);
2573 assert_eq!(node_txn[1].input.len(), 1);
2574 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2575 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2576 check_spends!(node_txn[1], node_txn[0]);
2578 // Justice transactions are indices 1-2-4
2579 assert_eq!(node_txn[2].input.len(), 1);
2580 assert_eq!(node_txn[3].input.len(), 1);
2581 assert_eq!(node_txn[4].input.len(), 1);
2583 check_spends!(node_txn[2], revoked_local_txn[0]);
2584 check_spends!(node_txn[3], revoked_local_txn[0]);
2585 check_spends!(node_txn[4], revoked_local_txn[0]);
2587 let mut witness_lens = BTreeSet::new();
2588 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2589 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2590 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2591 assert_eq!(witness_lens.len(), 3);
2592 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2593 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2594 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2596 get_announce_close_broadcast_events(&nodes, 0, 1);
2597 assert_eq!(nodes[0].node.list_channels().len(), 0);
2598 assert_eq!(nodes[1].node.list_channels().len(), 0);
2602 fn test_htlc_on_chain_success() {
2603 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2604 // the preimage backward accordingly. So here we test that ChannelManager is
2605 // broadcasting the right event to other nodes in payment path.
2606 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2607 // A --------------------> B ----------------------> C (preimage)
2608 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2609 // commitment transaction was broadcast.
2610 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2612 // B should be able to claim via preimage if A then broadcasts its local tx.
2613 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2614 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2615 // PaymentSent event).
2617 let chanmon_cfgs = create_chanmon_cfgs(3);
2618 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2620 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2622 // Create some initial channels
2623 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2624 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2626 // Ensure all nodes are at the same height
2627 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2628 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2629 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2630 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2632 // Rebalance the network a bit by relaying one payment through all the channels...
2633 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2634 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2636 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2637 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2639 // Broadcast legit commitment tx from C on B's chain
2640 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2641 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2642 assert_eq!(commitment_tx.len(), 1);
2643 check_spends!(commitment_tx[0], chan_2.3);
2644 nodes[2].node.claim_funds(our_payment_preimage);
2645 nodes[2].node.claim_funds(our_payment_preimage_2);
2646 check_added_monitors!(nodes[2], 2);
2647 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2648 assert!(updates.update_add_htlcs.is_empty());
2649 assert!(updates.update_fail_htlcs.is_empty());
2650 assert!(updates.update_fail_malformed_htlcs.is_empty());
2651 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2653 mine_transaction(&nodes[2], &commitment_tx[0]);
2654 check_closed_broadcast!(nodes[2], true);
2655 check_added_monitors!(nodes[2], 1);
2656 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2657 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)
2658 assert_eq!(node_txn.len(), 5);
2659 assert_eq!(node_txn[0], node_txn[3]);
2660 assert_eq!(node_txn[1], node_txn[4]);
2661 assert_eq!(node_txn[2], commitment_tx[0]);
2662 check_spends!(node_txn[0], commitment_tx[0]);
2663 check_spends!(node_txn[1], commitment_tx[0]);
2664 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2665 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2666 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2667 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2668 assert_eq!(node_txn[0].lock_time, 0);
2669 assert_eq!(node_txn[1].lock_time, 0);
2671 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2672 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2673 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2674 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2676 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2677 assert_eq!(added_monitors.len(), 1);
2678 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2679 added_monitors.clear();
2681 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2682 assert_eq!(forwarded_events.len(), 3);
2683 match forwarded_events[0] {
2684 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2685 _ => panic!("Unexpected event"),
2687 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2688 } else { panic!(); }
2689 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2690 } else { panic!(); }
2691 let events = nodes[1].node.get_and_clear_pending_msg_events();
2693 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2694 assert_eq!(added_monitors.len(), 2);
2695 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2696 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2697 added_monitors.clear();
2699 assert_eq!(events.len(), 3);
2701 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2702 _ => panic!("Unexpected event"),
2705 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2706 _ => panic!("Unexpected event"),
2710 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, .. } } => {
2711 assert!(update_add_htlcs.is_empty());
2712 assert!(update_fail_htlcs.is_empty());
2713 assert_eq!(update_fulfill_htlcs.len(), 1);
2714 assert!(update_fail_malformed_htlcs.is_empty());
2715 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2717 _ => panic!("Unexpected event"),
2719 macro_rules! check_tx_local_broadcast {
2720 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2721 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2722 assert_eq!(node_txn.len(), 3);
2723 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2724 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2725 check_spends!(node_txn[1], $commitment_tx);
2726 check_spends!(node_txn[2], $commitment_tx);
2727 assert_ne!(node_txn[1].lock_time, 0);
2728 assert_ne!(node_txn[2].lock_time, 0);
2730 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2731 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2732 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2733 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2735 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2736 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2737 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2738 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2740 check_spends!(node_txn[0], $chan_tx);
2741 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2745 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2746 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2747 // timeout-claim of the output that nodes[2] just claimed via success.
2748 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2750 // Broadcast legit commitment tx from A on B's chain
2751 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2752 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2753 check_spends!(node_a_commitment_tx[0], chan_1.3);
2754 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2755 check_closed_broadcast!(nodes[1], true);
2756 check_added_monitors!(nodes[1], 1);
2757 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2758 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2759 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2760 let commitment_spend =
2761 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2762 check_spends!(node_txn[1], commitment_tx[0]);
2763 check_spends!(node_txn[2], commitment_tx[0]);
2764 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2767 check_spends!(node_txn[0], commitment_tx[0]);
2768 check_spends!(node_txn[1], commitment_tx[0]);
2769 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2773 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2774 assert_eq!(commitment_spend.input.len(), 2);
2775 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2776 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2777 assert_eq!(commitment_spend.lock_time, 0);
2778 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2779 check_spends!(node_txn[3], chan_1.3);
2780 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2781 check_spends!(node_txn[4], node_txn[3]);
2782 check_spends!(node_txn[5], node_txn[3]);
2783 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2784 // we already checked the same situation with A.
2786 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2787 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2788 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2789 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2790 check_closed_broadcast!(nodes[0], true);
2791 check_added_monitors!(nodes[0], 1);
2792 let events = nodes[0].node.get_and_clear_pending_events();
2793 assert_eq!(events.len(), 5);
2794 let mut first_claimed = false;
2795 for event in events {
2797 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2798 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2799 assert!(!first_claimed);
2800 first_claimed = true;
2802 assert_eq!(payment_preimage, our_payment_preimage_2);
2803 assert_eq!(payment_hash, payment_hash_2);
2806 Event::PaymentPathSuccessful { .. } => {},
2807 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2808 _ => panic!("Unexpected event"),
2811 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2814 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2815 // Test that in case of a unilateral close onchain, we detect the state of output and
2816 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2817 // broadcasting the right event to other nodes in payment path.
2818 // A ------------------> B ----------------------> C (timeout)
2819 // B's commitment tx C's commitment tx
2821 // B's HTLC timeout tx B's timeout tx
2823 let chanmon_cfgs = create_chanmon_cfgs(3);
2824 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2825 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2826 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2827 *nodes[0].connect_style.borrow_mut() = connect_style;
2828 *nodes[1].connect_style.borrow_mut() = connect_style;
2829 *nodes[2].connect_style.borrow_mut() = connect_style;
2831 // Create some intial channels
2832 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2833 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2835 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2836 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2837 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2839 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2841 // Broadcast legit commitment tx from C on B's chain
2842 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2843 check_spends!(commitment_tx[0], chan_2.3);
2844 nodes[2].node.fail_htlc_backwards(&payment_hash);
2845 check_added_monitors!(nodes[2], 0);
2846 expect_pending_htlcs_forwardable!(nodes[2]);
2847 check_added_monitors!(nodes[2], 1);
2849 let events = nodes[2].node.get_and_clear_pending_msg_events();
2850 assert_eq!(events.len(), 1);
2852 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, .. } } => {
2853 assert!(update_add_htlcs.is_empty());
2854 assert!(!update_fail_htlcs.is_empty());
2855 assert!(update_fulfill_htlcs.is_empty());
2856 assert!(update_fail_malformed_htlcs.is_empty());
2857 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2859 _ => panic!("Unexpected event"),
2861 mine_transaction(&nodes[2], &commitment_tx[0]);
2862 check_closed_broadcast!(nodes[2], true);
2863 check_added_monitors!(nodes[2], 1);
2864 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2865 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2866 assert_eq!(node_txn.len(), 1);
2867 check_spends!(node_txn[0], chan_2.3);
2868 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2870 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2871 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2872 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2873 mine_transaction(&nodes[1], &commitment_tx[0]);
2874 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2877 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2878 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2879 assert_eq!(node_txn[0], node_txn[3]);
2880 assert_eq!(node_txn[1], node_txn[4]);
2882 check_spends!(node_txn[2], commitment_tx[0]);
2883 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2885 check_spends!(node_txn[0], chan_2.3);
2886 check_spends!(node_txn[1], node_txn[0]);
2887 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2888 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2890 timeout_tx = node_txn[2].clone();
2894 mine_transaction(&nodes[1], &timeout_tx);
2895 check_added_monitors!(nodes[1], 1);
2896 check_closed_broadcast!(nodes[1], true);
2898 // B will rebroadcast a fee-bumped timeout transaction here.
2899 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2900 assert_eq!(node_txn.len(), 1);
2901 check_spends!(node_txn[0], commitment_tx[0]);
2904 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2906 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2907 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2908 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2909 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2910 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2911 if node_txn.len() == 1 {
2912 check_spends!(node_txn[0], chan_2.3);
2914 assert_eq!(node_txn.len(), 0);
2918 expect_pending_htlcs_forwardable!(nodes[1]);
2919 check_added_monitors!(nodes[1], 1);
2920 let events = nodes[1].node.get_and_clear_pending_msg_events();
2921 assert_eq!(events.len(), 1);
2923 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, .. } } => {
2924 assert!(update_add_htlcs.is_empty());
2925 assert!(!update_fail_htlcs.is_empty());
2926 assert!(update_fulfill_htlcs.is_empty());
2927 assert!(update_fail_malformed_htlcs.is_empty());
2928 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2930 _ => panic!("Unexpected event"),
2933 // Broadcast legit commitment tx from B on A's chain
2934 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2935 check_spends!(commitment_tx[0], chan_1.3);
2937 mine_transaction(&nodes[0], &commitment_tx[0]);
2938 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2940 check_closed_broadcast!(nodes[0], true);
2941 check_added_monitors!(nodes[0], 1);
2942 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2943 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2944 assert_eq!(node_txn.len(), 2);
2945 check_spends!(node_txn[0], chan_1.3);
2946 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2947 check_spends!(node_txn[1], commitment_tx[0]);
2948 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2952 fn test_htlc_on_chain_timeout() {
2953 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2954 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2955 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2959 fn test_simple_commitment_revoked_fail_backward() {
2960 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2961 // and fail backward accordingly.
2963 let chanmon_cfgs = create_chanmon_cfgs(3);
2964 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2965 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2966 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2968 // Create some initial channels
2969 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2970 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2972 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2973 // Get the will-be-revoked local txn from nodes[2]
2974 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2975 // Revoke the old state
2976 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2978 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2980 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2981 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2982 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2983 check_added_monitors!(nodes[1], 1);
2984 check_closed_broadcast!(nodes[1], true);
2986 expect_pending_htlcs_forwardable!(nodes[1]);
2987 check_added_monitors!(nodes[1], 1);
2988 let events = nodes[1].node.get_and_clear_pending_msg_events();
2989 assert_eq!(events.len(), 1);
2991 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, .. } } => {
2992 assert!(update_add_htlcs.is_empty());
2993 assert_eq!(update_fail_htlcs.len(), 1);
2994 assert!(update_fulfill_htlcs.is_empty());
2995 assert!(update_fail_malformed_htlcs.is_empty());
2996 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2998 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2999 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3000 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3002 _ => panic!("Unexpected event"),
3006 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3007 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3008 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3009 // commitment transaction anymore.
3010 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3011 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3012 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3013 // technically disallowed and we should probably handle it reasonably.
3014 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3015 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3017 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3018 // commitment_signed (implying it will be in the latest remote commitment transaction).
3019 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3020 // and once they revoke the previous commitment transaction (allowing us to send a new
3021 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3022 let chanmon_cfgs = create_chanmon_cfgs(3);
3023 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3024 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3025 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3027 // Create some initial channels
3028 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3031 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 });
3032 // Get the will-be-revoked local txn from nodes[2]
3033 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3034 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3035 // Revoke the old state
3036 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3038 let value = if use_dust {
3039 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3040 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3041 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3044 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3045 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3046 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3048 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3049 expect_pending_htlcs_forwardable!(nodes[2]);
3050 check_added_monitors!(nodes[2], 1);
3051 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3052 assert!(updates.update_add_htlcs.is_empty());
3053 assert!(updates.update_fulfill_htlcs.is_empty());
3054 assert!(updates.update_fail_malformed_htlcs.is_empty());
3055 assert_eq!(updates.update_fail_htlcs.len(), 1);
3056 assert!(updates.update_fee.is_none());
3057 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3058 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3059 // Drop the last RAA from 3 -> 2
3061 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3062 expect_pending_htlcs_forwardable!(nodes[2]);
3063 check_added_monitors!(nodes[2], 1);
3064 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3065 assert!(updates.update_add_htlcs.is_empty());
3066 assert!(updates.update_fulfill_htlcs.is_empty());
3067 assert!(updates.update_fail_malformed_htlcs.is_empty());
3068 assert_eq!(updates.update_fail_htlcs.len(), 1);
3069 assert!(updates.update_fee.is_none());
3070 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3071 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3072 check_added_monitors!(nodes[1], 1);
3073 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3074 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3075 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3076 check_added_monitors!(nodes[2], 1);
3078 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3079 expect_pending_htlcs_forwardable!(nodes[2]);
3080 check_added_monitors!(nodes[2], 1);
3081 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3082 assert!(updates.update_add_htlcs.is_empty());
3083 assert!(updates.update_fulfill_htlcs.is_empty());
3084 assert!(updates.update_fail_malformed_htlcs.is_empty());
3085 assert_eq!(updates.update_fail_htlcs.len(), 1);
3086 assert!(updates.update_fee.is_none());
3087 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3088 // At this point first_payment_hash has dropped out of the latest two commitment
3089 // transactions that nodes[1] is tracking...
3090 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3091 check_added_monitors!(nodes[1], 1);
3092 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3093 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3094 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3095 check_added_monitors!(nodes[2], 1);
3097 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3098 // on nodes[2]'s RAA.
3099 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3100 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3101 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3102 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3103 check_added_monitors!(nodes[1], 0);
3106 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3107 // One monitor for the new revocation preimage, no second on as we won't generate a new
3108 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3109 check_added_monitors!(nodes[1], 1);
3110 let events = nodes[1].node.get_and_clear_pending_events();
3111 assert_eq!(events.len(), 1);
3113 Event::PendingHTLCsForwardable { .. } => { },
3114 _ => panic!("Unexpected event"),
3116 // Deliberately don't process the pending fail-back so they all fail back at once after
3117 // block connection just like the !deliver_bs_raa case
3120 let mut failed_htlcs = HashSet::new();
3121 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3123 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3124 check_added_monitors!(nodes[1], 1);
3125 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3126 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3128 let events = nodes[1].node.get_and_clear_pending_events();
3129 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3131 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3132 _ => panic!("Unexepected event"),
3135 Event::PaymentPathFailed { ref payment_hash, .. } => {
3136 assert_eq!(*payment_hash, fourth_payment_hash);
3138 _ => panic!("Unexpected event"),
3140 if !deliver_bs_raa {
3142 Event::PaymentFailed { ref payment_hash, .. } => {
3143 assert_eq!(*payment_hash, fourth_payment_hash);
3145 _ => panic!("Unexpected event"),
3148 Event::PendingHTLCsForwardable { .. } => { },
3149 _ => panic!("Unexpected event"),
3152 nodes[1].node.process_pending_htlc_forwards();
3153 check_added_monitors!(nodes[1], 1);
3155 let events = nodes[1].node.get_and_clear_pending_msg_events();
3156 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3157 match events[if deliver_bs_raa { 1 } else { 0 }] {
3158 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3159 _ => panic!("Unexpected event"),
3161 match events[if deliver_bs_raa { 2 } else { 1 }] {
3162 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3163 assert_eq!(channel_id, chan_2.2);
3164 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3166 _ => panic!("Unexpected event"),
3170 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, .. } } => {
3171 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3172 assert_eq!(update_add_htlcs.len(), 1);
3173 assert!(update_fulfill_htlcs.is_empty());
3174 assert!(update_fail_htlcs.is_empty());
3175 assert!(update_fail_malformed_htlcs.is_empty());
3177 _ => panic!("Unexpected event"),
3180 match events[if deliver_bs_raa { 3 } else { 2 }] {
3181 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, .. } } => {
3182 assert!(update_add_htlcs.is_empty());
3183 assert_eq!(update_fail_htlcs.len(), 3);
3184 assert!(update_fulfill_htlcs.is_empty());
3185 assert!(update_fail_malformed_htlcs.is_empty());
3186 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3188 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3189 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3190 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3192 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3194 let events = nodes[0].node.get_and_clear_pending_events();
3195 assert_eq!(events.len(), 3);
3197 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3198 assert!(failed_htlcs.insert(payment_hash.0));
3199 // If we delivered B's RAA we got an unknown preimage error, not something
3200 // that we should update our routing table for.
3201 if !deliver_bs_raa {
3202 assert!(network_update.is_some());
3205 _ => panic!("Unexpected event"),
3208 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3209 assert!(failed_htlcs.insert(payment_hash.0));
3210 assert!(network_update.is_some());
3212 _ => panic!("Unexpected event"),
3215 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3216 assert!(failed_htlcs.insert(payment_hash.0));
3217 assert!(network_update.is_some());
3219 _ => panic!("Unexpected event"),
3222 _ => panic!("Unexpected event"),
3225 assert!(failed_htlcs.contains(&first_payment_hash.0));
3226 assert!(failed_htlcs.contains(&second_payment_hash.0));
3227 assert!(failed_htlcs.contains(&third_payment_hash.0));
3231 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3232 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3233 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3234 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3235 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3239 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3240 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3241 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3242 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3243 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3247 fn fail_backward_pending_htlc_upon_channel_failure() {
3248 let chanmon_cfgs = create_chanmon_cfgs(2);
3249 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3250 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3251 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3252 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3254 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3256 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3257 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3258 check_added_monitors!(nodes[0], 1);
3260 let payment_event = {
3261 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3262 assert_eq!(events.len(), 1);
3263 SendEvent::from_event(events.remove(0))
3265 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3266 assert_eq!(payment_event.msgs.len(), 1);
3269 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3270 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3272 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3273 check_added_monitors!(nodes[0], 0);
3275 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3278 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3280 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3282 let secp_ctx = Secp256k1::new();
3283 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3284 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3285 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3286 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3287 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3289 // Send a 0-msat update_add_htlc to fail the channel.
3290 let update_add_htlc = msgs::UpdateAddHTLC {
3296 onion_routing_packet,
3298 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3300 let events = nodes[0].node.get_and_clear_pending_events();
3301 assert_eq!(events.len(), 2);
3302 // Check that Alice fails backward the pending HTLC from the second payment.
3304 Event::PaymentPathFailed { payment_hash, .. } => {
3305 assert_eq!(payment_hash, failed_payment_hash);
3307 _ => panic!("Unexpected event"),
3310 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3311 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3313 _ => panic!("Unexpected event {:?}", events[1]),
3315 check_closed_broadcast!(nodes[0], true);
3316 check_added_monitors!(nodes[0], 1);
3320 fn test_htlc_ignore_latest_remote_commitment() {
3321 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3322 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3323 let chanmon_cfgs = create_chanmon_cfgs(2);
3324 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3325 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3326 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3327 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3329 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3330 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3331 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3332 check_closed_broadcast!(nodes[0], true);
3333 check_added_monitors!(nodes[0], 1);
3334 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3336 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3337 assert_eq!(node_txn.len(), 3);
3338 assert_eq!(node_txn[0], node_txn[1]);
3340 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3341 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3342 check_closed_broadcast!(nodes[1], true);
3343 check_added_monitors!(nodes[1], 1);
3344 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3346 // Duplicate the connect_block call since this may happen due to other listeners
3347 // registering new transactions
3348 header.prev_blockhash = header.block_hash();
3349 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3353 fn test_force_close_fail_back() {
3354 // Check which HTLCs are failed-backwards on channel force-closure
3355 let chanmon_cfgs = create_chanmon_cfgs(3);
3356 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3357 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3358 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3359 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3360 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3362 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3364 let mut payment_event = {
3365 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3366 check_added_monitors!(nodes[0], 1);
3368 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3369 assert_eq!(events.len(), 1);
3370 SendEvent::from_event(events.remove(0))
3373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3374 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3376 expect_pending_htlcs_forwardable!(nodes[1]);
3378 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3379 assert_eq!(events_2.len(), 1);
3380 payment_event = SendEvent::from_event(events_2.remove(0));
3381 assert_eq!(payment_event.msgs.len(), 1);
3383 check_added_monitors!(nodes[1], 1);
3384 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3385 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3386 check_added_monitors!(nodes[2], 1);
3387 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3389 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3390 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3391 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3393 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3394 check_closed_broadcast!(nodes[2], true);
3395 check_added_monitors!(nodes[2], 1);
3396 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3398 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3399 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3400 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3401 // back to nodes[1] upon timeout otherwise.
3402 assert_eq!(node_txn.len(), 1);
3406 mine_transaction(&nodes[1], &tx);
3408 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3409 check_closed_broadcast!(nodes[1], true);
3410 check_added_monitors!(nodes[1], 1);
3411 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3413 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3415 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3416 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3418 mine_transaction(&nodes[2], &tx);
3419 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3420 assert_eq!(node_txn.len(), 1);
3421 assert_eq!(node_txn[0].input.len(), 1);
3422 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3423 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3424 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3426 check_spends!(node_txn[0], tx);
3430 fn test_dup_events_on_peer_disconnect() {
3431 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3432 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3433 // as we used to generate the event immediately upon receipt of the payment preimage in the
3434 // update_fulfill_htlc message.
3436 let chanmon_cfgs = create_chanmon_cfgs(2);
3437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3439 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3440 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3442 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3444 assert!(nodes[1].node.claim_funds(payment_preimage));
3445 check_added_monitors!(nodes[1], 1);
3446 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3447 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3448 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3450 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3451 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3453 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3454 expect_payment_path_successful!(nodes[0]);
3458 fn test_simple_peer_disconnect() {
3459 // Test that we can reconnect when there are no lost messages
3460 let chanmon_cfgs = create_chanmon_cfgs(3);
3461 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3462 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3463 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3464 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3465 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3467 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3468 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3469 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3471 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3472 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3473 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3474 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3476 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3477 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3478 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3480 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3481 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3482 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3483 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3485 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3486 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3488 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3489 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3491 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3493 let events = nodes[0].node.get_and_clear_pending_events();
3494 assert_eq!(events.len(), 3);
3496 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3497 assert_eq!(payment_preimage, payment_preimage_3);
3498 assert_eq!(payment_hash, payment_hash_3);
3500 _ => panic!("Unexpected event"),
3503 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3504 assert_eq!(payment_hash, payment_hash_5);
3505 assert!(rejected_by_dest);
3507 _ => panic!("Unexpected event"),
3510 Event::PaymentPathSuccessful { .. } => {},
3511 _ => panic!("Unexpected event"),
3515 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3516 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3519 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3520 // Test that we can reconnect when in-flight HTLC updates get dropped
3521 let chanmon_cfgs = create_chanmon_cfgs(2);
3522 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526 let mut as_funding_locked = None;
3527 if messages_delivered == 0 {
3528 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3529 as_funding_locked = Some(funding_locked);
3530 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3531 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3532 // it before the channel_reestablish message.
3534 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3537 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3539 let payment_event = {
3540 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3541 check_added_monitors!(nodes[0], 1);
3543 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3544 assert_eq!(events.len(), 1);
3545 SendEvent::from_event(events.remove(0))
3547 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3549 if messages_delivered < 2 {
3550 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3552 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3553 if messages_delivered >= 3 {
3554 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3555 check_added_monitors!(nodes[1], 1);
3556 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3558 if messages_delivered >= 4 {
3559 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3561 check_added_monitors!(nodes[0], 1);
3563 if messages_delivered >= 5 {
3564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3565 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3566 // No commitment_signed so get_event_msg's assert(len == 1) passes
3567 check_added_monitors!(nodes[0], 1);
3569 if messages_delivered >= 6 {
3570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3571 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3572 check_added_monitors!(nodes[1], 1);
3579 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3580 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3581 if messages_delivered < 3 {
3582 if simulate_broken_lnd {
3583 // lnd has a long-standing bug where they send a funding_locked prior to a
3584 // channel_reestablish if you reconnect prior to funding_locked time.
3586 // Here we simulate that behavior, delivering a funding_locked immediately on
3587 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3588 // in `reconnect_nodes` but we currently don't fail based on that.
3590 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3591 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3593 // Even if the funding_locked messages get exchanged, as long as nothing further was
3594 // received on either side, both sides will need to resend them.
3595 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596 } else if messages_delivered == 3 {
3597 // nodes[0] still wants its RAA + commitment_signed
3598 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3599 } else if messages_delivered == 4 {
3600 // nodes[0] still wants its commitment_signed
3601 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3602 } else if messages_delivered == 5 {
3603 // nodes[1] still wants its final RAA
3604 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3605 } else if messages_delivered == 6 {
3606 // Everything was delivered...
3607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3610 let events_1 = nodes[1].node.get_and_clear_pending_events();
3611 assert_eq!(events_1.len(), 1);
3613 Event::PendingHTLCsForwardable { .. } => { },
3614 _ => panic!("Unexpected event"),
3617 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3618 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3619 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3621 nodes[1].node.process_pending_htlc_forwards();
3623 let events_2 = nodes[1].node.get_and_clear_pending_events();
3624 assert_eq!(events_2.len(), 1);
3626 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3627 assert_eq!(payment_hash_1, *payment_hash);
3628 assert_eq!(amt, 1000000);
3630 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3631 assert!(payment_preimage.is_none());
3632 assert_eq!(payment_secret_1, *payment_secret);
3634 _ => panic!("expected PaymentPurpose::InvoicePayment")
3637 _ => panic!("Unexpected event"),
3640 nodes[1].node.claim_funds(payment_preimage_1);
3641 check_added_monitors!(nodes[1], 1);
3643 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3644 assert_eq!(events_3.len(), 1);
3645 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3646 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3647 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3648 assert!(updates.update_add_htlcs.is_empty());
3649 assert!(updates.update_fail_htlcs.is_empty());
3650 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3651 assert!(updates.update_fail_malformed_htlcs.is_empty());
3652 assert!(updates.update_fee.is_none());
3653 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3655 _ => panic!("Unexpected event"),
3658 if messages_delivered >= 1 {
3659 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3661 let events_4 = nodes[0].node.get_and_clear_pending_events();
3662 assert_eq!(events_4.len(), 1);
3664 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3665 assert_eq!(payment_preimage_1, *payment_preimage);
3666 assert_eq!(payment_hash_1, *payment_hash);
3668 _ => panic!("Unexpected event"),
3671 if messages_delivered >= 2 {
3672 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3673 check_added_monitors!(nodes[0], 1);
3674 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3676 if messages_delivered >= 3 {
3677 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3678 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3679 check_added_monitors!(nodes[1], 1);
3681 if messages_delivered >= 4 {
3682 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3683 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3684 // No commitment_signed so get_event_msg's assert(len == 1) passes
3685 check_added_monitors!(nodes[1], 1);
3687 if messages_delivered >= 5 {
3688 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3689 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3690 check_added_monitors!(nodes[0], 1);
3697 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3698 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3699 if messages_delivered < 2 {
3700 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701 if messages_delivered < 1 {
3702 expect_payment_sent!(nodes[0], payment_preimage_1);
3704 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3706 } else if messages_delivered == 2 {
3707 // nodes[0] still wants its RAA + commitment_signed
3708 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3709 } else if messages_delivered == 3 {
3710 // nodes[0] still wants its commitment_signed
3711 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712 } else if messages_delivered == 4 {
3713 // nodes[1] still wants its final RAA
3714 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3715 } else if messages_delivered == 5 {
3716 // Everything was delivered...
3717 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720 if messages_delivered == 1 || messages_delivered == 2 {
3721 expect_payment_path_successful!(nodes[0]);
3724 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3725 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3726 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728 if messages_delivered > 2 {
3729 expect_payment_path_successful!(nodes[0]);
3732 // Channel should still work fine...
3733 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3734 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3735 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3739 fn test_drop_messages_peer_disconnect_a() {
3740 do_test_drop_messages_peer_disconnect(0, true);
3741 do_test_drop_messages_peer_disconnect(0, false);
3742 do_test_drop_messages_peer_disconnect(1, false);
3743 do_test_drop_messages_peer_disconnect(2, false);
3747 fn test_drop_messages_peer_disconnect_b() {
3748 do_test_drop_messages_peer_disconnect(3, false);
3749 do_test_drop_messages_peer_disconnect(4, false);
3750 do_test_drop_messages_peer_disconnect(5, false);
3751 do_test_drop_messages_peer_disconnect(6, false);
3755 fn test_funding_peer_disconnect() {
3756 // Test that we can lock in our funding tx while disconnected
3757 let chanmon_cfgs = create_chanmon_cfgs(2);
3758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3760 let persister: test_utils::TestPersister;
3761 let new_chain_monitor: test_utils::TestChainMonitor;
3762 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3764 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3766 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3767 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3769 confirm_transaction(&nodes[0], &tx);
3770 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3771 assert!(events_1.is_empty());
3773 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3775 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3776 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3778 confirm_transaction(&nodes[1], &tx);
3779 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3780 assert!(events_2.is_empty());
3782 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3783 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3784 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3785 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3787 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3788 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3789 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3790 assert_eq!(events_3.len(), 1);
3791 let as_funding_locked = match events_3[0] {
3792 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3793 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3796 _ => panic!("Unexpected event {:?}", events_3[0]),
3799 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3800 // announcement_signatures as well as channel_update.
3801 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3802 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3803 assert_eq!(events_4.len(), 3);
3805 let bs_funding_locked = match events_4[0] {
3806 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3807 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3808 chan_id = msg.channel_id;
3811 _ => panic!("Unexpected event {:?}", events_4[0]),
3813 let bs_announcement_sigs = match events_4[1] {
3814 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3815 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3818 _ => panic!("Unexpected event {:?}", events_4[1]),
3821 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3822 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3824 _ => panic!("Unexpected event {:?}", events_4[2]),
3827 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3828 // generates a duplicative private channel_update
3829 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3830 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3831 assert_eq!(events_5.len(), 1);
3833 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3834 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3836 _ => panic!("Unexpected event {:?}", events_5[0]),
3839 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3840 // announcement_signatures.
3841 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3842 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3843 assert_eq!(events_6.len(), 1);
3844 let as_announcement_sigs = match events_6[0] {
3845 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3846 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3849 _ => panic!("Unexpected event {:?}", events_6[0]),
3852 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3853 // broadcast the channel announcement globally, as well as re-send its (now-public)
3855 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3856 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3857 assert_eq!(events_7.len(), 1);
3858 let (chan_announcement, as_update) = match events_7[0] {
3859 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3860 (msg.clone(), update_msg.clone())
3862 _ => panic!("Unexpected event {:?}", events_7[0]),
3865 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3866 // same channel_announcement.
3867 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3868 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3869 assert_eq!(events_8.len(), 1);
3870 let bs_update = match events_8[0] {
3871 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3872 assert_eq!(*msg, chan_announcement);
3875 _ => panic!("Unexpected event {:?}", events_8[0]),
3878 // Provide the channel announcement and public updates to the network graph
3879 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3880 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3881 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3883 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3884 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3885 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3887 // Check that after deserialization and reconnection we can still generate an identical
3888 // channel_announcement from the cached signatures.
3889 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3891 let nodes_0_serialized = nodes[0].node.encode();
3892 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3893 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3895 persister = test_utils::TestPersister::new();
3896 let keys_manager = &chanmon_cfgs[0].keys_manager;
3897 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);
3898 nodes[0].chain_monitor = &new_chain_monitor;
3899 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3900 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3901 &mut chan_0_monitor_read, keys_manager).unwrap();
3902 assert!(chan_0_monitor_read.is_empty());
3904 let mut nodes_0_read = &nodes_0_serialized[..];
3905 let (_, nodes_0_deserialized_tmp) = {
3906 let mut channel_monitors = HashMap::new();
3907 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3908 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3909 default_config: UserConfig::default(),
3911 fee_estimator: node_cfgs[0].fee_estimator,
3912 chain_monitor: nodes[0].chain_monitor,
3913 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3914 logger: nodes[0].logger,
3918 nodes_0_deserialized = nodes_0_deserialized_tmp;
3919 assert!(nodes_0_read.is_empty());
3921 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3922 nodes[0].node = &nodes_0_deserialized;
3923 check_added_monitors!(nodes[0], 1);
3925 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3927 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3928 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3929 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3930 let mut found_announcement = false;
3931 for event in msgs.iter() {
3933 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3934 if *msg == chan_announcement { found_announcement = true; }
3936 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3937 _ => panic!("Unexpected event"),
3940 assert!(found_announcement);
3944 fn test_funding_locked_without_best_block_updated() {
3945 // Previously, if we were offline when a funding transaction was locked in, and then we came
3946 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3947 // generate a funding_locked until a later best_block_updated. This tests that we generate the
3948 // funding_locked immediately instead.
3949 let chanmon_cfgs = create_chanmon_cfgs(2);
3950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3952 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3953 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3955 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
3957 let conf_height = nodes[0].best_block_info().1 + 1;
3958 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3959 let block_txn = [funding_tx];
3960 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3961 let conf_block_header = nodes[0].get_block_header(conf_height);
3962 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3964 // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
3965 let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
3966 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3970 fn test_drop_messages_peer_disconnect_dual_htlc() {
3971 // Test that we can handle reconnecting when both sides of a channel have pending
3972 // commitment_updates when we disconnect.
3973 let chanmon_cfgs = create_chanmon_cfgs(2);
3974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3976 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3977 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3979 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3981 // Now try to send a second payment which will fail to send
3982 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3983 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3984 check_added_monitors!(nodes[0], 1);
3986 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3987 assert_eq!(events_1.len(), 1);
3989 MessageSendEvent::UpdateHTLCs { .. } => {},
3990 _ => panic!("Unexpected event"),
3993 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3994 check_added_monitors!(nodes[1], 1);
3996 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3997 assert_eq!(events_2.len(), 1);
3999 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 } } => {
4000 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4001 assert!(update_add_htlcs.is_empty());
4002 assert_eq!(update_fulfill_htlcs.len(), 1);
4003 assert!(update_fail_htlcs.is_empty());
4004 assert!(update_fail_malformed_htlcs.is_empty());
4005 assert!(update_fee.is_none());
4007 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4008 let events_3 = nodes[0].node.get_and_clear_pending_events();
4009 assert_eq!(events_3.len(), 1);
4011 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4012 assert_eq!(*payment_preimage, payment_preimage_1);
4013 assert_eq!(*payment_hash, payment_hash_1);
4015 _ => panic!("Unexpected event"),
4018 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4019 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4020 // No commitment_signed so get_event_msg's assert(len == 1) passes
4021 check_added_monitors!(nodes[0], 1);
4023 _ => panic!("Unexpected event"),
4026 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4027 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4029 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4030 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4031 assert_eq!(reestablish_1.len(), 1);
4032 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4033 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4034 assert_eq!(reestablish_2.len(), 1);
4036 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4037 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4038 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4039 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4041 assert!(as_resp.0.is_none());
4042 assert!(bs_resp.0.is_none());
4044 assert!(bs_resp.1.is_none());
4045 assert!(bs_resp.2.is_none());
4047 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4049 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4050 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4051 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4052 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4053 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4054 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4055 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4056 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4057 // No commitment_signed so get_event_msg's assert(len == 1) passes
4058 check_added_monitors!(nodes[1], 1);
4060 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4061 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4062 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4063 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4064 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4065 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4066 assert!(bs_second_commitment_signed.update_fee.is_none());
4067 check_added_monitors!(nodes[1], 1);
4069 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4070 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4071 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4072 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4073 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4074 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4075 assert!(as_commitment_signed.update_fee.is_none());
4076 check_added_monitors!(nodes[0], 1);
4078 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4079 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4080 // No commitment_signed so get_event_msg's assert(len == 1) passes
4081 check_added_monitors!(nodes[0], 1);
4083 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4084 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4085 // No commitment_signed so get_event_msg's assert(len == 1) passes
4086 check_added_monitors!(nodes[1], 1);
4088 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4089 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4090 check_added_monitors!(nodes[1], 1);
4092 expect_pending_htlcs_forwardable!(nodes[1]);
4094 let events_5 = nodes[1].node.get_and_clear_pending_events();
4095 assert_eq!(events_5.len(), 1);
4097 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4098 assert_eq!(payment_hash_2, *payment_hash);
4100 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4101 assert!(payment_preimage.is_none());
4102 assert_eq!(payment_secret_2, *payment_secret);
4104 _ => panic!("expected PaymentPurpose::InvoicePayment")
4107 _ => panic!("Unexpected event"),
4110 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4111 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4112 check_added_monitors!(nodes[0], 1);
4114 expect_payment_path_successful!(nodes[0]);
4115 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4118 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4119 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4120 // to avoid our counterparty failing the channel.
4121 let chanmon_cfgs = create_chanmon_cfgs(2);
4122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4126 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4128 let our_payment_hash = if send_partial_mpp {
4129 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4130 // Use the utility function send_payment_along_path to send the payment with MPP data which
4131 // indicates there are more HTLCs coming.
4132 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.
4133 let payment_id = PaymentId([42; 32]);
4134 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();
4135 check_added_monitors!(nodes[0], 1);
4136 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4137 assert_eq!(events.len(), 1);
4138 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4139 // hop should *not* yet generate any PaymentReceived event(s).
4140 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4143 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4146 let mut block = Block {
4147 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4150 connect_block(&nodes[0], &block);
4151 connect_block(&nodes[1], &block);
4152 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4153 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4154 block.header.prev_blockhash = block.block_hash();
4155 connect_block(&nodes[0], &block);
4156 connect_block(&nodes[1], &block);
4159 expect_pending_htlcs_forwardable!(nodes[1]);
4161 check_added_monitors!(nodes[1], 1);
4162 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4163 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4164 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4165 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4166 assert!(htlc_timeout_updates.update_fee.is_none());
4168 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4169 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4170 // 100_000 msat as u64, followed by the height at which we failed back above
4171 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4172 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4173 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4177 fn test_htlc_timeout() {
4178 do_test_htlc_timeout(true);
4179 do_test_htlc_timeout(false);
4182 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4183 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4184 let chanmon_cfgs = create_chanmon_cfgs(3);
4185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4187 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4188 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4189 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4191 // Make sure all nodes are at the same starting height
4192 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4193 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4194 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4196 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4197 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4199 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4201 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4202 check_added_monitors!(nodes[1], 1);
4204 // Now attempt to route a second payment, which should be placed in the holding cell
4205 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4206 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4207 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4209 check_added_monitors!(nodes[0], 1);
4210 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4211 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4212 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4213 expect_pending_htlcs_forwardable!(nodes[1]);
4215 check_added_monitors!(nodes[1], 0);
4217 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4218 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4219 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4220 connect_blocks(&nodes[1], 1);
4223 expect_pending_htlcs_forwardable!(nodes[1]);
4224 check_added_monitors!(nodes[1], 1);
4225 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4226 assert_eq!(fail_commit.len(), 1);
4227 match fail_commit[0] {
4228 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4230 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4232 _ => unreachable!(),
4234 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4236 let events = nodes[1].node.get_and_clear_pending_events();
4237 assert_eq!(events.len(), 2);
4238 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4239 assert_eq!(*payment_hash, second_payment_hash);
4240 } else { panic!("Unexpected event"); }
4241 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4242 assert_eq!(*payment_hash, second_payment_hash);
4243 } else { panic!("Unexpected event"); }
4248 fn test_holding_cell_htlc_add_timeouts() {
4249 do_test_holding_cell_htlc_add_timeouts(false);
4250 do_test_holding_cell_htlc_add_timeouts(true);
4254 fn test_no_txn_manager_serialize_deserialize() {
4255 let chanmon_cfgs = create_chanmon_cfgs(2);
4256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4258 let logger: test_utils::TestLogger;
4259 let fee_estimator: test_utils::TestFeeEstimator;
4260 let persister: test_utils::TestPersister;
4261 let new_chain_monitor: test_utils::TestChainMonitor;
4262 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4263 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4265 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4267 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4269 let nodes_0_serialized = nodes[0].node.encode();
4270 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4271 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4272 .write(&mut chan_0_monitor_serialized).unwrap();
4274 logger = test_utils::TestLogger::new();
4275 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4276 persister = test_utils::TestPersister::new();
4277 let keys_manager = &chanmon_cfgs[0].keys_manager;
4278 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4279 nodes[0].chain_monitor = &new_chain_monitor;
4280 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4281 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4282 &mut chan_0_monitor_read, keys_manager).unwrap();
4283 assert!(chan_0_monitor_read.is_empty());
4285 let mut nodes_0_read = &nodes_0_serialized[..];
4286 let config = UserConfig::default();
4287 let (_, nodes_0_deserialized_tmp) = {
4288 let mut channel_monitors = HashMap::new();
4289 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4290 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4291 default_config: config,
4293 fee_estimator: &fee_estimator,
4294 chain_monitor: nodes[0].chain_monitor,
4295 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4300 nodes_0_deserialized = nodes_0_deserialized_tmp;
4301 assert!(nodes_0_read.is_empty());
4303 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4304 nodes[0].node = &nodes_0_deserialized;
4305 assert_eq!(nodes[0].node.list_channels().len(), 1);
4306 check_added_monitors!(nodes[0], 1);
4308 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4309 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4310 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4311 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4313 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4314 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4315 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4316 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4318 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4319 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4320 for node in nodes.iter() {
4321 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4322 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4323 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4326 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4330 fn test_manager_serialize_deserialize_events() {
4331 // This test makes sure the events field in ChannelManager survives de/serialization
4332 let chanmon_cfgs = create_chanmon_cfgs(2);
4333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4335 let fee_estimator: test_utils::TestFeeEstimator;
4336 let persister: test_utils::TestPersister;
4337 let logger: test_utils::TestLogger;
4338 let new_chain_monitor: test_utils::TestChainMonitor;
4339 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4342 // Start creating a channel, but stop right before broadcasting the funding transaction
4343 let channel_value = 100000;
4344 let push_msat = 10001;
4345 let a_flags = InitFeatures::known();
4346 let b_flags = InitFeatures::known();
4347 let node_a = nodes.remove(0);
4348 let node_b = nodes.remove(0);
4349 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4350 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()));
4351 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()));
4353 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4355 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4356 check_added_monitors!(node_a, 0);
4358 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()));
4360 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4361 assert_eq!(added_monitors.len(), 1);
4362 assert_eq!(added_monitors[0].0, funding_output);
4363 added_monitors.clear();
4366 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4367 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4369 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4370 assert_eq!(added_monitors.len(), 1);
4371 assert_eq!(added_monitors[0].0, funding_output);
4372 added_monitors.clear();
4374 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4379 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4380 let nodes_0_serialized = nodes[0].node.encode();
4381 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4382 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4384 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4385 logger = test_utils::TestLogger::new();
4386 persister = test_utils::TestPersister::new();
4387 let keys_manager = &chanmon_cfgs[0].keys_manager;
4388 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4389 nodes[0].chain_monitor = &new_chain_monitor;
4390 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4391 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4392 &mut chan_0_monitor_read, keys_manager).unwrap();
4393 assert!(chan_0_monitor_read.is_empty());
4395 let mut nodes_0_read = &nodes_0_serialized[..];
4396 let config = UserConfig::default();
4397 let (_, nodes_0_deserialized_tmp) = {
4398 let mut channel_monitors = HashMap::new();
4399 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4400 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4401 default_config: config,
4403 fee_estimator: &fee_estimator,
4404 chain_monitor: nodes[0].chain_monitor,
4405 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4410 nodes_0_deserialized = nodes_0_deserialized_tmp;
4411 assert!(nodes_0_read.is_empty());
4413 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4415 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4416 nodes[0].node = &nodes_0_deserialized;
4418 // After deserializing, make sure the funding_transaction is still held by the channel manager
4419 let events_4 = nodes[0].node.get_and_clear_pending_events();
4420 assert_eq!(events_4.len(), 0);
4421 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4422 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4424 // Make sure the channel is functioning as though the de/serialization never happened
4425 assert_eq!(nodes[0].node.list_channels().len(), 1);
4426 check_added_monitors!(nodes[0], 1);
4428 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4429 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4430 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4431 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4433 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4434 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4435 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4436 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4438 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4439 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4440 for node in nodes.iter() {
4441 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4442 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4443 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4446 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4450 fn test_simple_manager_serialize_deserialize() {
4451 let chanmon_cfgs = create_chanmon_cfgs(2);
4452 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4453 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4454 let logger: test_utils::TestLogger;
4455 let fee_estimator: test_utils::TestFeeEstimator;
4456 let persister: test_utils::TestPersister;
4457 let new_chain_monitor: test_utils::TestChainMonitor;
4458 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4459 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4460 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4462 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4463 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4465 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4467 let nodes_0_serialized = nodes[0].node.encode();
4468 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4469 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4471 logger = test_utils::TestLogger::new();
4472 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4473 persister = test_utils::TestPersister::new();
4474 let keys_manager = &chanmon_cfgs[0].keys_manager;
4475 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4476 nodes[0].chain_monitor = &new_chain_monitor;
4477 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4478 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4479 &mut chan_0_monitor_read, keys_manager).unwrap();
4480 assert!(chan_0_monitor_read.is_empty());
4482 let mut nodes_0_read = &nodes_0_serialized[..];
4483 let (_, nodes_0_deserialized_tmp) = {
4484 let mut channel_monitors = HashMap::new();
4485 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4486 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4487 default_config: UserConfig::default(),
4489 fee_estimator: &fee_estimator,
4490 chain_monitor: nodes[0].chain_monitor,
4491 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4496 nodes_0_deserialized = nodes_0_deserialized_tmp;
4497 assert!(nodes_0_read.is_empty());
4499 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4500 nodes[0].node = &nodes_0_deserialized;
4501 check_added_monitors!(nodes[0], 1);
4503 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4505 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4506 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4510 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4511 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4512 let chanmon_cfgs = create_chanmon_cfgs(4);
4513 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4514 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4515 let logger: test_utils::TestLogger;
4516 let fee_estimator: test_utils::TestFeeEstimator;
4517 let persister: test_utils::TestPersister;
4518 let new_chain_monitor: test_utils::TestChainMonitor;
4519 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4520 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4521 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4522 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4523 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4525 let mut node_0_stale_monitors_serialized = Vec::new();
4526 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4527 let mut writer = test_utils::TestVecWriter(Vec::new());
4528 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4529 node_0_stale_monitors_serialized.push(writer.0);
4532 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4534 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4535 let nodes_0_serialized = nodes[0].node.encode();
4537 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4538 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4539 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4540 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4542 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4544 let mut node_0_monitors_serialized = Vec::new();
4545 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4546 let mut writer = test_utils::TestVecWriter(Vec::new());
4547 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4548 node_0_monitors_serialized.push(writer.0);
4551 logger = test_utils::TestLogger::new();
4552 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4553 persister = test_utils::TestPersister::new();
4554 let keys_manager = &chanmon_cfgs[0].keys_manager;
4555 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4556 nodes[0].chain_monitor = &new_chain_monitor;
4559 let mut node_0_stale_monitors = Vec::new();
4560 for serialized in node_0_stale_monitors_serialized.iter() {
4561 let mut read = &serialized[..];
4562 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4563 assert!(read.is_empty());
4564 node_0_stale_monitors.push(monitor);
4567 let mut node_0_monitors = Vec::new();
4568 for serialized in node_0_monitors_serialized.iter() {
4569 let mut read = &serialized[..];
4570 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4571 assert!(read.is_empty());
4572 node_0_monitors.push(monitor);
4575 let mut nodes_0_read = &nodes_0_serialized[..];
4576 if let Err(msgs::DecodeError::InvalidValue) =
4577 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4578 default_config: UserConfig::default(),
4580 fee_estimator: &fee_estimator,
4581 chain_monitor: nodes[0].chain_monitor,
4582 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4584 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4586 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4589 let mut nodes_0_read = &nodes_0_serialized[..];
4590 let (_, nodes_0_deserialized_tmp) =
4591 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4592 default_config: UserConfig::default(),
4594 fee_estimator: &fee_estimator,
4595 chain_monitor: nodes[0].chain_monitor,
4596 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4598 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4600 nodes_0_deserialized = nodes_0_deserialized_tmp;
4601 assert!(nodes_0_read.is_empty());
4603 { // Channel close should result in a commitment tx
4604 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4605 assert_eq!(txn.len(), 1);
4606 check_spends!(txn[0], funding_tx);
4607 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4610 for monitor in node_0_monitors.drain(..) {
4611 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4612 check_added_monitors!(nodes[0], 1);
4614 nodes[0].node = &nodes_0_deserialized;
4615 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4617 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4618 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4619 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4620 //... and we can even still claim the payment!
4621 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4623 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4624 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4625 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4626 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4627 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4628 assert_eq!(msg_events.len(), 1);
4629 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4631 &ErrorAction::SendErrorMessage { ref msg } => {
4632 assert_eq!(msg.channel_id, channel_id);
4634 _ => panic!("Unexpected event!"),
4639 macro_rules! check_spendable_outputs {
4640 ($node: expr, $keysinterface: expr) => {
4642 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4643 let mut txn = Vec::new();
4644 let mut all_outputs = Vec::new();
4645 let secp_ctx = Secp256k1::new();
4646 for event in events.drain(..) {
4648 Event::SpendableOutputs { mut outputs } => {
4649 for outp in outputs.drain(..) {
4650 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4651 all_outputs.push(outp);
4654 _ => panic!("Unexpected event"),
4657 if all_outputs.len() > 1 {
4658 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) {
4668 fn test_claim_sizeable_push_msat() {
4669 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4670 let chanmon_cfgs = create_chanmon_cfgs(2);
4671 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4672 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4673 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4675 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4676 nodes[1].node.force_close_channel(&chan.2).unwrap();
4677 check_closed_broadcast!(nodes[1], true);
4678 check_added_monitors!(nodes[1], 1);
4679 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4680 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4681 assert_eq!(node_txn.len(), 1);
4682 check_spends!(node_txn[0], chan.3);
4683 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
4685 mine_transaction(&nodes[1], &node_txn[0]);
4686 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4688 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4689 assert_eq!(spend_txn.len(), 1);
4690 assert_eq!(spend_txn[0].input.len(), 1);
4691 check_spends!(spend_txn[0], node_txn[0]);
4692 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4696 fn test_claim_on_remote_sizeable_push_msat() {
4697 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4698 // to_remote output is encumbered by a P2WPKH
4699 let chanmon_cfgs = create_chanmon_cfgs(2);
4700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4704 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4705 nodes[0].node.force_close_channel(&chan.2).unwrap();
4706 check_closed_broadcast!(nodes[0], true);
4707 check_added_monitors!(nodes[0], 1);
4708 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4710 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4711 assert_eq!(node_txn.len(), 1);
4712 check_spends!(node_txn[0], chan.3);
4713 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
4715 mine_transaction(&nodes[1], &node_txn[0]);
4716 check_closed_broadcast!(nodes[1], true);
4717 check_added_monitors!(nodes[1], 1);
4718 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4719 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4721 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4722 assert_eq!(spend_txn.len(), 1);
4723 check_spends!(spend_txn[0], node_txn[0]);
4727 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4728 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4729 // to_remote output is encumbered by a P2WPKH
4731 let chanmon_cfgs = create_chanmon_cfgs(2);
4732 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4733 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4734 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4736 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4737 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4738 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4739 assert_eq!(revoked_local_txn[0].input.len(), 1);
4740 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4742 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4743 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4744 check_closed_broadcast!(nodes[1], true);
4745 check_added_monitors!(nodes[1], 1);
4746 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4748 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4749 mine_transaction(&nodes[1], &node_txn[0]);
4750 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4752 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4753 assert_eq!(spend_txn.len(), 3);
4754 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4755 check_spends!(spend_txn[1], node_txn[0]);
4756 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4760 fn test_static_spendable_outputs_preimage_tx() {
4761 let chanmon_cfgs = create_chanmon_cfgs(2);
4762 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4763 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4764 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4766 // Create some initial channels
4767 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4769 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4771 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4772 assert_eq!(commitment_tx[0].input.len(), 1);
4773 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4775 // Settle A's commitment tx on B's chain
4776 assert!(nodes[1].node.claim_funds(payment_preimage));
4777 check_added_monitors!(nodes[1], 1);
4778 mine_transaction(&nodes[1], &commitment_tx[0]);
4779 check_added_monitors!(nodes[1], 1);
4780 let events = nodes[1].node.get_and_clear_pending_msg_events();
4782 MessageSendEvent::UpdateHTLCs { .. } => {},
4783 _ => panic!("Unexpected event"),
4786 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4787 _ => panic!("Unexepected event"),
4790 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4791 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4792 assert_eq!(node_txn.len(), 3);
4793 check_spends!(node_txn[0], commitment_tx[0]);
4794 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4795 check_spends!(node_txn[1], chan_1.3);
4796 check_spends!(node_txn[2], node_txn[1]);
4798 mine_transaction(&nodes[1], &node_txn[0]);
4799 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4800 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4802 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4803 assert_eq!(spend_txn.len(), 1);
4804 check_spends!(spend_txn[0], node_txn[0]);
4808 fn test_static_spendable_outputs_timeout_tx() {
4809 let chanmon_cfgs = create_chanmon_cfgs(2);
4810 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4811 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4812 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4814 // Create some initial channels
4815 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4817 // Rebalance the network a bit by relaying one payment through all the channels ...
4818 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4820 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4822 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4823 assert_eq!(commitment_tx[0].input.len(), 1);
4824 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4826 // Settle A's commitment tx on B' chain
4827 mine_transaction(&nodes[1], &commitment_tx[0]);
4828 check_added_monitors!(nodes[1], 1);
4829 let events = nodes[1].node.get_and_clear_pending_msg_events();
4831 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4832 _ => panic!("Unexpected event"),
4834 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4836 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4837 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4838 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4839 check_spends!(node_txn[0], chan_1.3.clone());
4840 check_spends!(node_txn[1], commitment_tx[0].clone());
4841 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4843 mine_transaction(&nodes[1], &node_txn[1]);
4844 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4845 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4846 expect_payment_failed!(nodes[1], our_payment_hash, true);
4848 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4849 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4850 check_spends!(spend_txn[0], commitment_tx[0]);
4851 check_spends!(spend_txn[1], node_txn[1]);
4852 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4856 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4857 let chanmon_cfgs = create_chanmon_cfgs(2);
4858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4862 // Create some initial channels
4863 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4865 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4866 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4867 assert_eq!(revoked_local_txn[0].input.len(), 1);
4868 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4870 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4872 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4873 check_closed_broadcast!(nodes[1], true);
4874 check_added_monitors!(nodes[1], 1);
4875 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4877 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4878 assert_eq!(node_txn.len(), 2);
4879 assert_eq!(node_txn[0].input.len(), 2);
4880 check_spends!(node_txn[0], revoked_local_txn[0]);
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(), 1);
4887 check_spends!(spend_txn[0], node_txn[0]);
4891 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4892 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4893 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4894 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4895 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4896 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4898 // Create some initial channels
4899 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4901 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4902 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4903 assert_eq!(revoked_local_txn[0].input.len(), 1);
4904 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4906 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4908 // A will generate HTLC-Timeout from revoked commitment tx
4909 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4910 check_closed_broadcast!(nodes[0], true);
4911 check_added_monitors!(nodes[0], 1);
4912 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4913 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4915 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4916 assert_eq!(revoked_htlc_txn.len(), 2);
4917 check_spends!(revoked_htlc_txn[0], chan_1.3);
4918 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4919 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4920 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4921 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4923 // B will generate justice tx from A's revoked commitment/HTLC tx
4924 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4925 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4926 check_closed_broadcast!(nodes[1], true);
4927 check_added_monitors!(nodes[1], 1);
4928 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4930 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4931 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4932 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4933 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4934 // transactions next...
4935 assert_eq!(node_txn[0].input.len(), 3);
4936 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4938 assert_eq!(node_txn[1].input.len(), 2);
4939 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4940 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4941 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4943 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4944 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4947 assert_eq!(node_txn[2].input.len(), 1);
4948 check_spends!(node_txn[2], chan_1.3);
4950 mine_transaction(&nodes[1], &node_txn[1]);
4951 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4953 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4954 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4955 assert_eq!(spend_txn.len(), 1);
4956 assert_eq!(spend_txn[0].input.len(), 1);
4957 check_spends!(spend_txn[0], node_txn[1]);
4961 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4962 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4963 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4964 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4965 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4966 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4968 // Create some initial channels
4969 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4971 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4972 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4973 assert_eq!(revoked_local_txn[0].input.len(), 1);
4974 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4976 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4977 assert_eq!(revoked_local_txn[0].output.len(), 2);
4979 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4981 // B will generate HTLC-Success from revoked commitment tx
4982 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4983 check_closed_broadcast!(nodes[1], true);
4984 check_added_monitors!(nodes[1], 1);
4985 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4986 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4988 assert_eq!(revoked_htlc_txn.len(), 2);
4989 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4990 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4991 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4993 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4994 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4995 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4997 // A will generate justice tx from B's revoked commitment/HTLC tx
4998 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4999 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5000 check_closed_broadcast!(nodes[0], true);
5001 check_added_monitors!(nodes[0], 1);
5002 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5004 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5005 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5007 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5008 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5009 // transactions next...
5010 assert_eq!(node_txn[0].input.len(), 2);
5011 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5012 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5013 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5015 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5016 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5019 assert_eq!(node_txn[1].input.len(), 1);
5020 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5022 check_spends!(node_txn[2], chan_1.3);
5024 mine_transaction(&nodes[0], &node_txn[1]);
5025 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5027 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5028 // didn't try to generate any new transactions.
5030 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5031 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5032 assert_eq!(spend_txn.len(), 3);
5033 assert_eq!(spend_txn[0].input.len(), 1);
5034 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5035 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5036 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5037 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5041 fn test_onchain_to_onchain_claim() {
5042 // Test that in case of channel closure, we detect the state of output and claim HTLC
5043 // on downstream peer's remote commitment tx.
5044 // First, have C claim an HTLC against its own latest commitment transaction.
5045 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5047 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5050 let chanmon_cfgs = create_chanmon_cfgs(3);
5051 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5052 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5053 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5055 // Create some initial channels
5056 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5057 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5059 // Ensure all nodes are at the same height
5060 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5061 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5062 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5063 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5065 // Rebalance the network a bit by relaying one payment through all the channels ...
5066 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5067 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5069 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5070 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5071 check_spends!(commitment_tx[0], chan_2.3);
5072 nodes[2].node.claim_funds(payment_preimage);
5073 check_added_monitors!(nodes[2], 1);
5074 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5075 assert!(updates.update_add_htlcs.is_empty());
5076 assert!(updates.update_fail_htlcs.is_empty());
5077 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5078 assert!(updates.update_fail_malformed_htlcs.is_empty());
5080 mine_transaction(&nodes[2], &commitment_tx[0]);
5081 check_closed_broadcast!(nodes[2], true);
5082 check_added_monitors!(nodes[2], 1);
5083 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5085 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5086 assert_eq!(c_txn.len(), 3);
5087 assert_eq!(c_txn[0], c_txn[2]);
5088 assert_eq!(commitment_tx[0], c_txn[1]);
5089 check_spends!(c_txn[1], chan_2.3);
5090 check_spends!(c_txn[2], c_txn[1]);
5091 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5092 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5093 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5094 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5096 // 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
5097 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5098 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5099 check_added_monitors!(nodes[1], 1);
5100 let events = nodes[1].node.get_and_clear_pending_events();
5101 assert_eq!(events.len(), 2);
5103 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5104 _ => panic!("Unexpected event"),
5107 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5108 assert_eq!(fee_earned_msat, Some(1000));
5109 assert_eq!(claim_from_onchain_tx, true);
5111 _ => panic!("Unexpected event"),
5114 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5115 // ChannelMonitor: claim tx
5116 assert_eq!(b_txn.len(), 1);
5117 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5120 check_added_monitors!(nodes[1], 1);
5121 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5122 assert_eq!(msg_events.len(), 3);
5123 match msg_events[0] {
5124 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5125 _ => panic!("Unexpected event"),
5127 match msg_events[1] {
5128 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5129 _ => panic!("Unexpected event"),
5131 match msg_events[2] {
5132 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, .. } } => {
5133 assert!(update_add_htlcs.is_empty());
5134 assert!(update_fail_htlcs.is_empty());
5135 assert_eq!(update_fulfill_htlcs.len(), 1);
5136 assert!(update_fail_malformed_htlcs.is_empty());
5137 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5139 _ => panic!("Unexpected event"),
5141 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5142 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5143 mine_transaction(&nodes[1], &commitment_tx[0]);
5144 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5145 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5146 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5147 assert_eq!(b_txn.len(), 3);
5148 check_spends!(b_txn[1], chan_1.3);
5149 check_spends!(b_txn[2], b_txn[1]);
5150 check_spends!(b_txn[0], commitment_tx[0]);
5151 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5152 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5153 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5155 check_closed_broadcast!(nodes[1], true);
5156 check_added_monitors!(nodes[1], 1);
5160 fn test_duplicate_payment_hash_one_failure_one_success() {
5161 // Topology : A --> B --> C --> D
5162 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5163 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5164 // we forward one of the payments onwards to D.
5165 let chanmon_cfgs = create_chanmon_cfgs(4);
5166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5167 // When this test was written, the default base fee floated based on the HTLC count.
5168 // It is now fixed, so we simply set the fee to the expected value here.
5169 let mut config = test_default_channel_config();
5170 config.channel_options.forwarding_fee_base_msat = 196;
5171 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5172 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5173 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5175 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5176 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5177 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5179 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5180 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5181 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5182 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5183 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5185 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5187 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5188 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5189 // script push size limit so that the below script length checks match
5190 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5191 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id())
5192 .with_features(InvoiceFeatures::known());
5193 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 900000, TEST_FINAL_CLTV - 40);
5194 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5196 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5197 assert_eq!(commitment_txn[0].input.len(), 1);
5198 check_spends!(commitment_txn[0], chan_2.3);
5200 mine_transaction(&nodes[1], &commitment_txn[0]);
5201 check_closed_broadcast!(nodes[1], true);
5202 check_added_monitors!(nodes[1], 1);
5203 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5204 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5206 let htlc_timeout_tx;
5207 { // Extract one of the two HTLC-Timeout transaction
5208 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5209 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5210 assert_eq!(node_txn.len(), 4);
5211 check_spends!(node_txn[0], chan_2.3);
5213 check_spends!(node_txn[1], commitment_txn[0]);
5214 assert_eq!(node_txn[1].input.len(), 1);
5215 check_spends!(node_txn[2], commitment_txn[0]);
5216 assert_eq!(node_txn[2].input.len(), 1);
5217 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5218 check_spends!(node_txn[3], commitment_txn[0]);
5219 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5221 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5222 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5223 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5224 htlc_timeout_tx = node_txn[1].clone();
5227 nodes[2].node.claim_funds(our_payment_preimage);
5228 mine_transaction(&nodes[2], &commitment_txn[0]);
5229 check_added_monitors!(nodes[2], 2);
5230 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5231 let events = nodes[2].node.get_and_clear_pending_msg_events();
5233 MessageSendEvent::UpdateHTLCs { .. } => {},
5234 _ => panic!("Unexpected event"),
5237 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5238 _ => panic!("Unexepected event"),
5240 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5241 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)
5242 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5243 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5244 assert_eq!(htlc_success_txn[0].input.len(), 1);
5245 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5246 assert_eq!(htlc_success_txn[1].input.len(), 1);
5247 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5248 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5249 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5250 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5251 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5252 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5254 mine_transaction(&nodes[1], &htlc_timeout_tx);
5255 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5256 expect_pending_htlcs_forwardable!(nodes[1]);
5257 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5258 assert!(htlc_updates.update_add_htlcs.is_empty());
5259 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5260 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5261 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5262 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5263 check_added_monitors!(nodes[1], 1);
5265 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5266 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5268 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5270 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5272 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5273 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5274 // and nodes[2] fee) is rounded down and then claimed in full.
5275 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5276 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5277 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5278 assert!(updates.update_add_htlcs.is_empty());
5279 assert!(updates.update_fail_htlcs.is_empty());
5280 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5281 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5282 assert!(updates.update_fail_malformed_htlcs.is_empty());
5283 check_added_monitors!(nodes[1], 1);
5285 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5286 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5288 let events = nodes[0].node.get_and_clear_pending_events();
5290 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5291 assert_eq!(*payment_preimage, our_payment_preimage);
5292 assert_eq!(*payment_hash, duplicate_payment_hash);
5294 _ => panic!("Unexpected event"),
5299 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5300 let chanmon_cfgs = create_chanmon_cfgs(2);
5301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5303 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5305 // Create some initial channels
5306 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5308 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5309 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5310 assert_eq!(local_txn.len(), 1);
5311 assert_eq!(local_txn[0].input.len(), 1);
5312 check_spends!(local_txn[0], chan_1.3);
5314 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5315 nodes[1].node.claim_funds(payment_preimage);
5316 check_added_monitors!(nodes[1], 1);
5317 mine_transaction(&nodes[1], &local_txn[0]);
5318 check_added_monitors!(nodes[1], 1);
5319 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5320 let events = nodes[1].node.get_and_clear_pending_msg_events();
5322 MessageSendEvent::UpdateHTLCs { .. } => {},
5323 _ => panic!("Unexpected event"),
5326 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5327 _ => panic!("Unexepected event"),
5330 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5331 assert_eq!(node_txn.len(), 3);
5332 assert_eq!(node_txn[0], node_txn[2]);
5333 assert_eq!(node_txn[1], local_txn[0]);
5334 assert_eq!(node_txn[0].input.len(), 1);
5335 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5336 check_spends!(node_txn[0], local_txn[0]);
5340 mine_transaction(&nodes[1], &node_tx);
5341 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5343 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5344 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5345 assert_eq!(spend_txn.len(), 1);
5346 assert_eq!(spend_txn[0].input.len(), 1);
5347 check_spends!(spend_txn[0], node_tx);
5348 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5351 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5352 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5353 // unrevoked commitment transaction.
5354 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5355 // a remote RAA before they could be failed backwards (and combinations thereof).
5356 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5357 // use the same payment hashes.
5358 // Thus, we use a six-node network:
5363 // And test where C fails back to A/B when D announces its latest commitment transaction
5364 let chanmon_cfgs = create_chanmon_cfgs(6);
5365 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5366 // When this test was written, the default base fee floated based on the HTLC count.
5367 // It is now fixed, so we simply set the fee to the expected value here.
5368 let mut config = test_default_channel_config();
5369 config.channel_options.forwarding_fee_base_msat = 196;
5370 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5371 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5372 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5374 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5375 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5376 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5377 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5378 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5380 // Rebalance and check output sanity...
5381 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5382 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5383 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5385 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5387 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
5389 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
5390 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5392 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
5394 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
5396 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5398 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5399 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5401 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());
5403 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());
5406 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5408 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5409 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
5412 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
5414 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5415 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());
5417 // Double-check that six of the new HTLC were added
5418 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5419 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5420 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5421 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5423 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5424 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5425 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5426 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5427 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5428 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5429 check_added_monitors!(nodes[4], 0);
5430 expect_pending_htlcs_forwardable!(nodes[4]);
5431 check_added_monitors!(nodes[4], 1);
5433 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5434 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5435 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5436 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5437 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5438 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5440 // Fail 3rd below-dust and 7th above-dust HTLCs
5441 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5442 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5443 check_added_monitors!(nodes[5], 0);
5444 expect_pending_htlcs_forwardable!(nodes[5]);
5445 check_added_monitors!(nodes[5], 1);
5447 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5448 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5449 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5450 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5452 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5454 expect_pending_htlcs_forwardable!(nodes[3]);
5455 check_added_monitors!(nodes[3], 1);
5456 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5457 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5458 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5459 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5460 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5461 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5462 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5463 if deliver_last_raa {
5464 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5466 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5469 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5470 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5471 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5472 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5474 // We now broadcast the latest commitment transaction, which *should* result in failures for
5475 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5476 // the non-broadcast above-dust HTLCs.
5478 // Alternatively, we may broadcast the previous commitment transaction, which should only
5479 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5480 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5482 if announce_latest {
5483 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5485 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5487 let events = nodes[2].node.get_and_clear_pending_events();
5488 let close_event = if deliver_last_raa {
5489 assert_eq!(events.len(), 2);
5492 assert_eq!(events.len(), 1);
5496 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5497 _ => panic!("Unexpected event"),
5500 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5501 check_closed_broadcast!(nodes[2], true);
5502 if deliver_last_raa {
5503 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5505 expect_pending_htlcs_forwardable!(nodes[2]);
5507 check_added_monitors!(nodes[2], 3);
5509 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5510 assert_eq!(cs_msgs.len(), 2);
5511 let mut a_done = false;
5512 for msg in cs_msgs {
5514 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5515 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5516 // should be failed-backwards here.
5517 let target = if *node_id == nodes[0].node.get_our_node_id() {
5518 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5519 for htlc in &updates.update_fail_htlcs {
5520 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 });
5522 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5527 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5528 for htlc in &updates.update_fail_htlcs {
5529 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5531 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5532 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5535 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5536 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5537 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5538 if announce_latest {
5539 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5540 if *node_id == nodes[0].node.get_our_node_id() {
5541 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5544 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5546 _ => panic!("Unexpected event"),
5550 let as_events = nodes[0].node.get_and_clear_pending_events();
5551 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5552 let mut as_failds = HashSet::new();
5553 let mut as_updates = 0;
5554 for event in as_events.iter() {
5555 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5556 assert!(as_failds.insert(*payment_hash));
5557 if *payment_hash != payment_hash_2 {
5558 assert_eq!(*rejected_by_dest, deliver_last_raa);
5560 assert!(!rejected_by_dest);
5562 if network_update.is_some() {
5565 } else { panic!("Unexpected event"); }
5567 assert!(as_failds.contains(&payment_hash_1));
5568 assert!(as_failds.contains(&payment_hash_2));
5569 if announce_latest {
5570 assert!(as_failds.contains(&payment_hash_3));
5571 assert!(as_failds.contains(&payment_hash_5));
5573 assert!(as_failds.contains(&payment_hash_6));
5575 let bs_events = nodes[1].node.get_and_clear_pending_events();
5576 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5577 let mut bs_failds = HashSet::new();
5578 let mut bs_updates = 0;
5579 for event in bs_events.iter() {
5580 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5581 assert!(bs_failds.insert(*payment_hash));
5582 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5583 assert_eq!(*rejected_by_dest, deliver_last_raa);
5585 assert!(!rejected_by_dest);
5587 if network_update.is_some() {
5590 } else { panic!("Unexpected event"); }
5592 assert!(bs_failds.contains(&payment_hash_1));
5593 assert!(bs_failds.contains(&payment_hash_2));
5594 if announce_latest {
5595 assert!(bs_failds.contains(&payment_hash_4));
5597 assert!(bs_failds.contains(&payment_hash_5));
5599 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5600 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5601 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5602 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5603 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5604 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5608 fn test_fail_backwards_latest_remote_announce_a() {
5609 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5613 fn test_fail_backwards_latest_remote_announce_b() {
5614 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5618 fn test_fail_backwards_previous_remote_announce() {
5619 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5620 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5621 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5625 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5626 let chanmon_cfgs = create_chanmon_cfgs(2);
5627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5629 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5631 // Create some initial channels
5632 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5634 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5635 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5636 assert_eq!(local_txn[0].input.len(), 1);
5637 check_spends!(local_txn[0], chan_1.3);
5639 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5640 mine_transaction(&nodes[0], &local_txn[0]);
5641 check_closed_broadcast!(nodes[0], true);
5642 check_added_monitors!(nodes[0], 1);
5643 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5644 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5646 let htlc_timeout = {
5647 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5648 assert_eq!(node_txn.len(), 2);
5649 check_spends!(node_txn[0], chan_1.3);
5650 assert_eq!(node_txn[1].input.len(), 1);
5651 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5652 check_spends!(node_txn[1], local_txn[0]);
5656 mine_transaction(&nodes[0], &htlc_timeout);
5657 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5658 expect_payment_failed!(nodes[0], our_payment_hash, true);
5660 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5661 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5662 assert_eq!(spend_txn.len(), 3);
5663 check_spends!(spend_txn[0], local_txn[0]);
5664 assert_eq!(spend_txn[1].input.len(), 1);
5665 check_spends!(spend_txn[1], htlc_timeout);
5666 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5667 assert_eq!(spend_txn[2].input.len(), 2);
5668 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5669 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5670 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5674 fn test_key_derivation_params() {
5675 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5676 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5677 // let us re-derive the channel key set to then derive a delayed_payment_key.
5679 let chanmon_cfgs = create_chanmon_cfgs(3);
5681 // We manually create the node configuration to backup the seed.
5682 let seed = [42; 32];
5683 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5684 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);
5685 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, network_graph: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5686 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5687 node_cfgs.remove(0);
5688 node_cfgs.insert(0, node);
5690 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5691 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5693 // Create some initial channels
5694 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5696 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5697 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5698 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5700 // Ensure all nodes are at the same height
5701 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5702 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5703 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5704 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5706 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5707 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5708 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5709 assert_eq!(local_txn_1[0].input.len(), 1);
5710 check_spends!(local_txn_1[0], chan_1.3);
5712 // We check funding pubkey are unique
5713 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5714 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5715 if from_0_funding_key_0 == from_1_funding_key_0
5716 || from_0_funding_key_0 == from_1_funding_key_1
5717 || from_0_funding_key_1 == from_1_funding_key_0
5718 || from_0_funding_key_1 == from_1_funding_key_1 {
5719 panic!("Funding pubkeys aren't unique");
5722 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5723 mine_transaction(&nodes[0], &local_txn_1[0]);
5724 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5725 check_closed_broadcast!(nodes[0], true);
5726 check_added_monitors!(nodes[0], 1);
5727 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5729 let htlc_timeout = {
5730 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5731 assert_eq!(node_txn[1].input.len(), 1);
5732 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5733 check_spends!(node_txn[1], local_txn_1[0]);
5737 mine_transaction(&nodes[0], &htlc_timeout);
5738 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5739 expect_payment_failed!(nodes[0], our_payment_hash, true);
5741 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5742 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5743 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5744 assert_eq!(spend_txn.len(), 3);
5745 check_spends!(spend_txn[0], local_txn_1[0]);
5746 assert_eq!(spend_txn[1].input.len(), 1);
5747 check_spends!(spend_txn[1], htlc_timeout);
5748 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5749 assert_eq!(spend_txn[2].input.len(), 2);
5750 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5751 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5752 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5756 fn test_static_output_closing_tx() {
5757 let chanmon_cfgs = create_chanmon_cfgs(2);
5758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5760 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5762 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5764 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5765 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5767 mine_transaction(&nodes[0], &closing_tx);
5768 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5769 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5771 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5772 assert_eq!(spend_txn.len(), 1);
5773 check_spends!(spend_txn[0], closing_tx);
5775 mine_transaction(&nodes[1], &closing_tx);
5776 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5777 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5779 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5780 assert_eq!(spend_txn.len(), 1);
5781 check_spends!(spend_txn[0], closing_tx);
5784 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5785 let chanmon_cfgs = create_chanmon_cfgs(2);
5786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5789 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5791 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5793 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5794 // present in B's local commitment transaction, but none of A's commitment transactions.
5795 assert!(nodes[1].node.claim_funds(payment_preimage));
5796 check_added_monitors!(nodes[1], 1);
5798 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5799 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5800 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5802 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5803 check_added_monitors!(nodes[0], 1);
5804 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5805 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5806 check_added_monitors!(nodes[1], 1);
5808 let starting_block = nodes[1].best_block_info();
5809 let mut block = Block {
5810 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5813 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5814 connect_block(&nodes[1], &block);
5815 block.header.prev_blockhash = block.block_hash();
5817 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5818 check_closed_broadcast!(nodes[1], true);
5819 check_added_monitors!(nodes[1], 1);
5820 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5823 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5824 let chanmon_cfgs = create_chanmon_cfgs(2);
5825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5827 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5828 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5830 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5831 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5832 check_added_monitors!(nodes[0], 1);
5834 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5836 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5837 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5838 // to "time out" the HTLC.
5840 let starting_block = nodes[1].best_block_info();
5841 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5843 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5844 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5845 header.prev_blockhash = header.block_hash();
5847 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5848 check_closed_broadcast!(nodes[0], true);
5849 check_added_monitors!(nodes[0], 1);
5850 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5853 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5854 let chanmon_cfgs = create_chanmon_cfgs(3);
5855 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5856 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5857 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5858 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5860 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5861 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5862 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5863 // actually revoked.
5864 let htlc_value = if use_dust { 50000 } else { 3000000 };
5865 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5866 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5867 expect_pending_htlcs_forwardable!(nodes[1]);
5868 check_added_monitors!(nodes[1], 1);
5870 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5871 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5872 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5873 check_added_monitors!(nodes[0], 1);
5874 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5875 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5876 check_added_monitors!(nodes[1], 1);
5877 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5878 check_added_monitors!(nodes[1], 1);
5879 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5881 if check_revoke_no_close {
5882 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5883 check_added_monitors!(nodes[0], 1);
5886 let starting_block = nodes[1].best_block_info();
5887 let mut block = Block {
5888 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5891 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5892 connect_block(&nodes[0], &block);
5893 block.header.prev_blockhash = block.block_hash();
5895 if !check_revoke_no_close {
5896 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5897 check_closed_broadcast!(nodes[0], true);
5898 check_added_monitors!(nodes[0], 1);
5899 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5901 let events = nodes[0].node.get_and_clear_pending_events();
5902 assert_eq!(events.len(), 2);
5903 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5904 assert_eq!(*payment_hash, our_payment_hash);
5905 } else { panic!("Unexpected event"); }
5906 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5907 assert_eq!(*payment_hash, our_payment_hash);
5908 } else { panic!("Unexpected event"); }
5912 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5913 // There are only a few cases to test here:
5914 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5915 // broadcastable commitment transactions result in channel closure,
5916 // * its included in an unrevoked-but-previous remote commitment transaction,
5917 // * its included in the latest remote or local commitment transactions.
5918 // We test each of the three possible commitment transactions individually and use both dust and
5920 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5921 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5922 // tested for at least one of the cases in other tests.
5924 fn htlc_claim_single_commitment_only_a() {
5925 do_htlc_claim_local_commitment_only(true);
5926 do_htlc_claim_local_commitment_only(false);
5928 do_htlc_claim_current_remote_commitment_only(true);
5929 do_htlc_claim_current_remote_commitment_only(false);
5933 fn htlc_claim_single_commitment_only_b() {
5934 do_htlc_claim_previous_remote_commitment_only(true, false);
5935 do_htlc_claim_previous_remote_commitment_only(false, false);
5936 do_htlc_claim_previous_remote_commitment_only(true, true);
5937 do_htlc_claim_previous_remote_commitment_only(false, true);
5942 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5943 let chanmon_cfgs = create_chanmon_cfgs(2);
5944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5946 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5947 // Force duplicate randomness for every get-random call
5948 for node in nodes.iter() {
5949 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5952 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5953 let channel_value_satoshis=10000;
5954 let push_msat=10001;
5955 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5956 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5957 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5958 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5960 // Create a second channel with the same random values. This used to panic due to a colliding
5961 // channel_id, but now panics due to a colliding outbound SCID alias.
5962 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5966 fn bolt2_open_channel_sending_node_checks_part2() {
5967 let chanmon_cfgs = create_chanmon_cfgs(2);
5968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5970 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5972 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5973 let channel_value_satoshis=2^24;
5974 let push_msat=10001;
5975 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5977 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5978 let channel_value_satoshis=10000;
5979 // Test when push_msat is equal to 1000 * funding_satoshis.
5980 let push_msat=1000*channel_value_satoshis+1;
5981 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5983 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5984 let channel_value_satoshis=10000;
5985 let push_msat=10001;
5986 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
5987 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5988 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5990 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5991 // 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
5992 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5994 // 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.
5995 assert!(BREAKDOWN_TIMEOUT>0);
5996 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5998 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5999 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6000 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6002 // 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.
6003 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6004 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6005 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6006 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6007 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6011 fn bolt2_open_channel_sane_dust_limit() {
6012 let chanmon_cfgs = create_chanmon_cfgs(2);
6013 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6014 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6015 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6017 let channel_value_satoshis=1000000;
6018 let push_msat=10001;
6019 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6020 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6021 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6022 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6024 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6025 let events = nodes[1].node.get_and_clear_pending_msg_events();
6026 let err_msg = match events[0] {
6027 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6030 _ => panic!("Unexpected event"),
6032 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6035 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6036 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6037 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6038 // is no longer affordable once it's freed.
6040 fn test_fail_holding_cell_htlc_upon_free() {
6041 let chanmon_cfgs = create_chanmon_cfgs(2);
6042 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6043 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6044 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6045 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6047 // First nodes[0] generates an update_fee, setting the channel's
6048 // pending_update_fee.
6050 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6051 *feerate_lock += 20;
6053 nodes[0].node.timer_tick_occurred();
6054 check_added_monitors!(nodes[0], 1);
6056 let events = nodes[0].node.get_and_clear_pending_msg_events();
6057 assert_eq!(events.len(), 1);
6058 let (update_msg, commitment_signed) = match events[0] {
6059 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6060 (update_fee.as_ref(), commitment_signed)
6062 _ => panic!("Unexpected event"),
6065 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6067 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6068 let channel_reserve = chan_stat.channel_reserve_msat;
6069 let feerate = get_feerate!(nodes[0], chan.2);
6070 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6072 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6073 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6074 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6076 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6077 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6078 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6079 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6081 // Flush the pending fee update.
6082 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6083 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6084 check_added_monitors!(nodes[1], 1);
6085 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6086 check_added_monitors!(nodes[0], 1);
6088 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6089 // HTLC, but now that the fee has been raised the payment will now fail, causing
6090 // us to surface its failure to the user.
6091 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6092 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6093 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);
6094 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 {}",
6095 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6096 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6098 // Check that the payment failed to be sent out.
6099 let events = nodes[0].node.get_and_clear_pending_events();
6100 assert_eq!(events.len(), 1);
6102 &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, .. } => {
6103 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6104 assert_eq!(our_payment_hash.clone(), *payment_hash);
6105 assert_eq!(*rejected_by_dest, false);
6106 assert_eq!(*all_paths_failed, true);
6107 assert_eq!(*network_update, None);
6108 assert_eq!(*short_channel_id, None);
6109 assert_eq!(*error_code, None);
6110 assert_eq!(*error_data, None);
6112 _ => panic!("Unexpected event"),
6116 // Test that if multiple HTLCs are released from the holding cell and one is
6117 // valid but the other is no longer valid upon release, the valid HTLC can be
6118 // successfully completed while the other one fails as expected.
6120 fn test_free_and_fail_holding_cell_htlcs() {
6121 let chanmon_cfgs = create_chanmon_cfgs(2);
6122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6124 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6125 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6127 // First nodes[0] generates an update_fee, setting the channel's
6128 // pending_update_fee.
6130 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6131 *feerate_lock += 200;
6133 nodes[0].node.timer_tick_occurred();
6134 check_added_monitors!(nodes[0], 1);
6136 let events = nodes[0].node.get_and_clear_pending_msg_events();
6137 assert_eq!(events.len(), 1);
6138 let (update_msg, commitment_signed) = match events[0] {
6139 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6140 (update_fee.as_ref(), commitment_signed)
6142 _ => panic!("Unexpected event"),
6145 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6147 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6148 let channel_reserve = chan_stat.channel_reserve_msat;
6149 let feerate = get_feerate!(nodes[0], chan.2);
6150 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6152 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6154 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6155 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6156 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6158 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6159 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6160 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6161 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6162 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6163 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6164 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6166 // Flush the pending fee update.
6167 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6168 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6169 check_added_monitors!(nodes[1], 1);
6170 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6171 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6172 check_added_monitors!(nodes[0], 2);
6174 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6175 // but now that the fee has been raised the second payment will now fail, causing us
6176 // to surface its failure to the user. The first payment should succeed.
6177 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6178 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6179 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);
6180 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 {}",
6181 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6182 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6184 // Check that the second payment failed to be sent out.
6185 let events = nodes[0].node.get_and_clear_pending_events();
6186 assert_eq!(events.len(), 1);
6188 &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, .. } => {
6189 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6190 assert_eq!(payment_hash_2.clone(), *payment_hash);
6191 assert_eq!(*rejected_by_dest, false);
6192 assert_eq!(*all_paths_failed, true);
6193 assert_eq!(*network_update, None);
6194 assert_eq!(*short_channel_id, None);
6195 assert_eq!(*error_code, None);
6196 assert_eq!(*error_data, None);
6198 _ => panic!("Unexpected event"),
6201 // Complete the first payment and the RAA from the fee update.
6202 let (payment_event, send_raa_event) = {
6203 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6204 assert_eq!(msgs.len(), 2);
6205 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6207 let raa = match send_raa_event {
6208 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6209 _ => panic!("Unexpected event"),
6211 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6212 check_added_monitors!(nodes[1], 1);
6213 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6214 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6215 let events = nodes[1].node.get_and_clear_pending_events();
6216 assert_eq!(events.len(), 1);
6218 Event::PendingHTLCsForwardable { .. } => {},
6219 _ => panic!("Unexpected event"),
6221 nodes[1].node.process_pending_htlc_forwards();
6222 let events = nodes[1].node.get_and_clear_pending_events();
6223 assert_eq!(events.len(), 1);
6225 Event::PaymentReceived { .. } => {},
6226 _ => panic!("Unexpected event"),
6228 nodes[1].node.claim_funds(payment_preimage_1);
6229 check_added_monitors!(nodes[1], 1);
6230 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6231 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6232 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6233 expect_payment_sent!(nodes[0], payment_preimage_1);
6236 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6237 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6238 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6241 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6242 let chanmon_cfgs = create_chanmon_cfgs(3);
6243 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6244 // When this test was written, the default base fee floated based on the HTLC count.
6245 // It is now fixed, so we simply set the fee to the expected value here.
6246 let mut config = test_default_channel_config();
6247 config.channel_options.forwarding_fee_base_msat = 196;
6248 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6249 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6250 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6251 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6253 // First nodes[1] generates an update_fee, setting the channel's
6254 // pending_update_fee.
6256 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6257 *feerate_lock += 20;
6259 nodes[1].node.timer_tick_occurred();
6260 check_added_monitors!(nodes[1], 1);
6262 let events = nodes[1].node.get_and_clear_pending_msg_events();
6263 assert_eq!(events.len(), 1);
6264 let (update_msg, commitment_signed) = match events[0] {
6265 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6266 (update_fee.as_ref(), commitment_signed)
6268 _ => panic!("Unexpected event"),
6271 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6273 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6274 let channel_reserve = chan_stat.channel_reserve_msat;
6275 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6276 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6278 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6280 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6281 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6282 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6283 let payment_event = {
6284 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6285 check_added_monitors!(nodes[0], 1);
6287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6288 assert_eq!(events.len(), 1);
6290 SendEvent::from_event(events.remove(0))
6292 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6293 check_added_monitors!(nodes[1], 0);
6294 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6295 expect_pending_htlcs_forwardable!(nodes[1]);
6297 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6298 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6300 // Flush the pending fee update.
6301 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6302 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6303 check_added_monitors!(nodes[2], 1);
6304 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6305 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6306 check_added_monitors!(nodes[1], 2);
6308 // A final RAA message is generated to finalize the fee update.
6309 let events = nodes[1].node.get_and_clear_pending_msg_events();
6310 assert_eq!(events.len(), 1);
6312 let raa_msg = match &events[0] {
6313 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6316 _ => panic!("Unexpected event"),
6319 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6320 check_added_monitors!(nodes[2], 1);
6321 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6323 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6324 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6325 assert_eq!(process_htlc_forwards_event.len(), 1);
6326 match &process_htlc_forwards_event[0] {
6327 &Event::PendingHTLCsForwardable { .. } => {},
6328 _ => panic!("Unexpected event"),
6331 // In response, we call ChannelManager's process_pending_htlc_forwards
6332 nodes[1].node.process_pending_htlc_forwards();
6333 check_added_monitors!(nodes[1], 1);
6335 // This causes the HTLC to be failed backwards.
6336 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6337 assert_eq!(fail_event.len(), 1);
6338 let (fail_msg, commitment_signed) = match &fail_event[0] {
6339 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6340 assert_eq!(updates.update_add_htlcs.len(), 0);
6341 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6342 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6343 assert_eq!(updates.update_fail_htlcs.len(), 1);
6344 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6346 _ => panic!("Unexpected event"),
6349 // Pass the failure messages back to nodes[0].
6350 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6351 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6353 // Complete the HTLC failure+removal process.
6354 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6355 check_added_monitors!(nodes[0], 1);
6356 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6357 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6358 check_added_monitors!(nodes[1], 2);
6359 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6360 assert_eq!(final_raa_event.len(), 1);
6361 let raa = match &final_raa_event[0] {
6362 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6363 _ => panic!("Unexpected event"),
6365 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6366 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6367 check_added_monitors!(nodes[0], 1);
6370 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6371 // 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.
6372 //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.
6375 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6376 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6377 let chanmon_cfgs = create_chanmon_cfgs(2);
6378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6380 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6381 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6383 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6384 route.paths[0][0].fee_msat = 100;
6386 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6387 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6388 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6389 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6393 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6394 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6395 let chanmon_cfgs = create_chanmon_cfgs(2);
6396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6398 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6399 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6401 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6402 route.paths[0][0].fee_msat = 0;
6403 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6404 assert_eq!(err, "Cannot send 0-msat HTLC"));
6406 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6407 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6411 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6412 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6413 let chanmon_cfgs = create_chanmon_cfgs(2);
6414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6416 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6417 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6419 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6420 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6421 check_added_monitors!(nodes[0], 1);
6422 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6423 updates.update_add_htlcs[0].amount_msat = 0;
6425 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6426 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6427 check_closed_broadcast!(nodes[1], true).unwrap();
6428 check_added_monitors!(nodes[1], 1);
6429 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6433 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6434 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6435 //It is enforced when constructing a route.
6436 let chanmon_cfgs = create_chanmon_cfgs(2);
6437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6439 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6440 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6442 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
6443 .with_features(InvoiceFeatures::known());
6444 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6445 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6446 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6447 assert_eq!(err, &"Channel CLTV overflowed?"));
6451 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6452 //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.
6453 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6454 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6455 let chanmon_cfgs = create_chanmon_cfgs(2);
6456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6458 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6459 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6460 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6462 for i in 0..max_accepted_htlcs {
6463 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6464 let payment_event = {
6465 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6466 check_added_monitors!(nodes[0], 1);
6468 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6469 assert_eq!(events.len(), 1);
6470 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6471 assert_eq!(htlcs[0].htlc_id, i);
6475 SendEvent::from_event(events.remove(0))
6477 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6478 check_added_monitors!(nodes[1], 0);
6479 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6481 expect_pending_htlcs_forwardable!(nodes[1]);
6482 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6484 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6485 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6486 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6488 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6489 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6493 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6494 //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.
6495 let chanmon_cfgs = create_chanmon_cfgs(2);
6496 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6497 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6498 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6499 let channel_value = 100000;
6500 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6501 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6503 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6505 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6506 // Manually create a route over our max in flight (which our router normally automatically
6508 route.paths[0][0].fee_msat = max_in_flight + 1;
6509 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6510 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)));
6512 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6513 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);
6515 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6518 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6520 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6521 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6522 let chanmon_cfgs = create_chanmon_cfgs(2);
6523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6525 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6526 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6527 let htlc_minimum_msat: u64;
6529 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6530 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6531 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6534 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6535 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6536 check_added_monitors!(nodes[0], 1);
6537 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6538 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6539 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6540 assert!(nodes[1].node.list_channels().is_empty());
6541 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6542 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()));
6543 check_added_monitors!(nodes[1], 1);
6544 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6548 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6549 //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
6550 let chanmon_cfgs = create_chanmon_cfgs(2);
6551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6553 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6554 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6556 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6557 let channel_reserve = chan_stat.channel_reserve_msat;
6558 let feerate = get_feerate!(nodes[0], chan.2);
6559 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6560 // The 2* and +1 are for the fee spike reserve.
6561 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6563 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6564 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6565 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6566 check_added_monitors!(nodes[0], 1);
6567 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6569 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6570 // at this time channel-initiatee receivers are not required to enforce that senders
6571 // respect the fee_spike_reserve.
6572 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6573 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6575 assert!(nodes[1].node.list_channels().is_empty());
6576 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6577 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6578 check_added_monitors!(nodes[1], 1);
6579 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6583 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6584 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6585 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6586 let chanmon_cfgs = create_chanmon_cfgs(2);
6587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6589 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6590 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6592 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6593 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6594 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6595 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6596 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6597 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6599 let mut msg = msgs::UpdateAddHTLC {
6603 payment_hash: our_payment_hash,
6604 cltv_expiry: htlc_cltv,
6605 onion_routing_packet: onion_packet.clone(),
6608 for i in 0..super::channel::OUR_MAX_HTLCS {
6609 msg.htlc_id = i as u64;
6610 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6612 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6613 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6615 assert!(nodes[1].node.list_channels().is_empty());
6616 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6617 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6618 check_added_monitors!(nodes[1], 1);
6619 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6623 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6624 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6625 let chanmon_cfgs = create_chanmon_cfgs(2);
6626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6629 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6631 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6632 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6633 check_added_monitors!(nodes[0], 1);
6634 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6635 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6636 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6638 assert!(nodes[1].node.list_channels().is_empty());
6639 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6640 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6641 check_added_monitors!(nodes[1], 1);
6642 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6646 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6647 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6648 let chanmon_cfgs = create_chanmon_cfgs(2);
6649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6651 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6654 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6655 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6656 check_added_monitors!(nodes[0], 1);
6657 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6658 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6659 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6661 assert!(nodes[1].node.list_channels().is_empty());
6662 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6663 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6664 check_added_monitors!(nodes[1], 1);
6665 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6669 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6670 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6671 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6672 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6673 let chanmon_cfgs = create_chanmon_cfgs(2);
6674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6678 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6679 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6680 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6681 check_added_monitors!(nodes[0], 1);
6682 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6683 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6685 //Disconnect and Reconnect
6686 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6687 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6688 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6689 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6690 assert_eq!(reestablish_1.len(), 1);
6691 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6692 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6693 assert_eq!(reestablish_2.len(), 1);
6694 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6695 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6696 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6697 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6700 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6701 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6702 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6703 check_added_monitors!(nodes[1], 1);
6704 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6706 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6708 assert!(nodes[1].node.list_channels().is_empty());
6709 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6710 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6711 check_added_monitors!(nodes[1], 1);
6712 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6716 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6717 //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.
6719 let chanmon_cfgs = create_chanmon_cfgs(2);
6720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6722 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6723 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6724 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6725 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6727 check_added_monitors!(nodes[0], 1);
6728 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6729 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6731 let update_msg = msgs::UpdateFulfillHTLC{
6734 payment_preimage: our_payment_preimage,
6737 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6739 assert!(nodes[0].node.list_channels().is_empty());
6740 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6741 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()));
6742 check_added_monitors!(nodes[0], 1);
6743 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6747 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6748 //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.
6750 let chanmon_cfgs = create_chanmon_cfgs(2);
6751 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6752 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6753 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6754 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6756 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6757 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6758 check_added_monitors!(nodes[0], 1);
6759 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6760 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6762 let update_msg = msgs::UpdateFailHTLC{
6765 reason: msgs::OnionErrorPacket { data: Vec::new()},
6768 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6770 assert!(nodes[0].node.list_channels().is_empty());
6771 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6772 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()));
6773 check_added_monitors!(nodes[0], 1);
6774 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6778 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6779 //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.
6781 let chanmon_cfgs = create_chanmon_cfgs(2);
6782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6784 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6785 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6787 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6788 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6789 check_added_monitors!(nodes[0], 1);
6790 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6791 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6792 let update_msg = msgs::UpdateFailMalformedHTLC{
6795 sha256_of_onion: [1; 32],
6796 failure_code: 0x8000,
6799 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6801 assert!(nodes[0].node.list_channels().is_empty());
6802 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6803 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()));
6804 check_added_monitors!(nodes[0], 1);
6805 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6809 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6810 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6812 let chanmon_cfgs = create_chanmon_cfgs(2);
6813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6815 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6816 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6818 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6820 nodes[1].node.claim_funds(our_payment_preimage);
6821 check_added_monitors!(nodes[1], 1);
6823 let events = nodes[1].node.get_and_clear_pending_msg_events();
6824 assert_eq!(events.len(), 1);
6825 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6827 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, .. } } => {
6828 assert!(update_add_htlcs.is_empty());
6829 assert_eq!(update_fulfill_htlcs.len(), 1);
6830 assert!(update_fail_htlcs.is_empty());
6831 assert!(update_fail_malformed_htlcs.is_empty());
6832 assert!(update_fee.is_none());
6833 update_fulfill_htlcs[0].clone()
6835 _ => panic!("Unexpected event"),
6839 update_fulfill_msg.htlc_id = 1;
6841 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6843 assert!(nodes[0].node.list_channels().is_empty());
6844 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6845 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6846 check_added_monitors!(nodes[0], 1);
6847 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6851 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6852 //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.
6854 let chanmon_cfgs = create_chanmon_cfgs(2);
6855 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6856 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6857 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6858 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6860 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6862 nodes[1].node.claim_funds(our_payment_preimage);
6863 check_added_monitors!(nodes[1], 1);
6865 let events = nodes[1].node.get_and_clear_pending_msg_events();
6866 assert_eq!(events.len(), 1);
6867 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6869 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, .. } } => {
6870 assert!(update_add_htlcs.is_empty());
6871 assert_eq!(update_fulfill_htlcs.len(), 1);
6872 assert!(update_fail_htlcs.is_empty());
6873 assert!(update_fail_malformed_htlcs.is_empty());
6874 assert!(update_fee.is_none());
6875 update_fulfill_htlcs[0].clone()
6877 _ => panic!("Unexpected event"),
6881 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6883 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6885 assert!(nodes[0].node.list_channels().is_empty());
6886 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6887 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6888 check_added_monitors!(nodes[0], 1);
6889 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6893 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6894 //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.
6896 let chanmon_cfgs = create_chanmon_cfgs(2);
6897 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6898 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6899 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6900 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6902 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6903 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6904 check_added_monitors!(nodes[0], 1);
6906 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6907 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6909 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6910 check_added_monitors!(nodes[1], 0);
6911 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6913 let events = nodes[1].node.get_and_clear_pending_msg_events();
6915 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6917 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, .. } } => {
6918 assert!(update_add_htlcs.is_empty());
6919 assert!(update_fulfill_htlcs.is_empty());
6920 assert!(update_fail_htlcs.is_empty());
6921 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6922 assert!(update_fee.is_none());
6923 update_fail_malformed_htlcs[0].clone()
6925 _ => panic!("Unexpected event"),
6928 update_msg.failure_code &= !0x8000;
6929 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6931 assert!(nodes[0].node.list_channels().is_empty());
6932 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6933 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6934 check_added_monitors!(nodes[0], 1);
6935 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6939 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6940 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6941 // * 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.
6943 let chanmon_cfgs = create_chanmon_cfgs(3);
6944 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6945 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6946 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6947 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6948 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6950 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6953 let mut payment_event = {
6954 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6955 check_added_monitors!(nodes[0], 1);
6956 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6957 assert_eq!(events.len(), 1);
6958 SendEvent::from_event(events.remove(0))
6960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6961 check_added_monitors!(nodes[1], 0);
6962 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6963 expect_pending_htlcs_forwardable!(nodes[1]);
6964 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6965 assert_eq!(events_2.len(), 1);
6966 check_added_monitors!(nodes[1], 1);
6967 payment_event = SendEvent::from_event(events_2.remove(0));
6968 assert_eq!(payment_event.msgs.len(), 1);
6971 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6972 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6973 check_added_monitors!(nodes[2], 0);
6974 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6976 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6977 assert_eq!(events_3.len(), 1);
6978 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6980 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 } } => {
6981 assert!(update_add_htlcs.is_empty());
6982 assert!(update_fulfill_htlcs.is_empty());
6983 assert!(update_fail_htlcs.is_empty());
6984 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6985 assert!(update_fee.is_none());
6986 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6988 _ => panic!("Unexpected event"),
6992 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6994 check_added_monitors!(nodes[1], 0);
6995 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6996 expect_pending_htlcs_forwardable!(nodes[1]);
6997 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6998 assert_eq!(events_4.len(), 1);
7000 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7002 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, .. } } => {
7003 assert!(update_add_htlcs.is_empty());
7004 assert!(update_fulfill_htlcs.is_empty());
7005 assert_eq!(update_fail_htlcs.len(), 1);
7006 assert!(update_fail_malformed_htlcs.is_empty());
7007 assert!(update_fee.is_none());
7009 _ => panic!("Unexpected event"),
7012 check_added_monitors!(nodes[1], 1);
7015 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7016 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7017 // 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
7018 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7020 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7021 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7022 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7023 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7024 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7025 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7027 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7029 // We route 2 dust-HTLCs between A and B
7030 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7031 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7032 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7034 // Cache one local commitment tx as previous
7035 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7037 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7038 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7039 check_added_monitors!(nodes[1], 0);
7040 expect_pending_htlcs_forwardable!(nodes[1]);
7041 check_added_monitors!(nodes[1], 1);
7043 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7044 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7045 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7046 check_added_monitors!(nodes[0], 1);
7048 // Cache one local commitment tx as lastest
7049 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7051 let events = nodes[0].node.get_and_clear_pending_msg_events();
7053 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7054 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7056 _ => panic!("Unexpected event"),
7059 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7060 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7062 _ => panic!("Unexpected event"),
7065 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7066 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7067 if announce_latest {
7068 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7070 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7073 check_closed_broadcast!(nodes[0], true);
7074 check_added_monitors!(nodes[0], 1);
7075 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7077 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7078 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7079 let events = nodes[0].node.get_and_clear_pending_events();
7080 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7081 assert_eq!(events.len(), 2);
7082 let mut first_failed = false;
7083 for event in events {
7085 Event::PaymentPathFailed { payment_hash, .. } => {
7086 if payment_hash == payment_hash_1 {
7087 assert!(!first_failed);
7088 first_failed = true;
7090 assert_eq!(payment_hash, payment_hash_2);
7093 _ => panic!("Unexpected event"),
7099 fn test_failure_delay_dust_htlc_local_commitment() {
7100 do_test_failure_delay_dust_htlc_local_commitment(true);
7101 do_test_failure_delay_dust_htlc_local_commitment(false);
7104 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7105 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7106 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7107 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7108 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7109 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7110 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7112 let chanmon_cfgs = create_chanmon_cfgs(3);
7113 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7114 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7115 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7116 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7118 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7120 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7121 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7123 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7124 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7126 // We revoked bs_commitment_tx
7128 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7129 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7132 let mut timeout_tx = Vec::new();
7134 // We fail dust-HTLC 1 by broadcast of local commitment tx
7135 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7136 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7137 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7138 expect_payment_failed!(nodes[0], dust_hash, true);
7140 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7141 check_closed_broadcast!(nodes[0], true);
7142 check_added_monitors!(nodes[0], 1);
7143 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7144 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7145 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7146 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7147 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7148 mine_transaction(&nodes[0], &timeout_tx[0]);
7149 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7150 expect_payment_failed!(nodes[0], non_dust_hash, true);
7152 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7153 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7154 check_closed_broadcast!(nodes[0], true);
7155 check_added_monitors!(nodes[0], 1);
7156 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7157 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7158 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7159 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7161 expect_payment_failed!(nodes[0], dust_hash, true);
7162 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7163 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7164 mine_transaction(&nodes[0], &timeout_tx[0]);
7165 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7166 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7167 expect_payment_failed!(nodes[0], non_dust_hash, true);
7169 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7171 let events = nodes[0].node.get_and_clear_pending_events();
7172 assert_eq!(events.len(), 2);
7175 Event::PaymentPathFailed { payment_hash, .. } => {
7176 if payment_hash == dust_hash { first = true; }
7177 else { first = false; }
7179 _ => panic!("Unexpected event"),
7182 Event::PaymentPathFailed { payment_hash, .. } => {
7183 if first { assert_eq!(payment_hash, non_dust_hash); }
7184 else { assert_eq!(payment_hash, dust_hash); }
7186 _ => panic!("Unexpected event"),
7193 fn test_sweep_outbound_htlc_failure_update() {
7194 do_test_sweep_outbound_htlc_failure_update(false, true);
7195 do_test_sweep_outbound_htlc_failure_update(false, false);
7196 do_test_sweep_outbound_htlc_failure_update(true, false);
7200 fn test_user_configurable_csv_delay() {
7201 // We test our channel constructors yield errors when we pass them absurd csv delay
7203 let mut low_our_to_self_config = UserConfig::default();
7204 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7205 let mut high_their_to_self_config = UserConfig::default();
7206 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7207 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7208 let chanmon_cfgs = create_chanmon_cfgs(2);
7209 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7210 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7211 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7213 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7214 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7215 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7216 &low_our_to_self_config, 0, 42)
7219 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())); },
7220 _ => panic!("Unexpected event"),
7222 } else { assert!(false) }
7224 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7225 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7226 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7227 open_channel.to_self_delay = 200;
7228 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7229 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7230 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7233 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())); },
7234 _ => panic!("Unexpected event"),
7236 } else { assert!(false); }
7238 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7239 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7240 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()));
7241 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7242 accept_channel.to_self_delay = 200;
7243 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7245 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7247 &ErrorAction::SendErrorMessage { ref msg } => {
7248 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()));
7249 reason_msg = msg.data.clone();
7253 } else { panic!(); }
7254 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7256 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7257 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7258 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7259 open_channel.to_self_delay = 200;
7260 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7261 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7262 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7265 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())); },
7266 _ => panic!("Unexpected event"),
7268 } else { assert!(false); }
7272 fn test_data_loss_protect() {
7273 // We want to be sure that :
7274 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7275 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7276 // * we close channel in case of detecting other being fallen behind
7277 // * we are able to claim our own outputs thanks to to_remote being static
7278 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7284 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7285 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7286 // during signing due to revoked tx
7287 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7288 let keys_manager = &chanmon_cfgs[0].keys_manager;
7291 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7292 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7293 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7295 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7297 // Cache node A state before any channel update
7298 let previous_node_state = nodes[0].node.encode();
7299 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7300 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7302 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7303 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7305 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7306 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7308 // Restore node A from previous state
7309 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7310 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7311 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7312 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7313 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7314 persister = test_utils::TestPersister::new();
7315 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7317 let mut channel_monitors = HashMap::new();
7318 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7319 <(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 {
7320 keys_manager: keys_manager,
7321 fee_estimator: &fee_estimator,
7322 chain_monitor: &monitor,
7324 tx_broadcaster: &tx_broadcaster,
7325 default_config: UserConfig::default(),
7329 nodes[0].node = &node_state_0;
7330 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7331 nodes[0].chain_monitor = &monitor;
7332 nodes[0].chain_source = &chain_source;
7334 check_added_monitors!(nodes[0], 1);
7336 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7337 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7339 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7341 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7342 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7343 check_added_monitors!(nodes[0], 1);
7346 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7347 assert_eq!(node_txn.len(), 0);
7350 let mut reestablish_1 = Vec::with_capacity(1);
7351 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7352 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7353 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7354 reestablish_1.push(msg.clone());
7355 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7356 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7358 &ErrorAction::SendErrorMessage { ref msg } => {
7359 assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7361 _ => panic!("Unexpected event!"),
7364 panic!("Unexpected event")
7368 // Check we close channel detecting A is fallen-behind
7369 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7370 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7371 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7372 check_added_monitors!(nodes[1], 1);
7374 // Check A is able to claim to_remote output
7375 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7376 assert_eq!(node_txn.len(), 1);
7377 check_spends!(node_txn[0], chan.3);
7378 assert_eq!(node_txn[0].output.len(), 2);
7379 mine_transaction(&nodes[0], &node_txn[0]);
7380 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7381 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting".to_string() });
7382 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7383 assert_eq!(spend_txn.len(), 1);
7384 check_spends!(spend_txn[0], node_txn[0]);
7388 fn test_check_htlc_underpaying() {
7389 // Send payment through A -> B but A is maliciously
7390 // sending a probe payment (i.e less than expected value0
7391 // to B, B should refuse payment.
7393 let chanmon_cfgs = create_chanmon_cfgs(2);
7394 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7395 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7396 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7398 // Create some initial channels
7399 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7401 let scorer = test_utils::TestScorer::with_penalty(0);
7402 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7403 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7404 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();
7405 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7406 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7407 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7408 check_added_monitors!(nodes[0], 1);
7410 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7411 assert_eq!(events.len(), 1);
7412 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7413 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7414 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7416 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7417 // and then will wait a second random delay before failing the HTLC back:
7418 expect_pending_htlcs_forwardable!(nodes[1]);
7419 expect_pending_htlcs_forwardable!(nodes[1]);
7421 // Node 3 is expecting payment of 100_000 but received 10_000,
7422 // it should fail htlc like we didn't know the preimage.
7423 nodes[1].node.process_pending_htlc_forwards();
7425 let events = nodes[1].node.get_and_clear_pending_msg_events();
7426 assert_eq!(events.len(), 1);
7427 let (update_fail_htlc, commitment_signed) = match events[0] {
7428 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 } } => {
7429 assert!(update_add_htlcs.is_empty());
7430 assert!(update_fulfill_htlcs.is_empty());
7431 assert_eq!(update_fail_htlcs.len(), 1);
7432 assert!(update_fail_malformed_htlcs.is_empty());
7433 assert!(update_fee.is_none());
7434 (update_fail_htlcs[0].clone(), commitment_signed)
7436 _ => panic!("Unexpected event"),
7438 check_added_monitors!(nodes[1], 1);
7440 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7441 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7443 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7444 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7445 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7446 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7450 fn test_announce_disable_channels() {
7451 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7452 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7454 let chanmon_cfgs = create_chanmon_cfgs(2);
7455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7457 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7459 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7460 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7461 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7464 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7465 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7467 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7468 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7469 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7470 assert_eq!(msg_events.len(), 3);
7471 let mut chans_disabled = HashMap::new();
7472 for e in msg_events {
7474 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7475 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7476 // Check that each channel gets updated exactly once
7477 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7478 panic!("Generated ChannelUpdate for wrong chan!");
7481 _ => panic!("Unexpected event"),
7485 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7486 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7487 assert_eq!(reestablish_1.len(), 3);
7488 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7489 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7490 assert_eq!(reestablish_2.len(), 3);
7492 // Reestablish chan_1
7493 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7494 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7495 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7496 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7497 // Reestablish chan_2
7498 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7499 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7500 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7501 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7502 // Reestablish chan_3
7503 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7504 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7505 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7506 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7508 nodes[0].node.timer_tick_occurred();
7509 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7510 nodes[0].node.timer_tick_occurred();
7511 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7512 assert_eq!(msg_events.len(), 3);
7513 for e in msg_events {
7515 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7516 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7517 match chans_disabled.remove(&msg.contents.short_channel_id) {
7518 // Each update should have a higher timestamp than the previous one, replacing
7520 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7521 None => panic!("Generated ChannelUpdate for wrong chan!"),
7524 _ => panic!("Unexpected event"),
7527 // Check that each channel gets updated exactly once
7528 assert!(chans_disabled.is_empty());
7532 fn test_bump_penalty_txn_on_revoked_commitment() {
7533 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7534 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7536 let chanmon_cfgs = create_chanmon_cfgs(2);
7537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7539 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7541 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7543 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7544 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id())
7545 .with_features(InvoiceFeatures::known());
7546 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7547 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7549 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7550 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7551 assert_eq!(revoked_txn[0].output.len(), 4);
7552 assert_eq!(revoked_txn[0].input.len(), 1);
7553 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7554 let revoked_txid = revoked_txn[0].txid();
7556 let mut penalty_sum = 0;
7557 for outp in revoked_txn[0].output.iter() {
7558 if outp.script_pubkey.is_v0_p2wsh() {
7559 penalty_sum += outp.value;
7563 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7564 let header_114 = connect_blocks(&nodes[1], 14);
7566 // Actually revoke tx by claiming a HTLC
7567 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7568 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7569 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7570 check_added_monitors!(nodes[1], 1);
7572 // One or more justice tx should have been broadcast, check it
7576 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7577 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7578 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7579 assert_eq!(node_txn[0].output.len(), 1);
7580 check_spends!(node_txn[0], revoked_txn[0]);
7581 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7582 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7583 penalty_1 = node_txn[0].txid();
7587 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7588 connect_blocks(&nodes[1], 15);
7589 let mut penalty_2 = penalty_1;
7590 let mut feerate_2 = 0;
7592 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7593 assert_eq!(node_txn.len(), 1);
7594 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7595 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7596 assert_eq!(node_txn[0].output.len(), 1);
7597 check_spends!(node_txn[0], revoked_txn[0]);
7598 penalty_2 = node_txn[0].txid();
7599 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7600 assert_ne!(penalty_2, penalty_1);
7601 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7602 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7603 // Verify 25% bump heuristic
7604 assert!(feerate_2 * 100 >= feerate_1 * 125);
7608 assert_ne!(feerate_2, 0);
7610 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7611 connect_blocks(&nodes[1], 1);
7613 let mut feerate_3 = 0;
7615 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7616 assert_eq!(node_txn.len(), 1);
7617 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7618 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7619 assert_eq!(node_txn[0].output.len(), 1);
7620 check_spends!(node_txn[0], revoked_txn[0]);
7621 penalty_3 = node_txn[0].txid();
7622 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7623 assert_ne!(penalty_3, penalty_2);
7624 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7625 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7626 // Verify 25% bump heuristic
7627 assert!(feerate_3 * 100 >= feerate_2 * 125);
7631 assert_ne!(feerate_3, 0);
7633 nodes[1].node.get_and_clear_pending_events();
7634 nodes[1].node.get_and_clear_pending_msg_events();
7638 fn test_bump_penalty_txn_on_revoked_htlcs() {
7639 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7640 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7642 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7643 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7646 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7648 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7649 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7650 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7651 let scorer = test_utils::TestScorer::with_penalty(0);
7652 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7653 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7654 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7655 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7656 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7657 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7658 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7659 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7661 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7662 assert_eq!(revoked_local_txn[0].input.len(), 1);
7663 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7665 // Revoke local commitment tx
7666 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7668 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7669 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7670 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7671 check_closed_broadcast!(nodes[1], true);
7672 check_added_monitors!(nodes[1], 1);
7673 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7674 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7676 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7677 assert_eq!(revoked_htlc_txn.len(), 3);
7678 check_spends!(revoked_htlc_txn[1], chan.3);
7680 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7681 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7682 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7684 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7685 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7686 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7687 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7689 // Broadcast set of revoked txn on A
7690 let hash_128 = connect_blocks(&nodes[0], 40);
7691 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7692 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7693 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7694 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7695 let events = nodes[0].node.get_and_clear_pending_events();
7696 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7698 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7699 _ => panic!("Unexpected event"),
7705 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7706 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7707 // Verify claim tx are spending revoked HTLC txn
7709 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7710 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7711 // which are included in the same block (they are broadcasted because we scan the
7712 // transactions linearly and generate claims as we go, they likely should be removed in the
7714 assert_eq!(node_txn[0].input.len(), 1);
7715 check_spends!(node_txn[0], revoked_local_txn[0]);
7716 assert_eq!(node_txn[1].input.len(), 1);
7717 check_spends!(node_txn[1], revoked_local_txn[0]);
7718 assert_eq!(node_txn[2].input.len(), 1);
7719 check_spends!(node_txn[2], revoked_local_txn[0]);
7721 // Each of the three justice transactions claim a separate (single) output of the three
7722 // available, which we check here:
7723 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7724 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7725 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7727 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7728 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7730 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7731 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7732 // a remote commitment tx has already been confirmed).
7733 check_spends!(node_txn[3], chan.3);
7735 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7736 // output, checked above).
7737 assert_eq!(node_txn[4].input.len(), 2);
7738 assert_eq!(node_txn[4].output.len(), 1);
7739 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7741 first = node_txn[4].txid();
7742 // Store both feerates for later comparison
7743 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7744 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7745 penalty_txn = vec![node_txn[2].clone()];
7749 // Connect one more block to see if bumped penalty are issued for HTLC txn
7750 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7751 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7752 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7753 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7755 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7756 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7758 check_spends!(node_txn[0], revoked_local_txn[0]);
7759 check_spends!(node_txn[1], revoked_local_txn[0]);
7760 // Note that these are both bogus - they spend outputs already claimed in block 129:
7761 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7762 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7764 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7765 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7771 // Few more blocks to confirm penalty txn
7772 connect_blocks(&nodes[0], 4);
7773 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7774 let header_144 = connect_blocks(&nodes[0], 9);
7776 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7777 assert_eq!(node_txn.len(), 1);
7779 assert_eq!(node_txn[0].input.len(), 2);
7780 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7781 // Verify bumped tx is different and 25% bump heuristic
7782 assert_ne!(first, node_txn[0].txid());
7783 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7784 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7785 assert!(feerate_2 * 100 > feerate_1 * 125);
7786 let txn = vec![node_txn[0].clone()];
7790 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7791 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7792 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7793 connect_blocks(&nodes[0], 20);
7795 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7796 // We verify than no new transaction has been broadcast because previously
7797 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7798 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7799 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7800 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7801 // up bumped justice generation.
7802 assert_eq!(node_txn.len(), 0);
7805 check_closed_broadcast!(nodes[0], true);
7806 check_added_monitors!(nodes[0], 1);
7810 fn test_bump_penalty_txn_on_remote_commitment() {
7811 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7812 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7815 // Provide preimage for one
7816 // Check aggregation
7818 let chanmon_cfgs = create_chanmon_cfgs(2);
7819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7821 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7823 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7824 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7825 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7827 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7828 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7829 assert_eq!(remote_txn[0].output.len(), 4);
7830 assert_eq!(remote_txn[0].input.len(), 1);
7831 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7833 // Claim a HTLC without revocation (provide B monitor with preimage)
7834 nodes[1].node.claim_funds(payment_preimage);
7835 mine_transaction(&nodes[1], &remote_txn[0]);
7836 check_added_monitors!(nodes[1], 2);
7837 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7839 // One or more claim tx should have been broadcast, check it
7843 let feerate_timeout;
7844 let feerate_preimage;
7846 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7847 // 9 transactions including:
7848 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7849 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7850 // 2 * HTLC-Success (one RBF bump we'll check later)
7852 assert_eq!(node_txn.len(), 8);
7853 assert_eq!(node_txn[0].input.len(), 1);
7854 assert_eq!(node_txn[6].input.len(), 1);
7855 check_spends!(node_txn[0], remote_txn[0]);
7856 check_spends!(node_txn[6], remote_txn[0]);
7857 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7858 preimage_bump = node_txn[3].clone();
7860 check_spends!(node_txn[1], chan.3);
7861 check_spends!(node_txn[2], node_txn[1]);
7862 assert_eq!(node_txn[1], node_txn[4]);
7863 assert_eq!(node_txn[2], node_txn[5]);
7865 timeout = node_txn[6].txid();
7866 let index = node_txn[6].input[0].previous_output.vout;
7867 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7868 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7870 preimage = node_txn[0].txid();
7871 let index = node_txn[0].input[0].previous_output.vout;
7872 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7873 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7877 assert_ne!(feerate_timeout, 0);
7878 assert_ne!(feerate_preimage, 0);
7880 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7881 connect_blocks(&nodes[1], 15);
7883 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7884 assert_eq!(node_txn.len(), 1);
7885 assert_eq!(node_txn[0].input.len(), 1);
7886 assert_eq!(preimage_bump.input.len(), 1);
7887 check_spends!(node_txn[0], remote_txn[0]);
7888 check_spends!(preimage_bump, remote_txn[0]);
7890 let index = preimage_bump.input[0].previous_output.vout;
7891 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7892 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7893 assert!(new_feerate * 100 > feerate_timeout * 125);
7894 assert_ne!(timeout, preimage_bump.txid());
7896 let index = node_txn[0].input[0].previous_output.vout;
7897 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7898 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7899 assert!(new_feerate * 100 > feerate_preimage * 125);
7900 assert_ne!(preimage, node_txn[0].txid());
7905 nodes[1].node.get_and_clear_pending_events();
7906 nodes[1].node.get_and_clear_pending_msg_events();
7910 fn test_counterparty_raa_skip_no_crash() {
7911 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7912 // commitment transaction, we would have happily carried on and provided them the next
7913 // commitment transaction based on one RAA forward. This would probably eventually have led to
7914 // channel closure, but it would not have resulted in funds loss. Still, our
7915 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7916 // check simply that the channel is closed in response to such an RAA, but don't check whether
7917 // we decide to punish our counterparty for revoking their funds (as we don't currently
7919 let chanmon_cfgs = create_chanmon_cfgs(2);
7920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7923 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7925 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7926 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7928 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7930 // Make signer believe we got a counterparty signature, so that it allows the revocation
7931 keys.get_enforcement_state().last_holder_commitment -= 1;
7932 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7934 // Must revoke without gaps
7935 keys.get_enforcement_state().last_holder_commitment -= 1;
7936 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7938 keys.get_enforcement_state().last_holder_commitment -= 1;
7939 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7940 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7942 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7943 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7944 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7945 check_added_monitors!(nodes[1], 1);
7946 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7950 fn test_bump_txn_sanitize_tracking_maps() {
7951 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7952 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7954 let chanmon_cfgs = create_chanmon_cfgs(2);
7955 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7956 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7957 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7959 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7960 // Lock HTLC in both directions
7961 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7962 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7964 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7965 assert_eq!(revoked_local_txn[0].input.len(), 1);
7966 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7968 // Revoke local commitment tx
7969 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7971 // Broadcast set of revoked txn on A
7972 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7973 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7974 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7976 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7977 check_closed_broadcast!(nodes[0], true);
7978 check_added_monitors!(nodes[0], 1);
7979 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7981 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7982 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7983 check_spends!(node_txn[0], revoked_local_txn[0]);
7984 check_spends!(node_txn[1], revoked_local_txn[0]);
7985 check_spends!(node_txn[2], revoked_local_txn[0]);
7986 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7990 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7991 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7992 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7994 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7995 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7996 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8001 fn test_pending_claimed_htlc_no_balance_underflow() {
8002 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8003 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8004 let chanmon_cfgs = create_chanmon_cfgs(2);
8005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8007 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8008 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8010 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8011 nodes[1].node.claim_funds(payment_preimage);
8012 check_added_monitors!(nodes[1], 1);
8013 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8015 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8016 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8017 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8018 check_added_monitors!(nodes[0], 1);
8019 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8021 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8022 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8023 // can get our balance.
8025 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8026 // the public key of the only hop. This works around ChannelDetails not showing the
8027 // almost-claimed HTLC as available balance.
8028 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8029 route.payment_params = None; // This is all wrong, but unnecessary
8030 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8031 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8032 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8034 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8038 fn test_channel_conf_timeout() {
8039 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8040 // confirm within 2016 blocks, as recommended by BOLT 2.
8041 let chanmon_cfgs = create_chanmon_cfgs(2);
8042 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8043 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8044 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8046 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8048 // The outbound node should wait forever for confirmation:
8049 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8050 // copied here instead of directly referencing the constant.
8051 connect_blocks(&nodes[0], 2016);
8052 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8054 // The inbound node should fail the channel after exactly 2016 blocks
8055 connect_blocks(&nodes[1], 2015);
8056 check_added_monitors!(nodes[1], 0);
8057 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8059 connect_blocks(&nodes[1], 1);
8060 check_added_monitors!(nodes[1], 1);
8061 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8062 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8063 assert_eq!(close_ev.len(), 1);
8065 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8066 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8067 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8069 _ => panic!("Unexpected event"),
8074 fn test_override_channel_config() {
8075 let chanmon_cfgs = create_chanmon_cfgs(2);
8076 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8077 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8078 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8080 // Node0 initiates a channel to node1 using the override config.
8081 let mut override_config = UserConfig::default();
8082 override_config.own_channel_config.our_to_self_delay = 200;
8084 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8086 // Assert the channel created by node0 is using the override config.
8087 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8088 assert_eq!(res.channel_flags, 0);
8089 assert_eq!(res.to_self_delay, 200);
8093 fn test_override_0msat_htlc_minimum() {
8094 let mut zero_config = UserConfig::default();
8095 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8096 let chanmon_cfgs = create_chanmon_cfgs(2);
8097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8099 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8101 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8102 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8103 assert_eq!(res.htlc_minimum_msat, 1);
8105 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8106 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8107 assert_eq!(res.htlc_minimum_msat, 1);
8111 fn test_manually_accept_inbound_channel_request() {
8112 let mut manually_accept_conf = UserConfig::default();
8113 manually_accept_conf.manually_accept_inbound_channels = true;
8114 let chanmon_cfgs = create_chanmon_cfgs(2);
8115 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8116 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8117 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8119 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8120 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8122 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8124 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8125 // accepting the inbound channel request.
8126 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8128 let events = nodes[1].node.get_and_clear_pending_events();
8130 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8131 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8133 _ => panic!("Unexpected event"),
8136 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8137 assert_eq!(accept_msg_ev.len(), 1);
8139 match accept_msg_ev[0] {
8140 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8141 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8143 _ => panic!("Unexpected event"),
8146 nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8148 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8149 assert_eq!(close_msg_ev.len(), 1);
8151 let events = nodes[1].node.get_and_clear_pending_events();
8153 Event::ChannelClosed { user_channel_id, .. } => {
8154 assert_eq!(user_channel_id, 23);
8156 _ => panic!("Unexpected event"),
8161 fn test_manually_reject_inbound_channel_request() {
8162 let mut manually_accept_conf = UserConfig::default();
8163 manually_accept_conf.manually_accept_inbound_channels = true;
8164 let chanmon_cfgs = create_chanmon_cfgs(2);
8165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8169 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8170 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8172 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8174 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8175 // rejecting the inbound channel request.
8176 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8178 let events = nodes[1].node.get_and_clear_pending_events();
8180 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8181 nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8183 _ => panic!("Unexpected event"),
8186 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8187 assert_eq!(close_msg_ev.len(), 1);
8189 match close_msg_ev[0] {
8190 MessageSendEvent::HandleError { ref node_id, .. } => {
8191 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8193 _ => panic!("Unexpected event"),
8195 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8199 fn test_reject_funding_before_inbound_channel_accepted() {
8200 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8201 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8202 // the node operator before the counterparty sends a `FundingCreated` message. If a
8203 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8204 // and the channel should be closed.
8205 let mut manually_accept_conf = UserConfig::default();
8206 manually_accept_conf.manually_accept_inbound_channels = true;
8207 let chanmon_cfgs = create_chanmon_cfgs(2);
8208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8210 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8212 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8213 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8214 let temp_channel_id = res.temporary_channel_id;
8216 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8218 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8219 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8221 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8222 nodes[1].node.get_and_clear_pending_events();
8224 // Get the `AcceptChannel` message of `nodes[1]` without calling
8225 // `ChannelManager::accept_inbound_channel`, which generates a
8226 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8227 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8228 // succeed when `nodes[0]` is passed to it.
8231 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8232 let accept_chan_msg = channel.get_accept_channel_message();
8233 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8236 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8238 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8239 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8241 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8242 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8244 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8245 assert_eq!(close_msg_ev.len(), 1);
8247 let expected_err = "FundingCreated message received before the channel was accepted";
8248 match close_msg_ev[0] {
8249 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8250 assert_eq!(msg.channel_id, temp_channel_id);
8251 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8252 assert_eq!(msg.data, expected_err);
8254 _ => panic!("Unexpected event"),
8257 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8261 fn test_can_not_accept_inbound_channel_twice() {
8262 let mut manually_accept_conf = UserConfig::default();
8263 manually_accept_conf.manually_accept_inbound_channels = true;
8264 let chanmon_cfgs = create_chanmon_cfgs(2);
8265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8269 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8270 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8272 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8274 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8275 // accepting the inbound channel request.
8276 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8278 let events = nodes[1].node.get_and_clear_pending_events();
8280 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8281 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8282 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8284 Err(APIError::APIMisuseError { err }) => {
8285 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8287 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8288 Err(_) => panic!("Unexpected Error"),
8291 _ => panic!("Unexpected event"),
8294 // Ensure that the channel wasn't closed after attempting to accept it twice.
8295 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8296 assert_eq!(accept_msg_ev.len(), 1);
8298 match accept_msg_ev[0] {
8299 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8300 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8302 _ => panic!("Unexpected event"),
8307 fn test_can_not_accept_unknown_inbound_channel() {
8308 let chanmon_cfg = create_chanmon_cfgs(1);
8309 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8310 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8311 let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8313 let unknown_channel_id = [0; 32];
8314 let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8316 Err(APIError::ChannelUnavailable { err }) => {
8317 assert_eq!(err, "Can't accept a channel that doesn't exist");
8319 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8320 Err(_) => panic!("Unexpected Error"),
8325 fn test_simple_mpp() {
8326 // Simple test of sending a multi-path payment.
8327 let chanmon_cfgs = create_chanmon_cfgs(4);
8328 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8329 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8330 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8332 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8333 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8334 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8335 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8337 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8338 let path = route.paths[0].clone();
8339 route.paths.push(path);
8340 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8341 route.paths[0][0].short_channel_id = chan_1_id;
8342 route.paths[0][1].short_channel_id = chan_3_id;
8343 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8344 route.paths[1][0].short_channel_id = chan_2_id;
8345 route.paths[1][1].short_channel_id = chan_4_id;
8346 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8347 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8351 fn test_preimage_storage() {
8352 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8353 let chanmon_cfgs = create_chanmon_cfgs(2);
8354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8356 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8358 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8361 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8362 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8363 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8364 check_added_monitors!(nodes[0], 1);
8365 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8366 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8367 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8368 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8370 // Note that after leaving the above scope we have no knowledge of any arguments or return
8371 // values from previous calls.
8372 expect_pending_htlcs_forwardable!(nodes[1]);
8373 let events = nodes[1].node.get_and_clear_pending_events();
8374 assert_eq!(events.len(), 1);
8376 Event::PaymentReceived { ref purpose, .. } => {
8378 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8379 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8381 _ => panic!("expected PaymentPurpose::InvoicePayment")
8384 _ => panic!("Unexpected event"),
8389 #[allow(deprecated)]
8390 fn test_secret_timeout() {
8391 // Simple test of payment secret storage time outs. After
8392 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8393 let chanmon_cfgs = create_chanmon_cfgs(2);
8394 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8395 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8396 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8398 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8400 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8402 // We should fail to register the same payment hash twice, at least until we've connected a
8403 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8404 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8405 assert_eq!(err, "Duplicate payment hash");
8406 } else { panic!(); }
8408 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8410 header: BlockHeader {
8412 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8413 merkle_root: Default::default(),
8414 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8418 connect_block(&nodes[1], &block);
8419 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8420 assert_eq!(err, "Duplicate payment hash");
8421 } else { panic!(); }
8423 // If we then connect the second block, we should be able to register the same payment hash
8424 // again (this time getting a new payment secret).
8425 block.header.prev_blockhash = block.header.block_hash();
8426 block.header.time += 1;
8427 connect_block(&nodes[1], &block);
8428 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8429 assert_ne!(payment_secret_1, our_payment_secret);
8432 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8433 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8434 check_added_monitors!(nodes[0], 1);
8435 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8436 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8437 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8438 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8440 // Note that after leaving the above scope we have no knowledge of any arguments or return
8441 // values from previous calls.
8442 expect_pending_htlcs_forwardable!(nodes[1]);
8443 let events = nodes[1].node.get_and_clear_pending_events();
8444 assert_eq!(events.len(), 1);
8446 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8447 assert!(payment_preimage.is_none());
8448 assert_eq!(payment_secret, our_payment_secret);
8449 // We don't actually have the payment preimage with which to claim this payment!
8451 _ => panic!("Unexpected event"),
8456 fn test_bad_secret_hash() {
8457 // Simple test of unregistered payment hash/invalid payment secret handling
8458 let chanmon_cfgs = create_chanmon_cfgs(2);
8459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8460 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8461 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8463 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8465 let random_payment_hash = PaymentHash([42; 32]);
8466 let random_payment_secret = PaymentSecret([43; 32]);
8467 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8468 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8470 // All the below cases should end up being handled exactly identically, so we macro the
8471 // resulting events.
8472 macro_rules! handle_unknown_invalid_payment_data {
8474 check_added_monitors!(nodes[0], 1);
8475 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8476 let payment_event = SendEvent::from_event(events.pop().unwrap());
8477 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8478 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8480 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8481 // again to process the pending backwards-failure of the HTLC
8482 expect_pending_htlcs_forwardable!(nodes[1]);
8483 expect_pending_htlcs_forwardable!(nodes[1]);
8484 check_added_monitors!(nodes[1], 1);
8486 // We should fail the payment back
8487 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8488 match events.pop().unwrap() {
8489 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8490 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8491 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8493 _ => panic!("Unexpected event"),
8498 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8499 // Error data is the HTLC value (100,000) and current block height
8500 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8502 // Send a payment with the right payment hash but the wrong payment secret
8503 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8504 handle_unknown_invalid_payment_data!();
8505 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8507 // Send a payment with a random payment hash, but the right payment secret
8508 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8509 handle_unknown_invalid_payment_data!();
8510 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8512 // Send a payment with a random payment hash and random payment secret
8513 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8514 handle_unknown_invalid_payment_data!();
8515 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8519 fn test_update_err_monitor_lockdown() {
8520 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8521 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8522 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8524 // This scenario may happen in a watchtower setup, where watchtower process a block height
8525 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8526 // commitment at same time.
8528 let chanmon_cfgs = create_chanmon_cfgs(2);
8529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8531 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8533 // Create some initial channel
8534 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8535 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8537 // Rebalance the network to generate htlc in the two directions
8538 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8540 // Route a HTLC from node 0 to node 1 (but don't settle)
8541 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8543 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8544 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8545 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8546 let persister = test_utils::TestPersister::new();
8548 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8549 let mut w = test_utils::TestVecWriter(Vec::new());
8550 monitor.write(&mut w).unwrap();
8551 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8552 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8553 assert!(new_monitor == *monitor);
8554 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);
8555 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8558 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8559 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8560 // transaction lock time requirements here.
8561 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8562 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8564 // Try to update ChannelMonitor
8565 assert!(nodes[1].node.claim_funds(preimage));
8566 check_added_monitors!(nodes[1], 1);
8567 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8568 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8569 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8570 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8571 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8572 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8573 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8574 } else { assert!(false); }
8575 } else { assert!(false); };
8576 // Our local monitor is in-sync and hasn't processed yet timeout
8577 check_added_monitors!(nodes[0], 1);
8578 let events = nodes[0].node.get_and_clear_pending_events();
8579 assert_eq!(events.len(), 1);
8583 fn test_concurrent_monitor_claim() {
8584 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8585 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8586 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8587 // state N+1 confirms. Alice claims output from state N+1.
8589 let chanmon_cfgs = create_chanmon_cfgs(2);
8590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8592 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8594 // Create some initial channel
8595 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8596 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8598 // Rebalance the network to generate htlc in the two directions
8599 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8601 // Route a HTLC from node 0 to node 1 (but don't settle)
8602 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8604 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8605 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8606 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8607 let persister = test_utils::TestPersister::new();
8608 let watchtower_alice = {
8609 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8610 let mut w = test_utils::TestVecWriter(Vec::new());
8611 monitor.write(&mut w).unwrap();
8612 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8613 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8614 assert!(new_monitor == *monitor);
8615 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);
8616 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8619 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8620 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8621 // transaction lock time requirements here.
8622 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8623 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8625 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8627 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8628 assert_eq!(txn.len(), 2);
8632 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8633 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8634 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8635 let persister = test_utils::TestPersister::new();
8636 let watchtower_bob = {
8637 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8638 let mut w = test_utils::TestVecWriter(Vec::new());
8639 monitor.write(&mut w).unwrap();
8640 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8641 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8642 assert!(new_monitor == *monitor);
8643 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);
8644 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8647 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8648 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8650 // Route another payment to generate another update with still previous HTLC pending
8651 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8653 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8655 check_added_monitors!(nodes[1], 1);
8657 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8658 assert_eq!(updates.update_add_htlcs.len(), 1);
8659 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8660 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8661 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8662 // Watchtower Alice should already have seen the block and reject the update
8663 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8664 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8665 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8666 } else { assert!(false); }
8667 } else { assert!(false); };
8668 // Our local monitor is in-sync and hasn't processed yet timeout
8669 check_added_monitors!(nodes[0], 1);
8671 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8672 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8673 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8675 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8678 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8679 assert_eq!(txn.len(), 2);
8680 bob_state_y = txn[0].clone();
8684 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8685 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8686 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);
8688 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8689 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8690 // the onchain detection of the HTLC output
8691 assert_eq!(htlc_txn.len(), 2);
8692 check_spends!(htlc_txn[0], bob_state_y);
8693 check_spends!(htlc_txn[1], bob_state_y);
8698 fn test_pre_lockin_no_chan_closed_update() {
8699 // Test that if a peer closes a channel in response to a funding_created message we don't
8700 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8703 // Doing so would imply a channel monitor update before the initial channel monitor
8704 // registration, violating our API guarantees.
8706 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8707 // then opening a second channel with the same funding output as the first (which is not
8708 // rejected because the first channel does not exist in the ChannelManager) and closing it
8709 // before receiving funding_signed.
8710 let chanmon_cfgs = create_chanmon_cfgs(2);
8711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8715 // Create an initial channel
8716 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8717 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8718 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8719 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8720 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8722 // Move the first channel through the funding flow...
8723 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8725 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8726 check_added_monitors!(nodes[0], 0);
8728 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8729 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8730 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8731 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8732 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8736 fn test_htlc_no_detection() {
8737 // This test is a mutation to underscore the detection logic bug we had
8738 // before #653. HTLC value routed is above the remaining balance, thus
8739 // inverting HTLC and `to_remote` output. HTLC will come second and
8740 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8741 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8742 // outputs order detection for correct spending children filtring.
8744 let chanmon_cfgs = create_chanmon_cfgs(2);
8745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8749 // Create some initial channels
8750 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8752 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8753 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8754 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8755 assert_eq!(local_txn[0].input.len(), 1);
8756 assert_eq!(local_txn[0].output.len(), 3);
8757 check_spends!(local_txn[0], chan_1.3);
8759 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8760 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8761 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8762 // We deliberately connect the local tx twice as this should provoke a failure calling
8763 // this test before #653 fix.
8764 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);
8765 check_closed_broadcast!(nodes[0], true);
8766 check_added_monitors!(nodes[0], 1);
8767 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8768 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8770 let htlc_timeout = {
8771 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8772 assert_eq!(node_txn[1].input.len(), 1);
8773 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8774 check_spends!(node_txn[1], local_txn[0]);
8778 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8779 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8780 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8781 expect_payment_failed!(nodes[0], our_payment_hash, true);
8784 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8785 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8786 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8787 // Carol, Alice would be the upstream node, and Carol the downstream.)
8789 // Steps of the test:
8790 // 1) Alice sends a HTLC to Carol through Bob.
8791 // 2) Carol doesn't settle the HTLC.
8792 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8793 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8794 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8795 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8796 // 5) Carol release the preimage to Bob off-chain.
8797 // 6) Bob claims the offered output on the broadcasted commitment.
8798 let chanmon_cfgs = create_chanmon_cfgs(3);
8799 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8800 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8801 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8803 // Create some initial channels
8804 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8805 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8807 // Steps (1) and (2):
8808 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8809 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8811 // Check that Alice's commitment transaction now contains an output for this HTLC.
8812 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8813 check_spends!(alice_txn[0], chan_ab.3);
8814 assert_eq!(alice_txn[0].output.len(), 2);
8815 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8816 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8817 assert_eq!(alice_txn.len(), 2);
8819 // Steps (3) and (4):
8820 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8821 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8822 let mut force_closing_node = 0; // Alice force-closes
8823 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8824 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8825 check_closed_broadcast!(nodes[force_closing_node], true);
8826 check_added_monitors!(nodes[force_closing_node], 1);
8827 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8828 if go_onchain_before_fulfill {
8829 let txn_to_broadcast = match broadcast_alice {
8830 true => alice_txn.clone(),
8831 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8833 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8834 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8835 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8836 if broadcast_alice {
8837 check_closed_broadcast!(nodes[1], true);
8838 check_added_monitors!(nodes[1], 1);
8839 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8841 assert_eq!(bob_txn.len(), 1);
8842 check_spends!(bob_txn[0], chan_ab.3);
8846 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8847 // process of removing the HTLC from their commitment transactions.
8848 assert!(nodes[2].node.claim_funds(payment_preimage));
8849 check_added_monitors!(nodes[2], 1);
8850 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8851 assert!(carol_updates.update_add_htlcs.is_empty());
8852 assert!(carol_updates.update_fail_htlcs.is_empty());
8853 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8854 assert!(carol_updates.update_fee.is_none());
8855 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8857 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8858 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8859 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8860 if !go_onchain_before_fulfill && broadcast_alice {
8861 let events = nodes[1].node.get_and_clear_pending_msg_events();
8862 assert_eq!(events.len(), 1);
8864 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8865 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8867 _ => panic!("Unexpected event"),
8870 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8871 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8872 // Carol<->Bob's updated commitment transaction info.
8873 check_added_monitors!(nodes[1], 2);
8875 let events = nodes[1].node.get_and_clear_pending_msg_events();
8876 assert_eq!(events.len(), 2);
8877 let bob_revocation = match events[0] {
8878 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8879 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8882 _ => panic!("Unexpected event"),
8884 let bob_updates = match events[1] {
8885 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8886 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8889 _ => panic!("Unexpected event"),
8892 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8893 check_added_monitors!(nodes[2], 1);
8894 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8895 check_added_monitors!(nodes[2], 1);
8897 let events = nodes[2].node.get_and_clear_pending_msg_events();
8898 assert_eq!(events.len(), 1);
8899 let carol_revocation = match events[0] {
8900 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8901 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8904 _ => panic!("Unexpected event"),
8906 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8907 check_added_monitors!(nodes[1], 1);
8909 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8910 // here's where we put said channel's commitment tx on-chain.
8911 let mut txn_to_broadcast = alice_txn.clone();
8912 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8913 if !go_onchain_before_fulfill {
8914 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8915 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8916 // If Bob was the one to force-close, he will have already passed these checks earlier.
8917 if broadcast_alice {
8918 check_closed_broadcast!(nodes[1], true);
8919 check_added_monitors!(nodes[1], 1);
8920 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8922 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8923 if broadcast_alice {
8924 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8925 // new block being connected. The ChannelManager being notified triggers a monitor update,
8926 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8927 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8929 assert_eq!(bob_txn.len(), 3);
8930 check_spends!(bob_txn[1], chan_ab.3);
8932 assert_eq!(bob_txn.len(), 2);
8933 check_spends!(bob_txn[0], chan_ab.3);
8938 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8939 // broadcasted commitment transaction.
8941 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8942 if go_onchain_before_fulfill {
8943 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8944 assert_eq!(bob_txn.len(), 2);
8946 let script_weight = match broadcast_alice {
8947 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8948 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8950 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8951 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8952 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8953 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8954 if broadcast_alice && !go_onchain_before_fulfill {
8955 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8956 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8958 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8959 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8965 fn test_onchain_htlc_settlement_after_close() {
8966 do_test_onchain_htlc_settlement_after_close(true, true);
8967 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8968 do_test_onchain_htlc_settlement_after_close(true, false);
8969 do_test_onchain_htlc_settlement_after_close(false, false);
8973 fn test_duplicate_chan_id() {
8974 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8975 // already open we reject it and keep the old channel.
8977 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8978 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8979 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8980 // updating logic for the existing channel.
8981 let chanmon_cfgs = create_chanmon_cfgs(2);
8982 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8983 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8984 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8986 // Create an initial channel
8987 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8988 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8989 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8990 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()));
8992 // Try to create a second channel with the same temporary_channel_id as the first and check
8993 // that it is rejected.
8994 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8996 let events = nodes[1].node.get_and_clear_pending_msg_events();
8997 assert_eq!(events.len(), 1);
8999 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9000 // Technically, at this point, nodes[1] would be justified in thinking both the
9001 // first (valid) and second (invalid) channels are closed, given they both have
9002 // the same non-temporary channel_id. However, currently we do not, so we just
9003 // move forward with it.
9004 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9005 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9007 _ => panic!("Unexpected event"),
9011 // Move the first channel through the funding flow...
9012 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9014 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9015 check_added_monitors!(nodes[0], 0);
9017 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9018 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9020 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9021 assert_eq!(added_monitors.len(), 1);
9022 assert_eq!(added_monitors[0].0, funding_output);
9023 added_monitors.clear();
9025 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9027 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9028 let channel_id = funding_outpoint.to_channel_id();
9030 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9033 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9034 // Technically this is allowed by the spec, but we don't support it and there's little reason
9035 // to. Still, it shouldn't cause any other issues.
9036 open_chan_msg.temporary_channel_id = channel_id;
9037 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9039 let events = nodes[1].node.get_and_clear_pending_msg_events();
9040 assert_eq!(events.len(), 1);
9042 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9043 // Technically, at this point, nodes[1] would be justified in thinking both
9044 // channels are closed, but currently we do not, so we just move forward with it.
9045 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9046 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9048 _ => panic!("Unexpected event"),
9052 // Now try to create a second channel which has a duplicate funding output.
9053 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9054 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9055 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9056 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()));
9057 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9059 let funding_created = {
9060 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9061 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9062 let logger = test_utils::TestLogger::new();
9063 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9065 check_added_monitors!(nodes[0], 0);
9066 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9067 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9068 // still needs to be cleared here.
9069 check_added_monitors!(nodes[1], 1);
9071 // ...still, nodes[1] will reject the duplicate channel.
9073 let events = nodes[1].node.get_and_clear_pending_msg_events();
9074 assert_eq!(events.len(), 1);
9076 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9077 // Technically, at this point, nodes[1] would be justified in thinking both
9078 // channels are closed, but currently we do not, so we just move forward with it.
9079 assert_eq!(msg.channel_id, channel_id);
9080 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9082 _ => panic!("Unexpected event"),
9086 // finally, finish creating the original channel and send a payment over it to make sure
9087 // everything is functional.
9088 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9090 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9091 assert_eq!(added_monitors.len(), 1);
9092 assert_eq!(added_monitors[0].0, funding_output);
9093 added_monitors.clear();
9096 let events_4 = nodes[0].node.get_and_clear_pending_events();
9097 assert_eq!(events_4.len(), 0);
9098 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9099 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9101 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9102 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9103 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9104 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9108 fn test_error_chans_closed() {
9109 // Test that we properly handle error messages, closing appropriate channels.
9111 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9112 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9113 // we can test various edge cases around it to ensure we don't regress.
9114 let chanmon_cfgs = create_chanmon_cfgs(3);
9115 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9116 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9117 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9119 // Create some initial channels
9120 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9121 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9122 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9124 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9125 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9126 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9128 // Closing a channel from a different peer has no effect
9129 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9130 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9132 // Closing one channel doesn't impact others
9133 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9134 check_added_monitors!(nodes[0], 1);
9135 check_closed_broadcast!(nodes[0], false);
9136 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9137 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9138 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9139 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);
9140 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);
9142 // A null channel ID should close all channels
9143 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9144 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9145 check_added_monitors!(nodes[0], 2);
9146 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9147 let events = nodes[0].node.get_and_clear_pending_msg_events();
9148 assert_eq!(events.len(), 2);
9150 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9151 assert_eq!(msg.contents.flags & 2, 2);
9153 _ => panic!("Unexpected event"),
9156 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9157 assert_eq!(msg.contents.flags & 2, 2);
9159 _ => panic!("Unexpected event"),
9161 // Note that at this point users of a standard PeerHandler will end up calling
9162 // peer_disconnected with no_connection_possible set to false, duplicating the
9163 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9164 // users with their own peer handling logic. We duplicate the call here, however.
9165 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9166 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9168 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9169 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9170 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9174 fn test_invalid_funding_tx() {
9175 // Test that we properly handle invalid funding transactions sent to us from a peer.
9177 // Previously, all other major lightning implementations had failed to properly sanitize
9178 // funding transactions from their counterparties, leading to a multi-implementation critical
9179 // security vulnerability (though we always sanitized properly, we've previously had
9180 // un-released crashes in the sanitization process).
9181 let chanmon_cfgs = create_chanmon_cfgs(2);
9182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9186 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9187 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()));
9188 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()));
9190 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9191 for output in tx.output.iter_mut() {
9192 // Make the confirmed funding transaction have a bogus script_pubkey
9193 output.script_pubkey = bitcoin::Script::new();
9196 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9197 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()));
9198 check_added_monitors!(nodes[1], 1);
9200 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()));
9201 check_added_monitors!(nodes[0], 1);
9203 let events_1 = nodes[0].node.get_and_clear_pending_events();
9204 assert_eq!(events_1.len(), 0);
9206 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9207 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9208 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9210 let expected_err = "funding tx had wrong script/value or output index";
9211 confirm_transaction_at(&nodes[1], &tx, 1);
9212 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9213 check_added_monitors!(nodes[1], 1);
9214 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9215 assert_eq!(events_2.len(), 1);
9216 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9217 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9218 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9219 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9220 } else { panic!(); }
9221 } else { panic!(); }
9222 assert_eq!(nodes[1].node.list_channels().len(), 0);
9225 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9226 // In the first version of the chain::Confirm interface, after a refactor was made to not
9227 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9228 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9229 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9230 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9231 // spending transaction until height N+1 (or greater). This was due to the way
9232 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9233 // spending transaction at the height the input transaction was confirmed at, not whether we
9234 // should broadcast a spending transaction at the current height.
9235 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9236 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9237 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9238 // until we learned about an additional block.
9240 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9241 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9242 let chanmon_cfgs = create_chanmon_cfgs(3);
9243 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9244 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9245 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9246 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9248 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9249 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9250 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9251 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9252 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9254 nodes[1].node.force_close_channel(&channel_id).unwrap();
9255 check_closed_broadcast!(nodes[1], true);
9256 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9257 check_added_monitors!(nodes[1], 1);
9258 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9259 assert_eq!(node_txn.len(), 1);
9261 let conf_height = nodes[1].best_block_info().1;
9262 if !test_height_before_timelock {
9263 connect_blocks(&nodes[1], 24 * 6);
9265 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9266 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9267 if test_height_before_timelock {
9268 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9269 // generate any events or broadcast any transactions
9270 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9271 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9273 // We should broadcast an HTLC transaction spending our funding transaction first
9274 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9275 assert_eq!(spending_txn.len(), 2);
9276 assert_eq!(spending_txn[0], node_txn[0]);
9277 check_spends!(spending_txn[1], node_txn[0]);
9278 // We should also generate a SpendableOutputs event with the to_self output (as its
9280 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9281 assert_eq!(descriptor_spend_txn.len(), 1);
9283 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9284 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9285 // additional block built on top of the current chain.
9286 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9287 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9288 expect_pending_htlcs_forwardable!(nodes[1]);
9289 check_added_monitors!(nodes[1], 1);
9291 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9292 assert!(updates.update_add_htlcs.is_empty());
9293 assert!(updates.update_fulfill_htlcs.is_empty());
9294 assert_eq!(updates.update_fail_htlcs.len(), 1);
9295 assert!(updates.update_fail_malformed_htlcs.is_empty());
9296 assert!(updates.update_fee.is_none());
9297 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9298 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9299 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9304 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9305 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9306 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9310 fn test_forwardable_regen() {
9311 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9312 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9314 // We test it for both payment receipt and payment forwarding.
9316 let chanmon_cfgs = create_chanmon_cfgs(3);
9317 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9318 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9319 let persister: test_utils::TestPersister;
9320 let new_chain_monitor: test_utils::TestChainMonitor;
9321 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9322 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9323 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9324 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9326 // First send a payment to nodes[1]
9327 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9328 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9329 check_added_monitors!(nodes[0], 1);
9331 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9332 assert_eq!(events.len(), 1);
9333 let payment_event = SendEvent::from_event(events.pop().unwrap());
9334 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9335 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9337 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9339 // Next send a payment which is forwarded by nodes[1]
9340 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9341 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9342 check_added_monitors!(nodes[0], 1);
9344 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9345 assert_eq!(events.len(), 1);
9346 let payment_event = SendEvent::from_event(events.pop().unwrap());
9347 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9348 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9350 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9352 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9354 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9355 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9356 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9358 let nodes_1_serialized = nodes[1].node.encode();
9359 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9360 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9361 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9362 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9364 persister = test_utils::TestPersister::new();
9365 let keys_manager = &chanmon_cfgs[1].keys_manager;
9366 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);
9367 nodes[1].chain_monitor = &new_chain_monitor;
9369 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9370 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9371 &mut chan_0_monitor_read, keys_manager).unwrap();
9372 assert!(chan_0_monitor_read.is_empty());
9373 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9374 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9375 &mut chan_1_monitor_read, keys_manager).unwrap();
9376 assert!(chan_1_monitor_read.is_empty());
9378 let mut nodes_1_read = &nodes_1_serialized[..];
9379 let (_, nodes_1_deserialized_tmp) = {
9380 let mut channel_monitors = HashMap::new();
9381 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9382 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9383 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9384 default_config: UserConfig::default(),
9386 fee_estimator: node_cfgs[1].fee_estimator,
9387 chain_monitor: nodes[1].chain_monitor,
9388 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9389 logger: nodes[1].logger,
9393 nodes_1_deserialized = nodes_1_deserialized_tmp;
9394 assert!(nodes_1_read.is_empty());
9396 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9397 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9398 nodes[1].node = &nodes_1_deserialized;
9399 check_added_monitors!(nodes[1], 2);
9401 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9402 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9403 // the commitment state.
9404 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9406 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9408 expect_pending_htlcs_forwardable!(nodes[1]);
9409 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9410 check_added_monitors!(nodes[1], 1);
9412 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9413 assert_eq!(events.len(), 1);
9414 let payment_event = SendEvent::from_event(events.pop().unwrap());
9415 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9416 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9417 expect_pending_htlcs_forwardable!(nodes[2]);
9418 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9420 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9421 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9425 fn test_dup_htlc_second_fail_panic() {
9426 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9427 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9428 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9429 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9430 let chanmon_cfgs = create_chanmon_cfgs(2);
9431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9433 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9435 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9437 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9438 .with_features(InvoiceFeatures::known());
9439 let scorer = test_utils::TestScorer::with_penalty(0);
9440 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9441 let route = get_route(
9442 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
9443 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
9444 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9446 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9449 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9450 check_added_monitors!(nodes[0], 1);
9451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9452 assert_eq!(events.len(), 1);
9453 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9454 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9455 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9457 expect_pending_htlcs_forwardable!(nodes[1]);
9458 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9461 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9462 check_added_monitors!(nodes[0], 1);
9463 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9464 assert_eq!(events.len(), 1);
9465 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9466 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9467 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9468 // At this point, nodes[1] would notice it has too much value for the payment. It will
9469 // assume the second is a privacy attack (no longer particularly relevant
9470 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9471 // the first HTLC delivered above.
9474 // Now we go fail back the first HTLC from the user end.
9475 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9476 nodes[1].node.process_pending_htlc_forwards();
9477 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9479 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9480 nodes[1].node.process_pending_htlc_forwards();
9482 check_added_monitors!(nodes[1], 1);
9483 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9484 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9486 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9487 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9488 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9490 let failure_events = nodes[0].node.get_and_clear_pending_events();
9491 assert_eq!(failure_events.len(), 2);
9492 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9493 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9497 fn test_keysend_payments_to_public_node() {
9498 let chanmon_cfgs = create_chanmon_cfgs(2);
9499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9503 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9504 let network_graph = nodes[0].network_graph;
9505 let payer_pubkey = nodes[0].node.get_our_node_id();
9506 let payee_pubkey = nodes[1].node.get_our_node_id();
9507 let route_params = RouteParameters {
9508 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9509 final_value_msat: 10000,
9510 final_cltv_expiry_delta: 40,
9512 let scorer = test_utils::TestScorer::with_penalty(0);
9513 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9514 let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9516 let test_preimage = PaymentPreimage([42; 32]);
9517 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9518 check_added_monitors!(nodes[0], 1);
9519 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9520 assert_eq!(events.len(), 1);
9521 let event = events.pop().unwrap();
9522 let path = vec![&nodes[1]];
9523 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9524 claim_payment(&nodes[0], &path, test_preimage);
9528 fn test_keysend_payments_to_private_node() {
9529 let chanmon_cfgs = create_chanmon_cfgs(2);
9530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9532 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9534 let payer_pubkey = nodes[0].node.get_our_node_id();
9535 let payee_pubkey = nodes[1].node.get_our_node_id();
9536 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9537 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9539 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9540 let route_params = RouteParameters {
9541 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9542 final_value_msat: 10000,
9543 final_cltv_expiry_delta: 40,
9545 let network_graph = nodes[0].network_graph;
9546 let first_hops = nodes[0].node.list_usable_channels();
9547 let scorer = test_utils::TestScorer::with_penalty(0);
9548 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9549 let route = find_route(
9550 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9551 nodes[0].logger, &scorer, &random_seed_bytes
9554 let test_preimage = PaymentPreimage([42; 32]);
9555 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9556 check_added_monitors!(nodes[0], 1);
9557 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9558 assert_eq!(events.len(), 1);
9559 let event = events.pop().unwrap();
9560 let path = vec![&nodes[1]];
9561 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9562 claim_payment(&nodes[0], &path, test_preimage);
9565 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9566 #[derive(Clone, Copy, PartialEq)]
9567 enum ExposureEvent {
9568 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9570 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9572 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9573 AtUpdateFeeOutbound,
9576 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9577 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9580 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9581 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9582 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9583 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9584 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9585 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9586 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9587 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9589 let chanmon_cfgs = create_chanmon_cfgs(2);
9590 let mut config = test_default_channel_config();
9591 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9592 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9593 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9594 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9596 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9597 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9598 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9599 open_channel.max_accepted_htlcs = 60;
9601 open_channel.dust_limit_satoshis = 546;
9603 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9604 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9605 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9607 let opt_anchors = false;
9609 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9612 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9613 chan.holder_dust_limit_satoshis = 546;
9617 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9618 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()));
9619 check_added_monitors!(nodes[1], 1);
9621 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()));
9622 check_added_monitors!(nodes[0], 1);
9624 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9625 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9626 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9628 let dust_buffer_feerate = {
9629 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9630 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9631 chan.get_dust_buffer_feerate(None) as u64
9633 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;
9634 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9636 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;
9637 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9639 let dust_htlc_on_counterparty_tx: u64 = 25;
9640 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9643 if dust_outbound_balance {
9644 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9645 // Outbound dust balance: 4372 sats
9646 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9647 for i in 0..dust_outbound_htlc_on_holder_tx {
9648 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9649 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9652 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9653 // Inbound dust balance: 4372 sats
9654 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9655 for _ in 0..dust_inbound_htlc_on_holder_tx {
9656 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9660 if dust_outbound_balance {
9661 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9662 // Outbound dust balance: 5000 sats
9663 for i in 0..dust_htlc_on_counterparty_tx {
9664 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9665 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9668 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9669 // Inbound dust balance: 5000 sats
9670 for _ in 0..dust_htlc_on_counterparty_tx {
9671 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9676 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9677 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9678 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 });
9679 let mut config = UserConfig::default();
9680 // With default dust exposure: 5000 sats
9682 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9683 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9684 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat)));
9686 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat)));
9688 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9689 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 });
9690 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9691 check_added_monitors!(nodes[1], 1);
9692 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9693 assert_eq!(events.len(), 1);
9694 let payment_event = SendEvent::from_event(events.remove(0));
9695 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9696 // With default dust exposure: 5000 sats
9698 // Outbound dust balance: 6399 sats
9699 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9700 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9701 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat), 1);
9703 // Outbound dust balance: 5200 sats
9704 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat), 1);
9706 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9707 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9708 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9710 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9711 *feerate_lock = *feerate_lock * 10;
9713 nodes[0].node.timer_tick_occurred();
9714 check_added_monitors!(nodes[0], 1);
9715 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);
9718 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9719 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9720 added_monitors.clear();
9724 fn test_max_dust_htlc_exposure() {
9725 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9726 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9727 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9728 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9729 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9730 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9731 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9732 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9733 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9734 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9735 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9736 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);