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;
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::network_graph::RoutingFees;
27 use routing::router::{Payee, Route, RouteHop, RouteHint, RouteHintHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
45 use bitcoin::secp256k1::Secp256k1;
46 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
52 use alloc::collections::BTreeSet;
53 use core::default::Default;
54 use sync::{Arc, Mutex};
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
60 fn test_insane_channel_opens() {
61 // Stand up a network of 2 nodes
62 let chanmon_cfgs = create_chanmon_cfgs(2);
63 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
64 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
65 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67 // Instantiate channel parameters where we push the maximum msats given our
69 let channel_value_sat = 31337; // same as funding satoshis
70 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
71 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73 // Have node0 initiate a channel to node1 with aforementioned parameters
74 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76 // Extract the channel open message from node0 to node1
77 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79 // Test helper that asserts we get the correct error string given a mutator
80 // that supposedly makes the channel open message insane
81 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
82 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
83 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
84 assert_eq!(msg_events.len(), 1);
85 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
86 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88 &ErrorAction::SendErrorMessage { .. } => {
89 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91 _ => panic!("unexpected event!"),
93 } else { assert!(false); }
96 use ln::channel::MAX_FUNDING_SATOSHIS;
97 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99 // Test all mutations that would make the channel open message insane
100 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 });
102 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104 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 });
106 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108 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 });
110 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 });
112 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
114 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
117 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
118 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
119 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
120 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
121 // in normal testing, we test it explicitly here.
122 let chanmon_cfgs = create_chanmon_cfgs(2);
123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
127 // Have node0 initiate a channel to node1 with aforementioned parameters
128 let mut push_amt = 100_000_000;
129 let feerate_per_kw = 253;
130 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + 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));
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_1_conf_open(connect_style: ConnectStyle) {
466 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
467 // tests that we properly send one in that case.
468 let mut alice_config = UserConfig::default();
469 alice_config.own_channel_config.minimum_depth = 1;
470 alice_config.channel_options.announced_channel = true;
471 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
472 let mut bob_config = UserConfig::default();
473 bob_config.own_channel_config.minimum_depth = 1;
474 bob_config.channel_options.announced_channel = true;
475 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
476 let chanmon_cfgs = create_chanmon_cfgs(2);
477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
480 *nodes[0].connect_style.borrow_mut() = connect_style;
482 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
483 mine_transaction(&nodes[1], &tx);
484 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
486 mine_transaction(&nodes[0], &tx);
487 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
488 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
491 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
492 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
493 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
497 fn test_1_conf_open() {
498 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
499 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
500 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
503 fn do_test_sanity_on_in_flight_opens(steps: u8) {
504 // Previously, we had issues deserializing channels when we hadn't connected the first block
505 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
506 // serialization round-trips and simply do steps towards opening a channel and then drop the
509 let chanmon_cfgs = create_chanmon_cfgs(2);
510 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
511 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
512 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
514 if steps & 0b1000_0000 != 0{
516 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
519 connect_block(&nodes[0], &block);
520 connect_block(&nodes[1], &block);
523 if steps & 0x0f == 0 { return; }
524 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
525 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
527 if steps & 0x0f == 1 { return; }
528 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
529 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
531 if steps & 0x0f == 2 { return; }
532 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
534 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
536 if steps & 0x0f == 3 { return; }
537 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
538 check_added_monitors!(nodes[0], 0);
539 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
541 if steps & 0x0f == 4 { return; }
542 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
544 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
545 assert_eq!(added_monitors.len(), 1);
546 assert_eq!(added_monitors[0].0, funding_output);
547 added_monitors.clear();
549 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
551 if steps & 0x0f == 5 { return; }
552 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
554 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
555 assert_eq!(added_monitors.len(), 1);
556 assert_eq!(added_monitors[0].0, funding_output);
557 added_monitors.clear();
560 let events_4 = nodes[0].node.get_and_clear_pending_events();
561 assert_eq!(events_4.len(), 0);
563 if steps & 0x0f == 6 { return; }
564 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
566 if steps & 0x0f == 7 { return; }
567 confirm_transaction_at(&nodes[0], &tx, 2);
568 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
569 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
573 fn test_sanity_on_in_flight_opens() {
574 do_test_sanity_on_in_flight_opens(0);
575 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
576 do_test_sanity_on_in_flight_opens(1);
577 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
578 do_test_sanity_on_in_flight_opens(2);
579 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
580 do_test_sanity_on_in_flight_opens(3);
581 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
582 do_test_sanity_on_in_flight_opens(4);
583 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
584 do_test_sanity_on_in_flight_opens(5);
585 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
586 do_test_sanity_on_in_flight_opens(6);
587 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
588 do_test_sanity_on_in_flight_opens(7);
589 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
590 do_test_sanity_on_in_flight_opens(8);
591 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
595 fn test_update_fee_vanilla() {
596 let chanmon_cfgs = create_chanmon_cfgs(2);
597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
599 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
600 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
603 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
606 nodes[0].node.timer_tick_occurred();
607 check_added_monitors!(nodes[0], 1);
609 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
610 assert_eq!(events_0.len(), 1);
611 let (update_msg, commitment_signed) = match events_0[0] {
612 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 } } => {
613 (update_fee.as_ref(), commitment_signed)
615 _ => panic!("Unexpected event"),
617 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
619 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
620 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
621 check_added_monitors!(nodes[1], 1);
623 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
624 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
625 check_added_monitors!(nodes[0], 1);
627 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
628 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
629 // No commitment_signed so get_event_msg's assert(len == 1) passes
630 check_added_monitors!(nodes[0], 1);
632 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
633 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
634 check_added_monitors!(nodes[1], 1);
638 fn test_update_fee_that_funder_cannot_afford() {
639 let chanmon_cfgs = create_chanmon_cfgs(2);
640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
643 let channel_value = 5000;
645 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
646 let channel_id = chan.2;
647 let secp_ctx = Secp256k1::new();
648 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
650 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652 // calculate two different feerates here - the expected local limit as well as the expected
654 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (COMMITMENT_TX_BASE_WEIGHT + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / COMMITMENT_TX_BASE_WEIGHT) as u32;
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658 *feerate_lock = feerate;
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
662 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
666 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
668 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
670 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
672 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673 assert_eq!(commitment_tx.output.len(), 2);
674 let total_fee: u64 = commit_tx_fee_msat(feerate, 0) / 1000;
675 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676 actual_fee = channel_value - actual_fee;
677 assert_eq!(total_fee, actual_fee);
681 // Increment the feerate by a small constant, accounting for rounding errors
682 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685 nodes[0].node.timer_tick_occurred();
686 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687 check_added_monitors!(nodes[0], 0);
689 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
691 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692 // needed to sign the new commitment tx and (2) sign the new commitment tx.
693 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
695 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
696 let chan_signer = local_chan.get_signer();
697 let pubkeys = chan_signer.pubkeys();
698 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
699 pubkeys.funding_pubkey)
701 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
702 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
703 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
704 let chan_signer = remote_chan.get_signer();
705 let pubkeys = chan_signer.pubkeys();
706 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
707 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
708 pubkeys.funding_pubkey)
711 // Assemble the set of keys we can use for signatures for our commitment_signed message.
712 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
713 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
716 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
717 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
718 let local_chan_signer = local_chan.get_signer();
719 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
720 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
721 INITIAL_COMMITMENT_NUMBER - 1,
723 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0) / 1000,
724 false, local_funding, remote_funding,
725 commit_tx_keys.clone(),
726 non_buffer_feerate + 4,
728 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
730 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
733 let commit_signed_msg = msgs::CommitmentSigned {
736 htlc_signatures: res.1
739 let update_fee = msgs::UpdateFee {
741 feerate_per_kw: non_buffer_feerate + 4,
744 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
746 //While producing the commitment_signed response after handling a received update_fee request the
747 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
748 //Should produce and error.
749 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
750 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
751 check_added_monitors!(nodes[1], 1);
752 check_closed_broadcast!(nodes[1], true);
753 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
757 fn test_update_fee_with_fundee_update_add_htlc() {
758 let chanmon_cfgs = create_chanmon_cfgs(2);
759 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
760 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
761 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
762 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
765 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
768 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
771 nodes[0].node.timer_tick_occurred();
772 check_added_monitors!(nodes[0], 1);
774 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
775 assert_eq!(events_0.len(), 1);
776 let (update_msg, commitment_signed) = match events_0[0] {
777 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 } } => {
778 (update_fee.as_ref(), commitment_signed)
780 _ => panic!("Unexpected event"),
782 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
783 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
785 check_added_monitors!(nodes[1], 1);
787 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
789 // nothing happens since node[1] is in AwaitingRemoteRevoke
790 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
792 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
793 assert_eq!(added_monitors.len(), 0);
794 added_monitors.clear();
796 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
797 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
798 // node[1] has nothing to do
800 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
801 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
802 check_added_monitors!(nodes[0], 1);
804 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
805 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
806 // No commitment_signed so get_event_msg's assert(len == 1) passes
807 check_added_monitors!(nodes[0], 1);
808 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
809 check_added_monitors!(nodes[1], 1);
810 // AwaitingRemoteRevoke ends here
812 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
813 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
814 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
815 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
816 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
817 assert_eq!(commitment_update.update_fee.is_none(), true);
819 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
820 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
821 check_added_monitors!(nodes[0], 1);
822 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
824 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
825 check_added_monitors!(nodes[1], 1);
826 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
828 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
829 check_added_monitors!(nodes[1], 1);
830 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
831 // No commitment_signed so get_event_msg's assert(len == 1) passes
833 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
834 check_added_monitors!(nodes[0], 1);
835 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
837 expect_pending_htlcs_forwardable!(nodes[0]);
839 let events = nodes[0].node.get_and_clear_pending_events();
840 assert_eq!(events.len(), 1);
842 Event::PaymentReceived { .. } => { },
843 _ => panic!("Unexpected event"),
846 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
848 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
849 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
850 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
851 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
852 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
856 fn test_update_fee() {
857 let chanmon_cfgs = create_chanmon_cfgs(2);
858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
861 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
862 let channel_id = chan.2;
865 // (1) update_fee/commitment_signed ->
866 // <- (2) revoke_and_ack
867 // .- send (3) commitment_signed
868 // (4) update_fee/commitment_signed ->
869 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
870 // <- (3) commitment_signed delivered
871 // send (6) revoke_and_ack -.
872 // <- (5) deliver revoke_and_ack
873 // (6) deliver revoke_and_ack ->
874 // .- send (7) commitment_signed in response to (4)
875 // <- (7) deliver commitment_signed
878 // Create and deliver (1)...
881 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
882 feerate = *feerate_lock;
883 *feerate_lock = feerate + 20;
885 nodes[0].node.timer_tick_occurred();
886 check_added_monitors!(nodes[0], 1);
888 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
889 assert_eq!(events_0.len(), 1);
890 let (update_msg, commitment_signed) = match events_0[0] {
891 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 } } => {
892 (update_fee.as_ref(), commitment_signed)
894 _ => panic!("Unexpected event"),
896 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
898 // Generate (2) and (3):
899 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
900 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
901 check_added_monitors!(nodes[1], 1);
904 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
905 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
906 check_added_monitors!(nodes[0], 1);
908 // Create and deliver (4)...
910 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
911 *feerate_lock = feerate + 30;
913 nodes[0].node.timer_tick_occurred();
914 check_added_monitors!(nodes[0], 1);
915 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
916 assert_eq!(events_0.len(), 1);
917 let (update_msg, commitment_signed) = match events_0[0] {
918 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 } } => {
919 (update_fee.as_ref(), commitment_signed)
921 _ => panic!("Unexpected event"),
924 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
925 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
926 check_added_monitors!(nodes[1], 1);
928 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
929 // No commitment_signed so get_event_msg's assert(len == 1) passes
931 // Handle (3), creating (6):
932 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
933 check_added_monitors!(nodes[0], 1);
934 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
938 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
939 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
940 check_added_monitors!(nodes[0], 1);
942 // Deliver (6), creating (7):
943 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
944 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
945 assert!(commitment_update.update_add_htlcs.is_empty());
946 assert!(commitment_update.update_fulfill_htlcs.is_empty());
947 assert!(commitment_update.update_fail_htlcs.is_empty());
948 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
949 assert!(commitment_update.update_fee.is_none());
950 check_added_monitors!(nodes[1], 1);
953 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
954 check_added_monitors!(nodes[0], 1);
955 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
956 // No commitment_signed so get_event_msg's assert(len == 1) passes
958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
959 check_added_monitors!(nodes[1], 1);
960 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
962 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
963 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
964 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
965 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
966 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
970 fn fake_network_test() {
971 // Simple test which builds a network of ChannelManagers, connects them to each other, and
972 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
973 let chanmon_cfgs = create_chanmon_cfgs(4);
974 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
975 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
976 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
978 // Create some initial channels
979 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
980 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
981 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
983 // Rebalance the network a bit by relaying one payment through all the channels...
984 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
985 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
986 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
987 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
989 // Send some more payments
990 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
991 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
992 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
994 // Test failure packets
995 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
996 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
998 // Add a new channel that skips 3
999 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1001 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1002 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1003 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1004 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1005 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1006 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1007 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1009 // Do some rebalance loop payments, simultaneously
1010 let mut hops = Vec::with_capacity(3);
1011 hops.push(RouteHop {
1012 pubkey: nodes[2].node.get_our_node_id(),
1013 node_features: NodeFeatures::empty(),
1014 short_channel_id: chan_2.0.contents.short_channel_id,
1015 channel_features: ChannelFeatures::empty(),
1017 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1019 hops.push(RouteHop {
1020 pubkey: nodes[3].node.get_our_node_id(),
1021 node_features: NodeFeatures::empty(),
1022 short_channel_id: chan_3.0.contents.short_channel_id,
1023 channel_features: ChannelFeatures::empty(),
1025 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1027 hops.push(RouteHop {
1028 pubkey: nodes[1].node.get_our_node_id(),
1029 node_features: NodeFeatures::known(),
1030 short_channel_id: chan_4.0.contents.short_channel_id,
1031 channel_features: ChannelFeatures::known(),
1033 cltv_expiry_delta: TEST_FINAL_CLTV,
1035 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;
1036 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;
1037 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1039 let mut hops = Vec::with_capacity(3);
1040 hops.push(RouteHop {
1041 pubkey: nodes[3].node.get_our_node_id(),
1042 node_features: NodeFeatures::empty(),
1043 short_channel_id: chan_4.0.contents.short_channel_id,
1044 channel_features: ChannelFeatures::empty(),
1046 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1048 hops.push(RouteHop {
1049 pubkey: nodes[2].node.get_our_node_id(),
1050 node_features: NodeFeatures::empty(),
1051 short_channel_id: chan_3.0.contents.short_channel_id,
1052 channel_features: ChannelFeatures::empty(),
1054 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1056 hops.push(RouteHop {
1057 pubkey: nodes[1].node.get_our_node_id(),
1058 node_features: NodeFeatures::known(),
1059 short_channel_id: chan_2.0.contents.short_channel_id,
1060 channel_features: ChannelFeatures::known(),
1062 cltv_expiry_delta: TEST_FINAL_CLTV,
1064 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;
1065 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;
1066 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1068 // Claim the rebalances...
1069 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1070 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1072 // Add a duplicate new channel from 2 to 4
1073 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1075 // Send some payments across both channels
1076 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1077 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1078 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1081 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1082 let events = nodes[0].node.get_and_clear_pending_msg_events();
1083 assert_eq!(events.len(), 0);
1084 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);
1086 //TODO: Test that routes work again here as we've been notified that the channel is full
1088 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1089 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1090 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1092 // Close down the channels...
1093 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1094 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1095 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1097 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1098 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1099 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1100 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1101 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1102 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1103 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1104 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1105 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1106 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1107 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1111 fn holding_cell_htlc_counting() {
1112 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1113 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1114 // commitment dance rounds.
1115 let chanmon_cfgs = create_chanmon_cfgs(3);
1116 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1117 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1118 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1119 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1120 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1122 let mut payments = Vec::new();
1123 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1124 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1125 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1126 payments.push((payment_preimage, payment_hash));
1128 check_added_monitors!(nodes[1], 1);
1130 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1131 assert_eq!(events.len(), 1);
1132 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1133 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1135 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1136 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1138 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1140 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1141 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1142 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1143 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1146 // This should also be true if we try to forward a payment.
1147 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1149 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1150 check_added_monitors!(nodes[0], 1);
1153 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1154 assert_eq!(events.len(), 1);
1155 let payment_event = SendEvent::from_event(events.pop().unwrap());
1156 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1158 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1159 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1160 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1161 // fails), the second will process the resulting failure and fail the HTLC backward.
1162 expect_pending_htlcs_forwardable!(nodes[1]);
1163 expect_pending_htlcs_forwardable!(nodes[1]);
1164 check_added_monitors!(nodes[1], 1);
1166 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1167 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1168 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1170 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1172 // Now forward all the pending HTLCs and claim them back
1173 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1174 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1175 check_added_monitors!(nodes[2], 1);
1177 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1178 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1179 check_added_monitors!(nodes[1], 1);
1180 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1182 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1183 check_added_monitors!(nodes[1], 1);
1184 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1186 for ref update in as_updates.update_add_htlcs.iter() {
1187 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1189 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1190 check_added_monitors!(nodes[2], 1);
1191 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1192 check_added_monitors!(nodes[2], 1);
1193 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1195 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1196 check_added_monitors!(nodes[1], 1);
1197 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1198 check_added_monitors!(nodes[1], 1);
1199 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1201 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1202 check_added_monitors!(nodes[2], 1);
1204 expect_pending_htlcs_forwardable!(nodes[2]);
1206 let events = nodes[2].node.get_and_clear_pending_events();
1207 assert_eq!(events.len(), payments.len());
1208 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1210 &Event::PaymentReceived { ref payment_hash, .. } => {
1211 assert_eq!(*payment_hash, *hash);
1213 _ => panic!("Unexpected event"),
1217 for (preimage, _) in payments.drain(..) {
1218 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1221 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1225 fn duplicate_htlc_test() {
1226 // Test that we accept duplicate payment_hash HTLCs across the network and that
1227 // claiming/failing them are all separate and don't affect each other
1228 let chanmon_cfgs = create_chanmon_cfgs(6);
1229 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1230 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1231 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1233 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1234 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1235 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1236 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1237 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1238 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1240 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1242 *nodes[0].network_payment_count.borrow_mut() -= 1;
1243 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1245 *nodes[0].network_payment_count.borrow_mut() -= 1;
1246 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1248 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1249 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1250 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1254 fn test_duplicate_htlc_different_direction_onchain() {
1255 // Test that ChannelMonitor doesn't generate 2 preimage txn
1256 // when we have 2 HTLCs with same preimage that go across a node
1257 // in opposite directions, even with the same payment secret.
1258 let chanmon_cfgs = create_chanmon_cfgs(2);
1259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1261 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1263 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1266 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1268 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1270 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1271 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1272 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1274 // Provide preimage to node 0 by claiming payment
1275 nodes[0].node.claim_funds(payment_preimage);
1276 check_added_monitors!(nodes[0], 1);
1278 // Broadcast node 1 commitment txn
1279 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1281 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1282 let mut has_both_htlcs = 0; // check htlcs match ones committed
1283 for outp in remote_txn[0].output.iter() {
1284 if outp.value == 800_000 / 1000 {
1285 has_both_htlcs += 1;
1286 } else if outp.value == 900_000 / 1000 {
1287 has_both_htlcs += 1;
1290 assert_eq!(has_both_htlcs, 2);
1292 mine_transaction(&nodes[0], &remote_txn[0]);
1293 check_added_monitors!(nodes[0], 1);
1294 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1295 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1297 // Check we only broadcast 1 timeout tx
1298 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1299 assert_eq!(claim_txn.len(), 8);
1300 assert_eq!(claim_txn[1], claim_txn[4]);
1301 assert_eq!(claim_txn[2], claim_txn[5]);
1302 check_spends!(claim_txn[1], chan_1.3);
1303 check_spends!(claim_txn[2], claim_txn[1]);
1304 check_spends!(claim_txn[7], claim_txn[1]);
1306 assert_eq!(claim_txn[0].input.len(), 1);
1307 assert_eq!(claim_txn[3].input.len(), 1);
1308 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1310 assert_eq!(claim_txn[0].input.len(), 1);
1311 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1312 check_spends!(claim_txn[0], remote_txn[0]);
1313 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1314 assert_eq!(claim_txn[6].input.len(), 1);
1315 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1316 check_spends!(claim_txn[6], remote_txn[0]);
1317 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1319 let events = nodes[0].node.get_and_clear_pending_msg_events();
1320 assert_eq!(events.len(), 3);
1323 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1324 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1325 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1326 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1328 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, .. } } => {
1329 assert!(update_add_htlcs.is_empty());
1330 assert!(update_fail_htlcs.is_empty());
1331 assert_eq!(update_fulfill_htlcs.len(), 1);
1332 assert!(update_fail_malformed_htlcs.is_empty());
1333 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1335 _ => panic!("Unexpected event"),
1341 fn test_basic_channel_reserve() {
1342 let chanmon_cfgs = create_chanmon_cfgs(2);
1343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1345 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1346 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1348 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1349 let channel_reserve = chan_stat.channel_reserve_msat;
1351 // The 2* and +1 are for the fee spike reserve.
1352 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1353 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1354 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1355 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1357 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1359 &APIError::ChannelUnavailable{ref err} =>
1360 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1361 _ => panic!("Unexpected error variant"),
1364 _ => panic!("Unexpected error variant"),
1366 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1367 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);
1369 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1373 fn test_fee_spike_violation_fails_htlc() {
1374 let chanmon_cfgs = create_chanmon_cfgs(2);
1375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1377 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1378 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1380 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1381 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1382 let secp_ctx = Secp256k1::new();
1383 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1385 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1387 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1388 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1389 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1390 let msg = msgs::UpdateAddHTLC {
1393 amount_msat: htlc_msat,
1394 payment_hash: payment_hash,
1395 cltv_expiry: htlc_cltv,
1396 onion_routing_packet: onion_packet,
1399 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1401 // Now manually create the commitment_signed message corresponding to the update_add
1402 // nodes[0] just sent. In the code for construction of this message, "local" refers
1403 // to the sender of the message, and "remote" refers to the receiver.
1405 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1407 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1409 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1410 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1411 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1412 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1413 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1414 let chan_signer = local_chan.get_signer();
1415 // Make the signer believe we validated another commitment, so we can release the secret
1416 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1418 let pubkeys = chan_signer.pubkeys();
1419 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1420 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1421 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1422 chan_signer.pubkeys().funding_pubkey)
1424 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1425 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1426 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1427 let chan_signer = remote_chan.get_signer();
1428 let pubkeys = chan_signer.pubkeys();
1429 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1430 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1431 chan_signer.pubkeys().funding_pubkey)
1434 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1435 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1436 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1438 // Build the remote commitment transaction so we can sign it, and then later use the
1439 // signature for the commitment_signed message.
1440 let local_chan_balance = 1313;
1442 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1444 amount_msat: 3460001,
1445 cltv_expiry: htlc_cltv,
1447 transaction_output_index: Some(1),
1450 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1453 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1454 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1455 let local_chan_signer = local_chan.get_signer();
1456 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1460 false, local_funding, remote_funding,
1461 commit_tx_keys.clone(),
1463 &mut vec![(accepted_htlc_info, ())],
1464 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1466 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1469 let commit_signed_msg = msgs::CommitmentSigned {
1472 htlc_signatures: res.1
1475 // Send the commitment_signed message to the nodes[1].
1476 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1477 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1479 // Send the RAA to nodes[1].
1480 let raa_msg = msgs::RevokeAndACK {
1482 per_commitment_secret: local_secret,
1483 next_per_commitment_point: next_local_point
1485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1487 let events = nodes[1].node.get_and_clear_pending_msg_events();
1488 assert_eq!(events.len(), 1);
1489 // Make sure the HTLC failed in the way we expect.
1491 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492 assert_eq!(update_fail_htlcs.len(), 1);
1493 update_fail_htlcs[0].clone()
1495 _ => panic!("Unexpected event"),
1497 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1500 check_added_monitors!(nodes[1], 2);
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506 // Set the fee rate for the channel very high, to the point where the fundee
1507 // sending any above-dust amount would result in a channel reserve violation.
1508 // In this test we check that we would be prevented from sending an HTLC in
1510 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1515 let mut push_amt = 100_000_000;
1516 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1517 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1519 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1521 // Sending exactly enough to hit the reserve amount should be accepted
1522 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1523 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1526 // However one more HTLC should be significantly over the reserve amount and fail.
1527 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1528 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1529 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1530 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1531 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);
1535 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1536 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1537 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1540 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1542 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1543 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1544 // transaction fee with 0 HTLCs (183 sats)).
1545 let mut push_amt = 100_000_000;
1546 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1547 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1548 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1550 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1551 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1552 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1555 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1556 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1557 let secp_ctx = Secp256k1::new();
1558 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1559 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1560 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1561 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1562 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1563 let msg = msgs::UpdateAddHTLC {
1565 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1566 amount_msat: htlc_msat,
1567 payment_hash: payment_hash,
1568 cltv_expiry: htlc_cltv,
1569 onion_routing_packet: onion_packet,
1572 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1573 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1574 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);
1575 assert_eq!(nodes[0].node.list_channels().len(), 0);
1576 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1577 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1578 check_added_monitors!(nodes[0], 1);
1579 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() });
1583 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1584 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1585 // calculating our commitment transaction fee (this was previously broken).
1586 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1587 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1591 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1593 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1594 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1595 // transaction fee with 0 HTLCs (183 sats)).
1596 let mut push_amt = 100_000_000;
1597 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1598 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1599 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1601 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1602 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1603 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1604 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1605 // commitment transaction fee.
1606 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1608 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1609 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1610 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1613 // One more than the dust amt should fail, however.
1614 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1615 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1616 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1620 fn test_chan_init_feerate_unaffordability() {
1621 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1622 // channel reserve and feerate requirements.
1623 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1624 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1627 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1629 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1631 let mut push_amt = 100_000_000;
1632 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1633 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1634 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1636 // During open, we don't have a "counterparty channel reserve" to check against, so that
1637 // requirement only comes into play on the open_channel handling side.
1638 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1639 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1640 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1641 open_channel_msg.push_msat += 1;
1642 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1644 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1645 assert_eq!(msg_events.len(), 1);
1646 match msg_events[0] {
1647 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1648 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1650 _ => panic!("Unexpected event"),
1655 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1656 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1657 // calculating our counterparty's commitment transaction fee (this was previously broken).
1658 let chanmon_cfgs = create_chanmon_cfgs(2);
1659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1661 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1662 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1664 let payment_amt = 46000; // Dust amount
1665 // In the previous code, these first four payments would succeed.
1666 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1672 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1674 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1678 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1679 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1680 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1681 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1686 let chanmon_cfgs = create_chanmon_cfgs(3);
1687 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1688 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1689 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1690 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1691 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1694 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1695 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1696 let feerate = get_feerate!(nodes[0], chan.2);
1698 // Add a 2* and +1 for the fee spike reserve.
1699 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1700 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;
1701 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1703 // Add a pending HTLC.
1704 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1705 let payment_event_1 = {
1706 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1707 check_added_monitors!(nodes[0], 1);
1709 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1710 assert_eq!(events.len(), 1);
1711 SendEvent::from_event(events.remove(0))
1713 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1715 // Attempt to trigger a channel reserve violation --> payment failure.
1716 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1717 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;
1718 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1719 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1721 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1722 let secp_ctx = Secp256k1::new();
1723 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1724 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1725 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1726 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1727 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1728 let msg = msgs::UpdateAddHTLC {
1731 amount_msat: htlc_msat + 1,
1732 payment_hash: our_payment_hash_1,
1733 cltv_expiry: htlc_cltv,
1734 onion_routing_packet: onion_packet,
1737 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1738 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1739 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1740 assert_eq!(nodes[1].node.list_channels().len(), 1);
1741 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1742 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1743 check_added_monitors!(nodes[1], 1);
1744 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1748 fn test_inbound_outbound_capacity_is_not_zero() {
1749 let chanmon_cfgs = create_chanmon_cfgs(2);
1750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1754 let channels0 = node_chanmgrs[0].list_channels();
1755 let channels1 = node_chanmgrs[1].list_channels();
1756 assert_eq!(channels0.len(), 1);
1757 assert_eq!(channels1.len(), 1);
1759 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1760 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1761 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1763 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1764 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1767 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1768 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1772 fn test_channel_reserve_holding_cell_htlcs() {
1773 let chanmon_cfgs = create_chanmon_cfgs(3);
1774 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1775 // When this test was written, the default base fee floated based on the HTLC count.
1776 // It is now fixed, so we simply set the fee to the expected value here.
1777 let mut config = test_default_channel_config();
1778 config.channel_options.forwarding_fee_base_msat = 239;
1779 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1780 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1781 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1782 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1784 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1785 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1787 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1788 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1790 macro_rules! expect_forward {
1792 let mut events = $node.node.get_and_clear_pending_msg_events();
1793 assert_eq!(events.len(), 1);
1794 check_added_monitors!($node, 1);
1795 let payment_event = SendEvent::from_event(events.remove(0));
1800 let feemsat = 239; // set above
1801 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1802 let feerate = get_feerate!(nodes[0], chan_1.2);
1804 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1806 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1808 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1809 route.paths[0].last_mut().unwrap().fee_msat += 1;
1810 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1811 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1812 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1813 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1814 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1817 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1818 // nodes[0]'s wealth
1820 let amt_msat = recv_value_0 + total_fee_msat;
1821 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1822 // Also, ensure that each payment has enough to be over the dust limit to
1823 // ensure it'll be included in each commit tx fee calculation.
1824 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1825 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1826 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1829 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1831 let (stat01_, stat11_, stat12_, stat22_) = (
1832 get_channel_value_stat!(nodes[0], chan_1.2),
1833 get_channel_value_stat!(nodes[1], chan_1.2),
1834 get_channel_value_stat!(nodes[1], chan_2.2),
1835 get_channel_value_stat!(nodes[2], chan_2.2),
1838 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1839 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1840 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1841 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1842 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1845 // adding pending output.
1846 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1847 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1848 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1849 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1850 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1851 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1852 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1853 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1854 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1856 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1857 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1858 let amt_msat_1 = recv_value_1 + total_fee_msat;
1860 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);
1861 let payment_event_1 = {
1862 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1863 check_added_monitors!(nodes[0], 1);
1865 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1866 assert_eq!(events.len(), 1);
1867 SendEvent::from_event(events.remove(0))
1869 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1871 // channel reserve test with htlc pending output > 0
1872 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1874 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 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());
1880 // split the rest to test holding cell
1881 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1882 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1883 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1884 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1886 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1887 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);
1890 // now see if they go through on both sides
1891 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);
1892 // but this will stuck in the holding cell
1893 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1894 check_added_monitors!(nodes[0], 0);
1895 let events = nodes[0].node.get_and_clear_pending_events();
1896 assert_eq!(events.len(), 0);
1898 // test with outbound holding cell amount > 0
1900 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1901 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1902 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1903 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1904 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);
1907 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);
1908 // this will also stuck in the holding cell
1909 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1910 check_added_monitors!(nodes[0], 0);
1911 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1912 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914 // flush the pending htlc
1915 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1916 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1917 check_added_monitors!(nodes[1], 1);
1919 // the pending htlc should be promoted to committed
1920 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1921 check_added_monitors!(nodes[0], 1);
1922 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1924 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1925 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1926 // No commitment_signed so get_event_msg's assert(len == 1) passes
1927 check_added_monitors!(nodes[0], 1);
1929 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1930 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1931 check_added_monitors!(nodes[1], 1);
1933 expect_pending_htlcs_forwardable!(nodes[1]);
1935 let ref payment_event_11 = expect_forward!(nodes[1]);
1936 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1937 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1939 expect_pending_htlcs_forwardable!(nodes[2]);
1940 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1942 // flush the htlcs in the holding cell
1943 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1945 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1946 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1947 expect_pending_htlcs_forwardable!(nodes[1]);
1949 let ref payment_event_3 = expect_forward!(nodes[1]);
1950 assert_eq!(payment_event_3.msgs.len(), 2);
1951 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1952 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1954 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1955 expect_pending_htlcs_forwardable!(nodes[2]);
1957 let events = nodes[2].node.get_and_clear_pending_events();
1958 assert_eq!(events.len(), 2);
1960 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1961 assert_eq!(our_payment_hash_21, *payment_hash);
1962 assert_eq!(recv_value_21, amt);
1964 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1965 assert!(payment_preimage.is_none());
1966 assert_eq!(our_payment_secret_21, *payment_secret);
1968 _ => panic!("expected PaymentPurpose::InvoicePayment")
1971 _ => panic!("Unexpected event"),
1974 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1975 assert_eq!(our_payment_hash_22, *payment_hash);
1976 assert_eq!(recv_value_22, amt);
1978 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1979 assert!(payment_preimage.is_none());
1980 assert_eq!(our_payment_secret_22, *payment_secret);
1982 _ => panic!("expected PaymentPurpose::InvoicePayment")
1985 _ => panic!("Unexpected event"),
1988 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1989 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1990 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1992 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1993 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1994 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1996 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1997 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);
1998 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1999 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2000 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2002 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2003 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2007 fn channel_reserve_in_flight_removes() {
2008 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2009 // can send to its counterparty, but due to update ordering, the other side may not yet have
2010 // considered those HTLCs fully removed.
2011 // This tests that we don't count HTLCs which will not be included in the next remote
2012 // commitment transaction towards the reserve value (as it implies no commitment transaction
2013 // will be generated which violates the remote reserve value).
2014 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2016 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2017 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2018 // you only consider the value of the first HTLC, it may not),
2019 // * start routing a third HTLC from A to B,
2020 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2021 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2022 // * deliver the first fulfill from B
2023 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2025 // * deliver A's response CS and RAA.
2026 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2027 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2028 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2029 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2030 let chanmon_cfgs = create_chanmon_cfgs(2);
2031 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2032 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2033 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2034 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2036 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2037 // Route the first two HTLCs.
2038 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2039 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2041 // Start routing the third HTLC (this is just used to get everyone in the right state).
2042 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2044 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2045 check_added_monitors!(nodes[0], 1);
2046 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2047 assert_eq!(events.len(), 1);
2048 SendEvent::from_event(events.remove(0))
2051 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2052 // initial fulfill/CS.
2053 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2054 check_added_monitors!(nodes[1], 1);
2055 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2057 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2058 // remove the second HTLC when we send the HTLC back from B to A.
2059 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2060 check_added_monitors!(nodes[1], 1);
2061 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2063 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2064 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2065 check_added_monitors!(nodes[0], 1);
2066 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2067 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2069 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2071 check_added_monitors!(nodes[1], 1);
2072 // B is already AwaitingRAA, so cant generate a CS here
2073 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2076 check_added_monitors!(nodes[1], 1);
2077 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2079 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2080 check_added_monitors!(nodes[0], 1);
2081 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2083 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2084 check_added_monitors!(nodes[1], 1);
2085 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2087 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2088 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2089 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2090 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2091 // on-chain as necessary).
2092 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2093 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2094 check_added_monitors!(nodes[0], 1);
2095 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2096 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2098 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2099 check_added_monitors!(nodes[1], 1);
2100 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2102 expect_pending_htlcs_forwardable!(nodes[1]);
2103 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2105 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2106 // resolve the second HTLC from A's point of view.
2107 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2108 check_added_monitors!(nodes[0], 1);
2109 expect_payment_path_successful!(nodes[0]);
2110 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2112 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2113 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2114 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2116 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2117 check_added_monitors!(nodes[1], 1);
2118 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2119 assert_eq!(events.len(), 1);
2120 SendEvent::from_event(events.remove(0))
2123 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2124 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2125 check_added_monitors!(nodes[0], 1);
2126 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2128 // Now just resolve all the outstanding messages/HTLCs for completeness...
2130 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2131 check_added_monitors!(nodes[1], 1);
2132 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2134 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2135 check_added_monitors!(nodes[1], 1);
2137 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2138 check_added_monitors!(nodes[0], 1);
2139 expect_payment_path_successful!(nodes[0]);
2140 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2142 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2143 check_added_monitors!(nodes[1], 1);
2144 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2146 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2147 check_added_monitors!(nodes[0], 1);
2149 expect_pending_htlcs_forwardable!(nodes[0]);
2150 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2152 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2153 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2157 fn channel_monitor_network_test() {
2158 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2159 // tests that ChannelMonitor is able to recover from various states.
2160 let chanmon_cfgs = create_chanmon_cfgs(5);
2161 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2162 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2163 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2165 // Create some initial channels
2166 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2167 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2168 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2169 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2171 // Make sure all nodes are at the same starting height
2172 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2173 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2174 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2175 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2176 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2178 // Rebalance the network a bit by relaying one payment through all the channels...
2179 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2180 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2184 // Simple case with no pending HTLCs:
2185 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2186 check_added_monitors!(nodes[1], 1);
2187 check_closed_broadcast!(nodes[1], false);
2189 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2190 assert_eq!(node_txn.len(), 1);
2191 mine_transaction(&nodes[0], &node_txn[0]);
2192 check_added_monitors!(nodes[0], 1);
2193 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2195 check_closed_broadcast!(nodes[0], true);
2196 assert_eq!(nodes[0].node.list_channels().len(), 0);
2197 assert_eq!(nodes[1].node.list_channels().len(), 1);
2198 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2199 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2201 // One pending HTLC is discarded by the force-close:
2202 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2204 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2205 // broadcasted until we reach the timelock time).
2206 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2207 check_closed_broadcast!(nodes[1], false);
2208 check_added_monitors!(nodes[1], 1);
2210 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2211 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2212 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2213 mine_transaction(&nodes[2], &node_txn[0]);
2214 check_added_monitors!(nodes[2], 1);
2215 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2217 check_closed_broadcast!(nodes[2], true);
2218 assert_eq!(nodes[1].node.list_channels().len(), 0);
2219 assert_eq!(nodes[2].node.list_channels().len(), 1);
2220 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2221 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2223 macro_rules! claim_funds {
2224 ($node: expr, $prev_node: expr, $preimage: expr) => {
2226 assert!($node.node.claim_funds($preimage));
2227 check_added_monitors!($node, 1);
2229 let events = $node.node.get_and_clear_pending_msg_events();
2230 assert_eq!(events.len(), 1);
2232 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2233 assert!(update_add_htlcs.is_empty());
2234 assert!(update_fail_htlcs.is_empty());
2235 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2237 _ => panic!("Unexpected event"),
2243 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2244 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2245 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2246 check_added_monitors!(nodes[2], 1);
2247 check_closed_broadcast!(nodes[2], false);
2248 let node2_commitment_txid;
2250 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2251 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2252 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2253 node2_commitment_txid = node_txn[0].txid();
2255 // Claim the payment on nodes[3], giving it knowledge of the preimage
2256 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2257 mine_transaction(&nodes[3], &node_txn[0]);
2258 check_added_monitors!(nodes[3], 1);
2259 check_preimage_claim(&nodes[3], &node_txn);
2261 check_closed_broadcast!(nodes[3], true);
2262 assert_eq!(nodes[2].node.list_channels().len(), 0);
2263 assert_eq!(nodes[3].node.list_channels().len(), 1);
2264 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2265 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2267 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2268 // confusing us in the following tests.
2269 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2271 // One pending HTLC to time out:
2272 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2273 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2276 let (close_chan_update_1, close_chan_update_2) = {
2277 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2278 let events = nodes[3].node.get_and_clear_pending_msg_events();
2279 assert_eq!(events.len(), 2);
2280 let close_chan_update_1 = match events[0] {
2281 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2284 _ => panic!("Unexpected event"),
2287 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2288 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2290 _ => panic!("Unexpected event"),
2292 check_added_monitors!(nodes[3], 1);
2294 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2296 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2297 node_txn.retain(|tx| {
2298 if tx.input[0].previous_output.txid == node2_commitment_txid {
2304 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2306 // Claim the payment on nodes[4], giving it knowledge of the preimage
2307 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2309 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2310 let events = nodes[4].node.get_and_clear_pending_msg_events();
2311 assert_eq!(events.len(), 2);
2312 let close_chan_update_2 = match events[0] {
2313 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2316 _ => panic!("Unexpected event"),
2319 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2320 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2322 _ => panic!("Unexpected event"),
2324 check_added_monitors!(nodes[4], 1);
2325 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2327 mine_transaction(&nodes[4], &node_txn[0]);
2328 check_preimage_claim(&nodes[4], &node_txn);
2329 (close_chan_update_1, close_chan_update_2)
2331 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2332 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2333 assert_eq!(nodes[3].node.list_channels().len(), 0);
2334 assert_eq!(nodes[4].node.list_channels().len(), 0);
2336 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2337 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2338 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2342 fn test_justice_tx() {
2343 // Test justice txn built on revoked HTLC-Success tx, against both sides
2344 let mut alice_config = UserConfig::default();
2345 alice_config.channel_options.announced_channel = true;
2346 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2347 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2348 let mut bob_config = UserConfig::default();
2349 bob_config.channel_options.announced_channel = true;
2350 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2351 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2352 let user_cfgs = [Some(alice_config), Some(bob_config)];
2353 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2354 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2355 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2356 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2357 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2358 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2359 // Create some new channels:
2360 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2362 // A pending HTLC which will be revoked:
2363 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2364 // Get the will-be-revoked local txn from nodes[0]
2365 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2366 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2367 assert_eq!(revoked_local_txn[0].input.len(), 1);
2368 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2369 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2370 assert_eq!(revoked_local_txn[1].input.len(), 1);
2371 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2372 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2373 // Revoke the old state
2374 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2377 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2379 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2380 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2381 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2383 check_spends!(node_txn[0], revoked_local_txn[0]);
2384 node_txn.swap_remove(0);
2385 node_txn.truncate(1);
2387 check_added_monitors!(nodes[1], 1);
2388 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2389 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2391 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2392 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2393 // Verify broadcast of revoked HTLC-timeout
2394 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2395 check_added_monitors!(nodes[0], 1);
2396 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2397 // Broadcast revoked HTLC-timeout on node 1
2398 mine_transaction(&nodes[1], &node_txn[1]);
2399 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2401 get_announce_close_broadcast_events(&nodes, 0, 1);
2403 assert_eq!(nodes[0].node.list_channels().len(), 0);
2404 assert_eq!(nodes[1].node.list_channels().len(), 0);
2406 // We test justice_tx build by A on B's revoked HTLC-Success tx
2407 // Create some new channels:
2408 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2410 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2414 // A pending HTLC which will be revoked:
2415 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2416 // Get the will-be-revoked local txn from B
2417 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2418 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2419 assert_eq!(revoked_local_txn[0].input.len(), 1);
2420 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2421 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2422 // Revoke the old state
2423 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2425 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2427 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2428 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2429 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2431 check_spends!(node_txn[0], revoked_local_txn[0]);
2432 node_txn.swap_remove(0);
2434 check_added_monitors!(nodes[0], 1);
2435 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2437 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2438 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2439 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2440 check_added_monitors!(nodes[1], 1);
2441 mine_transaction(&nodes[0], &node_txn[1]);
2442 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2443 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2445 get_announce_close_broadcast_events(&nodes, 0, 1);
2446 assert_eq!(nodes[0].node.list_channels().len(), 0);
2447 assert_eq!(nodes[1].node.list_channels().len(), 0);
2451 fn revoked_output_claim() {
2452 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2453 // transaction is broadcast by its counterparty
2454 let chanmon_cfgs = create_chanmon_cfgs(2);
2455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2457 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2458 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2459 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2460 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2461 assert_eq!(revoked_local_txn.len(), 1);
2462 // Only output is the full channel value back to nodes[0]:
2463 assert_eq!(revoked_local_txn[0].output.len(), 1);
2464 // Send a payment through, updating everyone's latest commitment txn
2465 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2467 // Inform nodes[1] that nodes[0] broadcast a stale tx
2468 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2469 check_added_monitors!(nodes[1], 1);
2470 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2471 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2472 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2474 check_spends!(node_txn[0], revoked_local_txn[0]);
2475 check_spends!(node_txn[1], chan_1.3);
2477 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2478 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2479 get_announce_close_broadcast_events(&nodes, 0, 1);
2480 check_added_monitors!(nodes[0], 1);
2481 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2485 fn claim_htlc_outputs_shared_tx() {
2486 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2487 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2488 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2491 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2493 // Create some new channel:
2494 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2496 // Rebalance the network to generate htlc in the two directions
2497 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2498 // 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
2499 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2500 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2502 // Get the will-be-revoked local txn from node[0]
2503 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2504 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2505 assert_eq!(revoked_local_txn[0].input.len(), 1);
2506 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2507 assert_eq!(revoked_local_txn[1].input.len(), 1);
2508 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2509 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2510 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2512 //Revoke the old state
2513 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2516 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2517 check_added_monitors!(nodes[0], 1);
2518 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2519 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2520 check_added_monitors!(nodes[1], 1);
2521 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2522 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2523 expect_payment_failed!(nodes[1], payment_hash_2, true);
2525 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2526 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2528 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2529 check_spends!(node_txn[0], revoked_local_txn[0]);
2531 let mut witness_lens = BTreeSet::new();
2532 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2533 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2534 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2535 assert_eq!(witness_lens.len(), 3);
2536 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2537 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2538 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2540 // Next nodes[1] broadcasts its current local tx state:
2541 assert_eq!(node_txn[1].input.len(), 1);
2542 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2544 get_announce_close_broadcast_events(&nodes, 0, 1);
2545 assert_eq!(nodes[0].node.list_channels().len(), 0);
2546 assert_eq!(nodes[1].node.list_channels().len(), 0);
2550 fn claim_htlc_outputs_single_tx() {
2551 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2552 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2553 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2554 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2555 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2556 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2558 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2560 // Rebalance the network to generate htlc in the two directions
2561 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2562 // 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
2563 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2564 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2565 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2567 // Get the will-be-revoked local txn from node[0]
2568 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2570 //Revoke the old state
2571 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2574 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2575 check_added_monitors!(nodes[0], 1);
2576 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2577 check_added_monitors!(nodes[1], 1);
2578 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2579 let mut events = nodes[0].node.get_and_clear_pending_events();
2580 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2582 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2583 _ => panic!("Unexpected event"),
2586 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2587 expect_payment_failed!(nodes[1], payment_hash_2, true);
2589 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2590 assert_eq!(node_txn.len(), 9);
2591 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2592 // ChannelManager: local commmitment + local HTLC-timeout (2)
2593 // 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)
2594 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2596 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2597 assert_eq!(node_txn[0].input.len(), 1);
2598 check_spends!(node_txn[0], chan_1.3);
2599 assert_eq!(node_txn[1].input.len(), 1);
2600 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2601 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2602 check_spends!(node_txn[1], node_txn[0]);
2604 // Justice transactions are indices 1-2-4
2605 assert_eq!(node_txn[2].input.len(), 1);
2606 assert_eq!(node_txn[3].input.len(), 1);
2607 assert_eq!(node_txn[4].input.len(), 1);
2609 check_spends!(node_txn[2], revoked_local_txn[0]);
2610 check_spends!(node_txn[3], revoked_local_txn[0]);
2611 check_spends!(node_txn[4], revoked_local_txn[0]);
2613 let mut witness_lens = BTreeSet::new();
2614 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2615 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2616 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2617 assert_eq!(witness_lens.len(), 3);
2618 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2619 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2620 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2622 get_announce_close_broadcast_events(&nodes, 0, 1);
2623 assert_eq!(nodes[0].node.list_channels().len(), 0);
2624 assert_eq!(nodes[1].node.list_channels().len(), 0);
2628 fn test_htlc_on_chain_success() {
2629 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2630 // the preimage backward accordingly. So here we test that ChannelManager is
2631 // broadcasting the right event to other nodes in payment path.
2632 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2633 // A --------------------> B ----------------------> C (preimage)
2634 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2635 // commitment transaction was broadcast.
2636 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2638 // B should be able to claim via preimage if A then broadcasts its local tx.
2639 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2640 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2641 // PaymentSent event).
2643 let chanmon_cfgs = create_chanmon_cfgs(3);
2644 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2645 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2646 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2648 // Create some initial channels
2649 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2650 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2652 // Ensure all nodes are at the same height
2653 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2654 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2655 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2656 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2658 // Rebalance the network a bit by relaying one payment through all the channels...
2659 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2660 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2662 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2663 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2665 // Broadcast legit commitment tx from C on B's chain
2666 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2667 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2668 assert_eq!(commitment_tx.len(), 1);
2669 check_spends!(commitment_tx[0], chan_2.3);
2670 nodes[2].node.claim_funds(our_payment_preimage);
2671 nodes[2].node.claim_funds(our_payment_preimage_2);
2672 check_added_monitors!(nodes[2], 2);
2673 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2674 assert!(updates.update_add_htlcs.is_empty());
2675 assert!(updates.update_fail_htlcs.is_empty());
2676 assert!(updates.update_fail_malformed_htlcs.is_empty());
2677 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2679 mine_transaction(&nodes[2], &commitment_tx[0]);
2680 check_closed_broadcast!(nodes[2], true);
2681 check_added_monitors!(nodes[2], 1);
2682 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2683 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)
2684 assert_eq!(node_txn.len(), 5);
2685 assert_eq!(node_txn[0], node_txn[3]);
2686 assert_eq!(node_txn[1], node_txn[4]);
2687 assert_eq!(node_txn[2], commitment_tx[0]);
2688 check_spends!(node_txn[0], commitment_tx[0]);
2689 check_spends!(node_txn[1], commitment_tx[0]);
2690 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2691 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2692 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2693 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2694 assert_eq!(node_txn[0].lock_time, 0);
2695 assert_eq!(node_txn[1].lock_time, 0);
2697 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2698 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2699 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2700 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2702 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2703 assert_eq!(added_monitors.len(), 1);
2704 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2705 added_monitors.clear();
2707 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2708 assert_eq!(forwarded_events.len(), 3);
2709 match forwarded_events[0] {
2710 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2711 _ => panic!("Unexpected event"),
2713 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2714 } else { panic!(); }
2715 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2716 } else { panic!(); }
2717 let events = nodes[1].node.get_and_clear_pending_msg_events();
2719 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2720 assert_eq!(added_monitors.len(), 2);
2721 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2722 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2723 added_monitors.clear();
2725 assert_eq!(events.len(), 3);
2727 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2728 _ => panic!("Unexpected event"),
2731 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2732 _ => panic!("Unexpected event"),
2736 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, .. } } => {
2737 assert!(update_add_htlcs.is_empty());
2738 assert!(update_fail_htlcs.is_empty());
2739 assert_eq!(update_fulfill_htlcs.len(), 1);
2740 assert!(update_fail_malformed_htlcs.is_empty());
2741 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2743 _ => panic!("Unexpected event"),
2745 macro_rules! check_tx_local_broadcast {
2746 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2747 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2748 assert_eq!(node_txn.len(), 3);
2749 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2750 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2751 check_spends!(node_txn[1], $commitment_tx);
2752 check_spends!(node_txn[2], $commitment_tx);
2753 assert_ne!(node_txn[1].lock_time, 0);
2754 assert_ne!(node_txn[2].lock_time, 0);
2756 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2757 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2758 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2759 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2761 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2762 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2763 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2764 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2766 check_spends!(node_txn[0], $chan_tx);
2767 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2771 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2772 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2773 // timeout-claim of the output that nodes[2] just claimed via success.
2774 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2776 // Broadcast legit commitment tx from A on B's chain
2777 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2778 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2779 check_spends!(node_a_commitment_tx[0], chan_1.3);
2780 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2781 check_closed_broadcast!(nodes[1], true);
2782 check_added_monitors!(nodes[1], 1);
2783 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2784 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2785 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2786 let commitment_spend =
2787 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2788 check_spends!(node_txn[1], commitment_tx[0]);
2789 check_spends!(node_txn[2], commitment_tx[0]);
2790 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2793 check_spends!(node_txn[0], commitment_tx[0]);
2794 check_spends!(node_txn[1], commitment_tx[0]);
2795 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2799 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2800 assert_eq!(commitment_spend.input.len(), 2);
2801 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2802 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2803 assert_eq!(commitment_spend.lock_time, 0);
2804 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2805 check_spends!(node_txn[3], chan_1.3);
2806 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2807 check_spends!(node_txn[4], node_txn[3]);
2808 check_spends!(node_txn[5], node_txn[3]);
2809 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2810 // we already checked the same situation with A.
2812 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2813 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2814 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2815 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2816 check_closed_broadcast!(nodes[0], true);
2817 check_added_monitors!(nodes[0], 1);
2818 let events = nodes[0].node.get_and_clear_pending_events();
2819 assert_eq!(events.len(), 5);
2820 let mut first_claimed = false;
2821 for event in events {
2823 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2824 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2825 assert!(!first_claimed);
2826 first_claimed = true;
2828 assert_eq!(payment_preimage, our_payment_preimage_2);
2829 assert_eq!(payment_hash, payment_hash_2);
2832 Event::PaymentPathSuccessful { .. } => {},
2833 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2834 _ => panic!("Unexpected event"),
2837 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2840 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2841 // Test that in case of a unilateral close onchain, we detect the state of output and
2842 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2843 // broadcasting the right event to other nodes in payment path.
2844 // A ------------------> B ----------------------> C (timeout)
2845 // B's commitment tx C's commitment tx
2847 // B's HTLC timeout tx B's timeout tx
2849 let chanmon_cfgs = create_chanmon_cfgs(3);
2850 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2851 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2852 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2853 *nodes[0].connect_style.borrow_mut() = connect_style;
2854 *nodes[1].connect_style.borrow_mut() = connect_style;
2855 *nodes[2].connect_style.borrow_mut() = connect_style;
2857 // Create some intial channels
2858 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2859 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2861 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2862 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2863 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2865 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2867 // Broadcast legit commitment tx from C on B's chain
2868 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2869 check_spends!(commitment_tx[0], chan_2.3);
2870 nodes[2].node.fail_htlc_backwards(&payment_hash);
2871 check_added_monitors!(nodes[2], 0);
2872 expect_pending_htlcs_forwardable!(nodes[2]);
2873 check_added_monitors!(nodes[2], 1);
2875 let events = nodes[2].node.get_and_clear_pending_msg_events();
2876 assert_eq!(events.len(), 1);
2878 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, .. } } => {
2879 assert!(update_add_htlcs.is_empty());
2880 assert!(!update_fail_htlcs.is_empty());
2881 assert!(update_fulfill_htlcs.is_empty());
2882 assert!(update_fail_malformed_htlcs.is_empty());
2883 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2885 _ => panic!("Unexpected event"),
2887 mine_transaction(&nodes[2], &commitment_tx[0]);
2888 check_closed_broadcast!(nodes[2], true);
2889 check_added_monitors!(nodes[2], 1);
2890 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2891 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2892 assert_eq!(node_txn.len(), 1);
2893 check_spends!(node_txn[0], chan_2.3);
2894 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2896 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2897 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2898 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2899 mine_transaction(&nodes[1], &commitment_tx[0]);
2900 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2903 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2904 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2905 assert_eq!(node_txn[0], node_txn[3]);
2906 assert_eq!(node_txn[1], node_txn[4]);
2908 check_spends!(node_txn[2], commitment_tx[0]);
2909 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2911 check_spends!(node_txn[0], chan_2.3);
2912 check_spends!(node_txn[1], node_txn[0]);
2913 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2914 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2916 timeout_tx = node_txn[2].clone();
2920 mine_transaction(&nodes[1], &timeout_tx);
2921 check_added_monitors!(nodes[1], 1);
2922 check_closed_broadcast!(nodes[1], true);
2924 // B will rebroadcast a fee-bumped timeout transaction here.
2925 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2926 assert_eq!(node_txn.len(), 1);
2927 check_spends!(node_txn[0], commitment_tx[0]);
2930 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2932 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2933 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2934 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2935 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2936 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2937 if node_txn.len() == 1 {
2938 check_spends!(node_txn[0], chan_2.3);
2940 assert_eq!(node_txn.len(), 0);
2944 expect_pending_htlcs_forwardable!(nodes[1]);
2945 check_added_monitors!(nodes[1], 1);
2946 let events = nodes[1].node.get_and_clear_pending_msg_events();
2947 assert_eq!(events.len(), 1);
2949 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, .. } } => {
2950 assert!(update_add_htlcs.is_empty());
2951 assert!(!update_fail_htlcs.is_empty());
2952 assert!(update_fulfill_htlcs.is_empty());
2953 assert!(update_fail_malformed_htlcs.is_empty());
2954 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2956 _ => panic!("Unexpected event"),
2959 // Broadcast legit commitment tx from B on A's chain
2960 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2961 check_spends!(commitment_tx[0], chan_1.3);
2963 mine_transaction(&nodes[0], &commitment_tx[0]);
2964 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2966 check_closed_broadcast!(nodes[0], true);
2967 check_added_monitors!(nodes[0], 1);
2968 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2969 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2970 assert_eq!(node_txn.len(), 2);
2971 check_spends!(node_txn[0], chan_1.3);
2972 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2973 check_spends!(node_txn[1], commitment_tx[0]);
2974 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2978 fn test_htlc_on_chain_timeout() {
2979 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2980 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2981 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2985 fn test_simple_commitment_revoked_fail_backward() {
2986 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2987 // and fail backward accordingly.
2989 let chanmon_cfgs = create_chanmon_cfgs(3);
2990 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2991 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2992 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2994 // Create some initial channels
2995 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2996 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2998 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2999 // Get the will-be-revoked local txn from nodes[2]
3000 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3001 // Revoke the old state
3002 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3004 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3006 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3007 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3008 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3009 check_added_monitors!(nodes[1], 1);
3010 check_closed_broadcast!(nodes[1], true);
3012 expect_pending_htlcs_forwardable!(nodes[1]);
3013 check_added_monitors!(nodes[1], 1);
3014 let events = nodes[1].node.get_and_clear_pending_msg_events();
3015 assert_eq!(events.len(), 1);
3017 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, .. } } => {
3018 assert!(update_add_htlcs.is_empty());
3019 assert_eq!(update_fail_htlcs.len(), 1);
3020 assert!(update_fulfill_htlcs.is_empty());
3021 assert!(update_fail_malformed_htlcs.is_empty());
3022 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3024 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3025 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3026 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3028 _ => panic!("Unexpected event"),
3032 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3033 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3034 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3035 // commitment transaction anymore.
3036 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3037 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3038 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3039 // technically disallowed and we should probably handle it reasonably.
3040 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3041 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3043 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3044 // commitment_signed (implying it will be in the latest remote commitment transaction).
3045 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3046 // and once they revoke the previous commitment transaction (allowing us to send a new
3047 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3048 let chanmon_cfgs = create_chanmon_cfgs(3);
3049 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3050 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3051 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3053 // Create some initial channels
3054 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3055 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3057 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 });
3058 // Get the will-be-revoked local txn from nodes[2]
3059 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3060 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3061 // Revoke the old state
3062 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3064 let value = if use_dust {
3065 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3066 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3067 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3070 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3071 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3072 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3074 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3075 expect_pending_htlcs_forwardable!(nodes[2]);
3076 check_added_monitors!(nodes[2], 1);
3077 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3078 assert!(updates.update_add_htlcs.is_empty());
3079 assert!(updates.update_fulfill_htlcs.is_empty());
3080 assert!(updates.update_fail_malformed_htlcs.is_empty());
3081 assert_eq!(updates.update_fail_htlcs.len(), 1);
3082 assert!(updates.update_fee.is_none());
3083 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3084 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3085 // Drop the last RAA from 3 -> 2
3087 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3088 expect_pending_htlcs_forwardable!(nodes[2]);
3089 check_added_monitors!(nodes[2], 1);
3090 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3091 assert!(updates.update_add_htlcs.is_empty());
3092 assert!(updates.update_fulfill_htlcs.is_empty());
3093 assert!(updates.update_fail_malformed_htlcs.is_empty());
3094 assert_eq!(updates.update_fail_htlcs.len(), 1);
3095 assert!(updates.update_fee.is_none());
3096 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3097 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3098 check_added_monitors!(nodes[1], 1);
3099 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3100 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3101 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3102 check_added_monitors!(nodes[2], 1);
3104 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3105 expect_pending_htlcs_forwardable!(nodes[2]);
3106 check_added_monitors!(nodes[2], 1);
3107 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3108 assert!(updates.update_add_htlcs.is_empty());
3109 assert!(updates.update_fulfill_htlcs.is_empty());
3110 assert!(updates.update_fail_malformed_htlcs.is_empty());
3111 assert_eq!(updates.update_fail_htlcs.len(), 1);
3112 assert!(updates.update_fee.is_none());
3113 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3114 // At this point first_payment_hash has dropped out of the latest two commitment
3115 // transactions that nodes[1] is tracking...
3116 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3117 check_added_monitors!(nodes[1], 1);
3118 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3119 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3120 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3121 check_added_monitors!(nodes[2], 1);
3123 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3124 // on nodes[2]'s RAA.
3125 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3126 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3127 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3128 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3129 check_added_monitors!(nodes[1], 0);
3132 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3133 // One monitor for the new revocation preimage, no second on as we won't generate a new
3134 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3135 check_added_monitors!(nodes[1], 1);
3136 let events = nodes[1].node.get_and_clear_pending_events();
3137 assert_eq!(events.len(), 1);
3139 Event::PendingHTLCsForwardable { .. } => { },
3140 _ => panic!("Unexpected event"),
3142 // Deliberately don't process the pending fail-back so they all fail back at once after
3143 // block connection just like the !deliver_bs_raa case
3146 let mut failed_htlcs = HashSet::new();
3147 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3149 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3150 check_added_monitors!(nodes[1], 1);
3151 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3152 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3154 let events = nodes[1].node.get_and_clear_pending_events();
3155 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3157 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3158 _ => panic!("Unexepected event"),
3161 Event::PaymentPathFailed { ref payment_hash, .. } => {
3162 assert_eq!(*payment_hash, fourth_payment_hash);
3164 _ => panic!("Unexpected event"),
3166 if !deliver_bs_raa {
3168 Event::PaymentFailed { ref payment_hash, .. } => {
3169 assert_eq!(*payment_hash, fourth_payment_hash);
3171 _ => panic!("Unexpected event"),
3174 Event::PendingHTLCsForwardable { .. } => { },
3175 _ => panic!("Unexpected event"),
3178 nodes[1].node.process_pending_htlc_forwards();
3179 check_added_monitors!(nodes[1], 1);
3181 let events = nodes[1].node.get_and_clear_pending_msg_events();
3182 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3183 match events[if deliver_bs_raa { 1 } else { 0 }] {
3184 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3185 _ => panic!("Unexpected event"),
3187 match events[if deliver_bs_raa { 2 } else { 1 }] {
3188 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3189 assert_eq!(channel_id, chan_2.2);
3190 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3192 _ => panic!("Unexpected event"),
3196 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, .. } } => {
3197 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3198 assert_eq!(update_add_htlcs.len(), 1);
3199 assert!(update_fulfill_htlcs.is_empty());
3200 assert!(update_fail_htlcs.is_empty());
3201 assert!(update_fail_malformed_htlcs.is_empty());
3203 _ => panic!("Unexpected event"),
3206 match events[if deliver_bs_raa { 3 } else { 2 }] {
3207 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, .. } } => {
3208 assert!(update_add_htlcs.is_empty());
3209 assert_eq!(update_fail_htlcs.len(), 3);
3210 assert!(update_fulfill_htlcs.is_empty());
3211 assert!(update_fail_malformed_htlcs.is_empty());
3212 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3215 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3216 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3218 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3220 let events = nodes[0].node.get_and_clear_pending_events();
3221 assert_eq!(events.len(), 3);
3223 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3224 assert!(failed_htlcs.insert(payment_hash.0));
3225 // If we delivered B's RAA we got an unknown preimage error, not something
3226 // that we should update our routing table for.
3227 if !deliver_bs_raa {
3228 assert!(network_update.is_some());
3231 _ => panic!("Unexpected event"),
3234 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3235 assert!(failed_htlcs.insert(payment_hash.0));
3236 assert!(network_update.is_some());
3238 _ => panic!("Unexpected event"),
3241 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3242 assert!(failed_htlcs.insert(payment_hash.0));
3243 assert!(network_update.is_some());
3245 _ => panic!("Unexpected event"),
3248 _ => panic!("Unexpected event"),
3251 assert!(failed_htlcs.contains(&first_payment_hash.0));
3252 assert!(failed_htlcs.contains(&second_payment_hash.0));
3253 assert!(failed_htlcs.contains(&third_payment_hash.0));
3257 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3258 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3259 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3260 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3261 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3265 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3266 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3267 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3268 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3269 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3273 fn fail_backward_pending_htlc_upon_channel_failure() {
3274 let chanmon_cfgs = create_chanmon_cfgs(2);
3275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3277 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3278 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3280 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3282 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3283 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3284 check_added_monitors!(nodes[0], 1);
3286 let payment_event = {
3287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3288 assert_eq!(events.len(), 1);
3289 SendEvent::from_event(events.remove(0))
3291 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3292 assert_eq!(payment_event.msgs.len(), 1);
3295 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3296 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3298 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3299 check_added_monitors!(nodes[0], 0);
3301 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3304 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3306 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3308 let secp_ctx = Secp256k1::new();
3309 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3310 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3311 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3312 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3313 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3315 // Send a 0-msat update_add_htlc to fail the channel.
3316 let update_add_htlc = msgs::UpdateAddHTLC {
3322 onion_routing_packet,
3324 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3326 let events = nodes[0].node.get_and_clear_pending_events();
3327 assert_eq!(events.len(), 2);
3328 // Check that Alice fails backward the pending HTLC from the second payment.
3330 Event::PaymentPathFailed { payment_hash, .. } => {
3331 assert_eq!(payment_hash, failed_payment_hash);
3333 _ => panic!("Unexpected event"),
3336 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3337 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3339 _ => panic!("Unexpected event {:?}", events[1]),
3341 check_closed_broadcast!(nodes[0], true);
3342 check_added_monitors!(nodes[0], 1);
3346 fn test_htlc_ignore_latest_remote_commitment() {
3347 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3348 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3349 let chanmon_cfgs = create_chanmon_cfgs(2);
3350 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3351 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3352 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3353 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3355 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3356 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3357 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3358 check_closed_broadcast!(nodes[0], true);
3359 check_added_monitors!(nodes[0], 1);
3360 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3362 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3363 assert_eq!(node_txn.len(), 3);
3364 assert_eq!(node_txn[0], node_txn[1]);
3366 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3367 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3368 check_closed_broadcast!(nodes[1], true);
3369 check_added_monitors!(nodes[1], 1);
3370 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3372 // Duplicate the connect_block call since this may happen due to other listeners
3373 // registering new transactions
3374 header.prev_blockhash = header.block_hash();
3375 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3379 fn test_force_close_fail_back() {
3380 // Check which HTLCs are failed-backwards on channel force-closure
3381 let chanmon_cfgs = create_chanmon_cfgs(3);
3382 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3383 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3384 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3385 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3386 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3388 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3390 let mut payment_event = {
3391 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3392 check_added_monitors!(nodes[0], 1);
3394 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3395 assert_eq!(events.len(), 1);
3396 SendEvent::from_event(events.remove(0))
3399 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3400 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3402 expect_pending_htlcs_forwardable!(nodes[1]);
3404 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3405 assert_eq!(events_2.len(), 1);
3406 payment_event = SendEvent::from_event(events_2.remove(0));
3407 assert_eq!(payment_event.msgs.len(), 1);
3409 check_added_monitors!(nodes[1], 1);
3410 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3411 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3412 check_added_monitors!(nodes[2], 1);
3413 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3415 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3416 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3417 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3419 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3420 check_closed_broadcast!(nodes[2], true);
3421 check_added_monitors!(nodes[2], 1);
3422 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3424 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3425 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3426 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3427 // back to nodes[1] upon timeout otherwise.
3428 assert_eq!(node_txn.len(), 1);
3432 mine_transaction(&nodes[1], &tx);
3434 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3435 check_closed_broadcast!(nodes[1], true);
3436 check_added_monitors!(nodes[1], 1);
3437 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3439 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3441 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3442 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3444 mine_transaction(&nodes[2], &tx);
3445 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3446 assert_eq!(node_txn.len(), 1);
3447 assert_eq!(node_txn[0].input.len(), 1);
3448 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3449 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3450 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3452 check_spends!(node_txn[0], tx);
3456 fn test_dup_events_on_peer_disconnect() {
3457 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3458 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3459 // as we used to generate the event immediately upon receipt of the payment preimage in the
3460 // update_fulfill_htlc message.
3462 let chanmon_cfgs = create_chanmon_cfgs(2);
3463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3466 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3468 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3470 assert!(nodes[1].node.claim_funds(payment_preimage));
3471 check_added_monitors!(nodes[1], 1);
3472 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3473 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3474 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
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);
3479 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3480 expect_payment_path_successful!(nodes[0]);
3484 fn test_simple_peer_disconnect() {
3485 // Test that we can reconnect when there are no lost messages
3486 let chanmon_cfgs = create_chanmon_cfgs(3);
3487 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3488 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3489 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3490 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3491 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3493 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3494 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3495 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3497 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3498 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3499 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3500 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3502 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3503 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3504 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3506 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3507 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3508 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3509 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3511 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3512 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3514 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3515 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3517 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3519 let events = nodes[0].node.get_and_clear_pending_events();
3520 assert_eq!(events.len(), 3);
3522 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3523 assert_eq!(payment_preimage, payment_preimage_3);
3524 assert_eq!(payment_hash, payment_hash_3);
3526 _ => panic!("Unexpected event"),
3529 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3530 assert_eq!(payment_hash, payment_hash_5);
3531 assert!(rejected_by_dest);
3533 _ => panic!("Unexpected event"),
3536 Event::PaymentPathSuccessful { .. } => {},
3537 _ => panic!("Unexpected event"),
3541 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3542 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3545 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3546 // Test that we can reconnect when in-flight HTLC updates get dropped
3547 let chanmon_cfgs = create_chanmon_cfgs(2);
3548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3550 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3552 let mut as_funding_locked = None;
3553 if messages_delivered == 0 {
3554 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3555 as_funding_locked = Some(funding_locked);
3556 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3557 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3558 // it before the channel_reestablish message.
3560 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3563 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3565 let payment_event = {
3566 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3567 check_added_monitors!(nodes[0], 1);
3569 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3570 assert_eq!(events.len(), 1);
3571 SendEvent::from_event(events.remove(0))
3573 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3575 if messages_delivered < 2 {
3576 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3579 if messages_delivered >= 3 {
3580 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3581 check_added_monitors!(nodes[1], 1);
3582 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3584 if messages_delivered >= 4 {
3585 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3586 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3587 check_added_monitors!(nodes[0], 1);
3589 if messages_delivered >= 5 {
3590 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3591 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3592 // No commitment_signed so get_event_msg's assert(len == 1) passes
3593 check_added_monitors!(nodes[0], 1);
3595 if messages_delivered >= 6 {
3596 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3597 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3598 check_added_monitors!(nodes[1], 1);
3605 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3606 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3607 if messages_delivered < 3 {
3608 if simulate_broken_lnd {
3609 // lnd has a long-standing bug where they send a funding_locked prior to a
3610 // channel_reestablish if you reconnect prior to funding_locked time.
3612 // Here we simulate that behavior, delivering a funding_locked immediately on
3613 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3614 // in `reconnect_nodes` but we currently don't fail based on that.
3616 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3617 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3619 // Even if the funding_locked messages get exchanged, as long as nothing further was
3620 // received on either side, both sides will need to resend them.
3621 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3622 } else if messages_delivered == 3 {
3623 // nodes[0] still wants its RAA + commitment_signed
3624 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3625 } else if messages_delivered == 4 {
3626 // nodes[0] still wants its commitment_signed
3627 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3628 } else if messages_delivered == 5 {
3629 // nodes[1] still wants its final RAA
3630 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3631 } else if messages_delivered == 6 {
3632 // Everything was delivered...
3633 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3636 let events_1 = nodes[1].node.get_and_clear_pending_events();
3637 assert_eq!(events_1.len(), 1);
3639 Event::PendingHTLCsForwardable { .. } => { },
3640 _ => panic!("Unexpected event"),
3643 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3644 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3645 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3647 nodes[1].node.process_pending_htlc_forwards();
3649 let events_2 = nodes[1].node.get_and_clear_pending_events();
3650 assert_eq!(events_2.len(), 1);
3652 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3653 assert_eq!(payment_hash_1, *payment_hash);
3654 assert_eq!(amt, 1000000);
3656 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3657 assert!(payment_preimage.is_none());
3658 assert_eq!(payment_secret_1, *payment_secret);
3660 _ => panic!("expected PaymentPurpose::InvoicePayment")
3663 _ => panic!("Unexpected event"),
3666 nodes[1].node.claim_funds(payment_preimage_1);
3667 check_added_monitors!(nodes[1], 1);
3669 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3670 assert_eq!(events_3.len(), 1);
3671 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3672 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3673 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3674 assert!(updates.update_add_htlcs.is_empty());
3675 assert!(updates.update_fail_htlcs.is_empty());
3676 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3677 assert!(updates.update_fail_malformed_htlcs.is_empty());
3678 assert!(updates.update_fee.is_none());
3679 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3681 _ => panic!("Unexpected event"),
3684 if messages_delivered >= 1 {
3685 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3687 let events_4 = nodes[0].node.get_and_clear_pending_events();
3688 assert_eq!(events_4.len(), 1);
3690 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3691 assert_eq!(payment_preimage_1, *payment_preimage);
3692 assert_eq!(payment_hash_1, *payment_hash);
3694 _ => panic!("Unexpected event"),
3697 if messages_delivered >= 2 {
3698 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3699 check_added_monitors!(nodes[0], 1);
3700 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3702 if messages_delivered >= 3 {
3703 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3704 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3705 check_added_monitors!(nodes[1], 1);
3707 if messages_delivered >= 4 {
3708 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3709 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3710 // No commitment_signed so get_event_msg's assert(len == 1) passes
3711 check_added_monitors!(nodes[1], 1);
3713 if messages_delivered >= 5 {
3714 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3715 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3716 check_added_monitors!(nodes[0], 1);
3723 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3724 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3725 if messages_delivered < 2 {
3726 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3727 if messages_delivered < 1 {
3728 expect_payment_sent!(nodes[0], payment_preimage_1);
3730 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3732 } else if messages_delivered == 2 {
3733 // nodes[0] still wants its RAA + commitment_signed
3734 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3735 } else if messages_delivered == 3 {
3736 // nodes[0] still wants its commitment_signed
3737 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3738 } else if messages_delivered == 4 {
3739 // nodes[1] still wants its final RAA
3740 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3741 } else if messages_delivered == 5 {
3742 // Everything was delivered...
3743 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3746 if messages_delivered == 1 || messages_delivered == 2 {
3747 expect_payment_path_successful!(nodes[0]);
3750 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3751 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3752 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3754 if messages_delivered > 2 {
3755 expect_payment_path_successful!(nodes[0]);
3758 // Channel should still work fine...
3759 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3760 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3761 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3765 fn test_drop_messages_peer_disconnect_a() {
3766 do_test_drop_messages_peer_disconnect(0, true);
3767 do_test_drop_messages_peer_disconnect(0, false);
3768 do_test_drop_messages_peer_disconnect(1, false);
3769 do_test_drop_messages_peer_disconnect(2, false);
3773 fn test_drop_messages_peer_disconnect_b() {
3774 do_test_drop_messages_peer_disconnect(3, false);
3775 do_test_drop_messages_peer_disconnect(4, false);
3776 do_test_drop_messages_peer_disconnect(5, false);
3777 do_test_drop_messages_peer_disconnect(6, false);
3781 fn test_funding_peer_disconnect() {
3782 // Test that we can lock in our funding tx while disconnected
3783 let chanmon_cfgs = create_chanmon_cfgs(2);
3784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3786 let persister: test_utils::TestPersister;
3787 let new_chain_monitor: test_utils::TestChainMonitor;
3788 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3789 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3790 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3792 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3793 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3795 confirm_transaction(&nodes[0], &tx);
3796 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3797 assert!(events_1.is_empty());
3799 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3801 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3802 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3804 confirm_transaction(&nodes[1], &tx);
3805 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3806 assert!(events_2.is_empty());
3808 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3809 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3810 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3811 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3813 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3814 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3815 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3816 assert_eq!(events_3.len(), 1);
3817 let as_funding_locked = match events_3[0] {
3818 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3819 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3822 _ => panic!("Unexpected event {:?}", events_3[0]),
3825 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3826 // announcement_signatures as well as channel_update.
3827 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3828 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3829 assert_eq!(events_4.len(), 3);
3831 let bs_funding_locked = match events_4[0] {
3832 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3833 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3834 chan_id = msg.channel_id;
3837 _ => panic!("Unexpected event {:?}", events_4[0]),
3839 let bs_announcement_sigs = match events_4[1] {
3840 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3841 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3844 _ => panic!("Unexpected event {:?}", events_4[1]),
3847 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3848 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3850 _ => panic!("Unexpected event {:?}", events_4[2]),
3853 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3854 // generates a duplicative announcement_signatures
3855 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3856 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3857 assert_eq!(events_5.len(), 1);
3859 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3860 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3861 assert_eq!(*msg, bs_announcement_sigs);
3863 _ => panic!("Unexpected event {:?}", events_5[0]),
3866 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3867 // announcement_signatures.
3868 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3869 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3870 assert_eq!(events_6.len(), 1);
3871 let as_announcement_sigs = match events_6[0] {
3872 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3873 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3876 _ => panic!("Unexpected event {:?}", events_6[0]),
3879 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3880 // broadcast the channel announcement globally, as well as re-send its (now-public)
3882 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3883 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3884 assert_eq!(events_7.len(), 1);
3885 let (chan_announcement, as_update) = match events_7[0] {
3886 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3887 (msg.clone(), update_msg.clone())
3889 _ => panic!("Unexpected event {:?}", events_7[0]),
3892 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3893 // same channel_announcement.
3894 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3895 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3896 assert_eq!(events_8.len(), 1);
3897 let bs_update = match events_8[0] {
3898 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3899 assert_eq!(*msg, chan_announcement);
3902 _ => panic!("Unexpected event {:?}", events_8[0]),
3905 // Provide the channel announcement and public updates to the network graph
3906 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3907 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3908 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3910 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3911 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3912 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3914 // Check that after deserialization and reconnection we can still generate an identical
3915 // channel_announcement from the cached signatures.
3916 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3918 let nodes_0_serialized = nodes[0].node.encode();
3919 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3920 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3922 persister = test_utils::TestPersister::new();
3923 let keys_manager = &chanmon_cfgs[0].keys_manager;
3924 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);
3925 nodes[0].chain_monitor = &new_chain_monitor;
3926 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3927 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3928 &mut chan_0_monitor_read, keys_manager).unwrap();
3929 assert!(chan_0_monitor_read.is_empty());
3931 let mut nodes_0_read = &nodes_0_serialized[..];
3932 let (_, nodes_0_deserialized_tmp) = {
3933 let mut channel_monitors = HashMap::new();
3934 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3935 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3936 default_config: UserConfig::default(),
3938 fee_estimator: node_cfgs[0].fee_estimator,
3939 chain_monitor: nodes[0].chain_monitor,
3940 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3941 logger: nodes[0].logger,
3945 nodes_0_deserialized = nodes_0_deserialized_tmp;
3946 assert!(nodes_0_read.is_empty());
3948 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3949 nodes[0].node = &nodes_0_deserialized;
3950 check_added_monitors!(nodes[0], 1);
3952 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3954 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3955 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3956 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3957 let mut found_announcement = false;
3958 for event in msgs.iter() {
3960 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3961 if *msg == chan_announcement { found_announcement = true; }
3963 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3964 _ => panic!("Unexpected event"),
3967 assert!(found_announcement);
3971 fn test_drop_messages_peer_disconnect_dual_htlc() {
3972 // Test that we can handle reconnecting when both sides of a channel have pending
3973 // commitment_updates when we disconnect.
3974 let chanmon_cfgs = create_chanmon_cfgs(2);
3975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3977 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3978 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3980 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3982 // Now try to send a second payment which will fail to send
3983 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3984 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3985 check_added_monitors!(nodes[0], 1);
3987 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3988 assert_eq!(events_1.len(), 1);
3990 MessageSendEvent::UpdateHTLCs { .. } => {},
3991 _ => panic!("Unexpected event"),
3994 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3995 check_added_monitors!(nodes[1], 1);
3997 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3998 assert_eq!(events_2.len(), 1);
4000 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 } } => {
4001 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4002 assert!(update_add_htlcs.is_empty());
4003 assert_eq!(update_fulfill_htlcs.len(), 1);
4004 assert!(update_fail_htlcs.is_empty());
4005 assert!(update_fail_malformed_htlcs.is_empty());
4006 assert!(update_fee.is_none());
4008 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4009 let events_3 = nodes[0].node.get_and_clear_pending_events();
4010 assert_eq!(events_3.len(), 1);
4012 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4013 assert_eq!(*payment_preimage, payment_preimage_1);
4014 assert_eq!(*payment_hash, payment_hash_1);
4016 _ => panic!("Unexpected event"),
4019 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4020 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4021 // No commitment_signed so get_event_msg's assert(len == 1) passes
4022 check_added_monitors!(nodes[0], 1);
4024 _ => panic!("Unexpected event"),
4027 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4030 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4031 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4032 assert_eq!(reestablish_1.len(), 1);
4033 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4034 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4035 assert_eq!(reestablish_2.len(), 1);
4037 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4038 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4039 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4040 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4042 assert!(as_resp.0.is_none());
4043 assert!(bs_resp.0.is_none());
4045 assert!(bs_resp.1.is_none());
4046 assert!(bs_resp.2.is_none());
4048 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4050 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4051 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4052 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4053 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4054 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4055 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4056 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4057 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4058 // No commitment_signed so get_event_msg's assert(len == 1) passes
4059 check_added_monitors!(nodes[1], 1);
4061 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4062 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4063 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4064 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4065 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4066 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4067 assert!(bs_second_commitment_signed.update_fee.is_none());
4068 check_added_monitors!(nodes[1], 1);
4070 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4071 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4072 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4073 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4074 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4075 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4076 assert!(as_commitment_signed.update_fee.is_none());
4077 check_added_monitors!(nodes[0], 1);
4079 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4080 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4081 // No commitment_signed so get_event_msg's assert(len == 1) passes
4082 check_added_monitors!(nodes[0], 1);
4084 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4085 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4086 // No commitment_signed so get_event_msg's assert(len == 1) passes
4087 check_added_monitors!(nodes[1], 1);
4089 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4090 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4091 check_added_monitors!(nodes[1], 1);
4093 expect_pending_htlcs_forwardable!(nodes[1]);
4095 let events_5 = nodes[1].node.get_and_clear_pending_events();
4096 assert_eq!(events_5.len(), 1);
4098 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4099 assert_eq!(payment_hash_2, *payment_hash);
4101 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4102 assert!(payment_preimage.is_none());
4103 assert_eq!(payment_secret_2, *payment_secret);
4105 _ => panic!("expected PaymentPurpose::InvoicePayment")
4108 _ => panic!("Unexpected event"),
4111 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4112 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4113 check_added_monitors!(nodes[0], 1);
4115 expect_payment_path_successful!(nodes[0]);
4116 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4119 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4120 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4121 // to avoid our counterparty failing the channel.
4122 let chanmon_cfgs = create_chanmon_cfgs(2);
4123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4127 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4129 let our_payment_hash = if send_partial_mpp {
4130 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4131 // Use the utility function send_payment_along_path to send the payment with MPP data which
4132 // indicates there are more HTLCs coming.
4133 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.
4134 let payment_id = PaymentId([42; 32]);
4135 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payee, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4136 check_added_monitors!(nodes[0], 1);
4137 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4138 assert_eq!(events.len(), 1);
4139 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4140 // hop should *not* yet generate any PaymentReceived event(s).
4141 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4144 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4147 let mut block = Block {
4148 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4151 connect_block(&nodes[0], &block);
4152 connect_block(&nodes[1], &block);
4153 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4154 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4155 block.header.prev_blockhash = block.block_hash();
4156 connect_block(&nodes[0], &block);
4157 connect_block(&nodes[1], &block);
4160 expect_pending_htlcs_forwardable!(nodes[1]);
4162 check_added_monitors!(nodes[1], 1);
4163 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4164 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4165 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4166 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4167 assert!(htlc_timeout_updates.update_fee.is_none());
4169 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4170 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4171 // 100_000 msat as u64, followed by the height at which we failed back above
4172 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4173 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4174 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4178 fn test_htlc_timeout() {
4179 do_test_htlc_timeout(true);
4180 do_test_htlc_timeout(false);
4183 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4184 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4185 let chanmon_cfgs = create_chanmon_cfgs(3);
4186 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4187 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4188 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4189 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4190 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4192 // Make sure all nodes are at the same starting height
4193 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4194 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4195 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4197 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4198 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4200 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4202 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4203 check_added_monitors!(nodes[1], 1);
4205 // Now attempt to route a second payment, which should be placed in the holding cell
4206 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4207 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4208 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4210 check_added_monitors!(nodes[0], 1);
4211 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4212 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4213 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4214 expect_pending_htlcs_forwardable!(nodes[1]);
4216 check_added_monitors!(nodes[1], 0);
4218 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4219 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4220 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4221 connect_blocks(&nodes[1], 1);
4224 expect_pending_htlcs_forwardable!(nodes[1]);
4225 check_added_monitors!(nodes[1], 1);
4226 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4227 assert_eq!(fail_commit.len(), 1);
4228 match fail_commit[0] {
4229 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4230 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4231 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4233 _ => unreachable!(),
4235 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4237 let events = nodes[1].node.get_and_clear_pending_events();
4238 assert_eq!(events.len(), 2);
4239 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4240 assert_eq!(*payment_hash, second_payment_hash);
4241 } else { panic!("Unexpected event"); }
4242 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4243 assert_eq!(*payment_hash, second_payment_hash);
4244 } else { panic!("Unexpected event"); }
4249 fn test_holding_cell_htlc_add_timeouts() {
4250 do_test_holding_cell_htlc_add_timeouts(false);
4251 do_test_holding_cell_htlc_add_timeouts(true);
4255 fn test_no_txn_manager_serialize_deserialize() {
4256 let chanmon_cfgs = create_chanmon_cfgs(2);
4257 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4258 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4259 let logger: test_utils::TestLogger;
4260 let fee_estimator: test_utils::TestFeeEstimator;
4261 let persister: test_utils::TestPersister;
4262 let new_chain_monitor: test_utils::TestChainMonitor;
4263 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4264 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4266 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4268 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4270 let nodes_0_serialized = nodes[0].node.encode();
4271 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4272 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4273 .write(&mut chan_0_monitor_serialized).unwrap();
4275 logger = test_utils::TestLogger::new();
4276 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4277 persister = test_utils::TestPersister::new();
4278 let keys_manager = &chanmon_cfgs[0].keys_manager;
4279 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4280 nodes[0].chain_monitor = &new_chain_monitor;
4281 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4282 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4283 &mut chan_0_monitor_read, keys_manager).unwrap();
4284 assert!(chan_0_monitor_read.is_empty());
4286 let mut nodes_0_read = &nodes_0_serialized[..];
4287 let config = UserConfig::default();
4288 let (_, nodes_0_deserialized_tmp) = {
4289 let mut channel_monitors = HashMap::new();
4290 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4291 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4292 default_config: config,
4294 fee_estimator: &fee_estimator,
4295 chain_monitor: nodes[0].chain_monitor,
4296 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4301 nodes_0_deserialized = nodes_0_deserialized_tmp;
4302 assert!(nodes_0_read.is_empty());
4304 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4305 nodes[0].node = &nodes_0_deserialized;
4306 assert_eq!(nodes[0].node.list_channels().len(), 1);
4307 check_added_monitors!(nodes[0], 1);
4309 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4310 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4311 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4312 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4314 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4315 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4316 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4317 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4319 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4320 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4321 for node in nodes.iter() {
4322 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4323 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4324 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4327 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4331 fn test_manager_serialize_deserialize_events() {
4332 // This test makes sure the events field in ChannelManager survives de/serialization
4333 let chanmon_cfgs = create_chanmon_cfgs(2);
4334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4336 let fee_estimator: test_utils::TestFeeEstimator;
4337 let persister: test_utils::TestPersister;
4338 let logger: test_utils::TestLogger;
4339 let new_chain_monitor: test_utils::TestChainMonitor;
4340 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4343 // Start creating a channel, but stop right before broadcasting the funding transaction
4344 let channel_value = 100000;
4345 let push_msat = 10001;
4346 let a_flags = InitFeatures::known();
4347 let b_flags = InitFeatures::known();
4348 let node_a = nodes.remove(0);
4349 let node_b = nodes.remove(0);
4350 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4351 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()));
4352 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()));
4354 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4356 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4357 check_added_monitors!(node_a, 0);
4359 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()));
4361 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4362 assert_eq!(added_monitors.len(), 1);
4363 assert_eq!(added_monitors[0].0, funding_output);
4364 added_monitors.clear();
4367 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4368 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4370 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4371 assert_eq!(added_monitors.len(), 1);
4372 assert_eq!(added_monitors[0].0, funding_output);
4373 added_monitors.clear();
4375 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4380 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4381 let nodes_0_serialized = nodes[0].node.encode();
4382 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4383 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4385 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4386 logger = test_utils::TestLogger::new();
4387 persister = test_utils::TestPersister::new();
4388 let keys_manager = &chanmon_cfgs[0].keys_manager;
4389 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4390 nodes[0].chain_monitor = &new_chain_monitor;
4391 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4392 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4393 &mut chan_0_monitor_read, keys_manager).unwrap();
4394 assert!(chan_0_monitor_read.is_empty());
4396 let mut nodes_0_read = &nodes_0_serialized[..];
4397 let config = UserConfig::default();
4398 let (_, nodes_0_deserialized_tmp) = {
4399 let mut channel_monitors = HashMap::new();
4400 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4401 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4402 default_config: config,
4404 fee_estimator: &fee_estimator,
4405 chain_monitor: nodes[0].chain_monitor,
4406 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4411 nodes_0_deserialized = nodes_0_deserialized_tmp;
4412 assert!(nodes_0_read.is_empty());
4414 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4416 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4417 nodes[0].node = &nodes_0_deserialized;
4419 // After deserializing, make sure the funding_transaction is still held by the channel manager
4420 let events_4 = nodes[0].node.get_and_clear_pending_events();
4421 assert_eq!(events_4.len(), 0);
4422 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4423 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4425 // Make sure the channel is functioning as though the de/serialization never happened
4426 assert_eq!(nodes[0].node.list_channels().len(), 1);
4427 check_added_monitors!(nodes[0], 1);
4429 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4430 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4431 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4432 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4434 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4435 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4436 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4437 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4439 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4440 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4441 for node in nodes.iter() {
4442 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4443 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4444 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4447 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4451 fn test_simple_manager_serialize_deserialize() {
4452 let chanmon_cfgs = create_chanmon_cfgs(2);
4453 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4454 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4455 let logger: test_utils::TestLogger;
4456 let fee_estimator: test_utils::TestFeeEstimator;
4457 let persister: test_utils::TestPersister;
4458 let new_chain_monitor: test_utils::TestChainMonitor;
4459 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4460 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4461 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4463 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4464 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4466 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4468 let nodes_0_serialized = nodes[0].node.encode();
4469 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4470 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4472 logger = test_utils::TestLogger::new();
4473 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4474 persister = test_utils::TestPersister::new();
4475 let keys_manager = &chanmon_cfgs[0].keys_manager;
4476 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4477 nodes[0].chain_monitor = &new_chain_monitor;
4478 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4479 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4480 &mut chan_0_monitor_read, keys_manager).unwrap();
4481 assert!(chan_0_monitor_read.is_empty());
4483 let mut nodes_0_read = &nodes_0_serialized[..];
4484 let (_, nodes_0_deserialized_tmp) = {
4485 let mut channel_monitors = HashMap::new();
4486 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4487 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4488 default_config: UserConfig::default(),
4490 fee_estimator: &fee_estimator,
4491 chain_monitor: nodes[0].chain_monitor,
4492 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4497 nodes_0_deserialized = nodes_0_deserialized_tmp;
4498 assert!(nodes_0_read.is_empty());
4500 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4501 nodes[0].node = &nodes_0_deserialized;
4502 check_added_monitors!(nodes[0], 1);
4504 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4506 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4507 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4511 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4512 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4513 let chanmon_cfgs = create_chanmon_cfgs(4);
4514 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4515 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4516 let logger: test_utils::TestLogger;
4517 let fee_estimator: test_utils::TestFeeEstimator;
4518 let persister: test_utils::TestPersister;
4519 let new_chain_monitor: test_utils::TestChainMonitor;
4520 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4521 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4522 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4523 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4524 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4526 let mut node_0_stale_monitors_serialized = Vec::new();
4527 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4528 let mut writer = test_utils::TestVecWriter(Vec::new());
4529 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4530 node_0_stale_monitors_serialized.push(writer.0);
4533 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4535 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4536 let nodes_0_serialized = nodes[0].node.encode();
4538 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4539 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4540 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4541 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4543 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4545 let mut node_0_monitors_serialized = Vec::new();
4546 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4547 let mut writer = test_utils::TestVecWriter(Vec::new());
4548 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4549 node_0_monitors_serialized.push(writer.0);
4552 logger = test_utils::TestLogger::new();
4553 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4554 persister = test_utils::TestPersister::new();
4555 let keys_manager = &chanmon_cfgs[0].keys_manager;
4556 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4557 nodes[0].chain_monitor = &new_chain_monitor;
4560 let mut node_0_stale_monitors = Vec::new();
4561 for serialized in node_0_stale_monitors_serialized.iter() {
4562 let mut read = &serialized[..];
4563 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4564 assert!(read.is_empty());
4565 node_0_stale_monitors.push(monitor);
4568 let mut node_0_monitors = Vec::new();
4569 for serialized in node_0_monitors_serialized.iter() {
4570 let mut read = &serialized[..];
4571 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4572 assert!(read.is_empty());
4573 node_0_monitors.push(monitor);
4576 let mut nodes_0_read = &nodes_0_serialized[..];
4577 if let Err(msgs::DecodeError::InvalidValue) =
4578 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4579 default_config: UserConfig::default(),
4581 fee_estimator: &fee_estimator,
4582 chain_monitor: nodes[0].chain_monitor,
4583 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4585 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4587 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4590 let mut nodes_0_read = &nodes_0_serialized[..];
4591 let (_, nodes_0_deserialized_tmp) =
4592 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4593 default_config: UserConfig::default(),
4595 fee_estimator: &fee_estimator,
4596 chain_monitor: nodes[0].chain_monitor,
4597 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4599 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4601 nodes_0_deserialized = nodes_0_deserialized_tmp;
4602 assert!(nodes_0_read.is_empty());
4604 { // Channel close should result in a commitment tx
4605 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4606 assert_eq!(txn.len(), 1);
4607 check_spends!(txn[0], funding_tx);
4608 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4611 for monitor in node_0_monitors.drain(..) {
4612 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4613 check_added_monitors!(nodes[0], 1);
4615 nodes[0].node = &nodes_0_deserialized;
4616 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4618 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4619 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4620 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4621 //... and we can even still claim the payment!
4622 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4624 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4625 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4626 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4627 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4628 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4629 assert_eq!(msg_events.len(), 1);
4630 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4632 &ErrorAction::SendErrorMessage { ref msg } => {
4633 assert_eq!(msg.channel_id, channel_id);
4635 _ => panic!("Unexpected event!"),
4640 macro_rules! check_spendable_outputs {
4641 ($node: expr, $keysinterface: expr) => {
4643 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4644 let mut txn = Vec::new();
4645 let mut all_outputs = Vec::new();
4646 let secp_ctx = Secp256k1::new();
4647 for event in events.drain(..) {
4649 Event::SpendableOutputs { mut outputs } => {
4650 for outp in outputs.drain(..) {
4651 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4652 all_outputs.push(outp);
4655 _ => panic!("Unexpected event"),
4658 if all_outputs.len() > 1 {
4659 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) {
4669 fn test_claim_sizeable_push_msat() {
4670 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4671 let chanmon_cfgs = create_chanmon_cfgs(2);
4672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4674 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4676 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4677 nodes[1].node.force_close_channel(&chan.2).unwrap();
4678 check_closed_broadcast!(nodes[1], true);
4679 check_added_monitors!(nodes[1], 1);
4680 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4681 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4682 assert_eq!(node_txn.len(), 1);
4683 check_spends!(node_txn[0], chan.3);
4684 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
4686 mine_transaction(&nodes[1], &node_txn[0]);
4687 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4689 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4690 assert_eq!(spend_txn.len(), 1);
4691 assert_eq!(spend_txn[0].input.len(), 1);
4692 check_spends!(spend_txn[0], node_txn[0]);
4693 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4697 fn test_claim_on_remote_sizeable_push_msat() {
4698 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4699 // to_remote output is encumbered by a P2WPKH
4700 let chanmon_cfgs = create_chanmon_cfgs(2);
4701 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4702 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4703 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4705 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4706 nodes[0].node.force_close_channel(&chan.2).unwrap();
4707 check_closed_broadcast!(nodes[0], true);
4708 check_added_monitors!(nodes[0], 1);
4709 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4711 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4712 assert_eq!(node_txn.len(), 1);
4713 check_spends!(node_txn[0], chan.3);
4714 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
4716 mine_transaction(&nodes[1], &node_txn[0]);
4717 check_closed_broadcast!(nodes[1], true);
4718 check_added_monitors!(nodes[1], 1);
4719 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4720 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4722 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4723 assert_eq!(spend_txn.len(), 1);
4724 check_spends!(spend_txn[0], node_txn[0]);
4728 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4729 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4730 // to_remote output is encumbered by a P2WPKH
4732 let chanmon_cfgs = create_chanmon_cfgs(2);
4733 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4734 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4735 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4737 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4738 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4739 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4740 assert_eq!(revoked_local_txn[0].input.len(), 1);
4741 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4743 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4744 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4745 check_closed_broadcast!(nodes[1], true);
4746 check_added_monitors!(nodes[1], 1);
4747 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4749 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4750 mine_transaction(&nodes[1], &node_txn[0]);
4751 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4753 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4754 assert_eq!(spend_txn.len(), 3);
4755 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4756 check_spends!(spend_txn[1], node_txn[0]);
4757 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4761 fn test_static_spendable_outputs_preimage_tx() {
4762 let chanmon_cfgs = create_chanmon_cfgs(2);
4763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4765 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4767 // Create some initial channels
4768 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4770 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4772 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4773 assert_eq!(commitment_tx[0].input.len(), 1);
4774 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4776 // Settle A's commitment tx on B's chain
4777 assert!(nodes[1].node.claim_funds(payment_preimage));
4778 check_added_monitors!(nodes[1], 1);
4779 mine_transaction(&nodes[1], &commitment_tx[0]);
4780 check_added_monitors!(nodes[1], 1);
4781 let events = nodes[1].node.get_and_clear_pending_msg_events();
4783 MessageSendEvent::UpdateHTLCs { .. } => {},
4784 _ => panic!("Unexpected event"),
4787 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4788 _ => panic!("Unexepected event"),
4791 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4792 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4793 assert_eq!(node_txn.len(), 3);
4794 check_spends!(node_txn[0], commitment_tx[0]);
4795 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4796 check_spends!(node_txn[1], chan_1.3);
4797 check_spends!(node_txn[2], node_txn[1]);
4799 mine_transaction(&nodes[1], &node_txn[0]);
4800 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4801 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4803 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4804 assert_eq!(spend_txn.len(), 1);
4805 check_spends!(spend_txn[0], node_txn[0]);
4809 fn test_static_spendable_outputs_timeout_tx() {
4810 let chanmon_cfgs = create_chanmon_cfgs(2);
4811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4813 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4815 // Create some initial channels
4816 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4818 // Rebalance the network a bit by relaying one payment through all the channels ...
4819 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4821 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4823 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4824 assert_eq!(commitment_tx[0].input.len(), 1);
4825 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4827 // Settle A's commitment tx on B' chain
4828 mine_transaction(&nodes[1], &commitment_tx[0]);
4829 check_added_monitors!(nodes[1], 1);
4830 let events = nodes[1].node.get_and_clear_pending_msg_events();
4832 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4833 _ => panic!("Unexpected event"),
4835 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4837 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4838 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4839 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4840 check_spends!(node_txn[0], chan_1.3.clone());
4841 check_spends!(node_txn[1], commitment_tx[0].clone());
4842 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4844 mine_transaction(&nodes[1], &node_txn[1]);
4845 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4846 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4847 expect_payment_failed!(nodes[1], our_payment_hash, true);
4849 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4850 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4851 check_spends!(spend_txn[0], commitment_tx[0]);
4852 check_spends!(spend_txn[1], node_txn[1]);
4853 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4857 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4858 let chanmon_cfgs = create_chanmon_cfgs(2);
4859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4863 // Create some initial channels
4864 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4866 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4867 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4868 assert_eq!(revoked_local_txn[0].input.len(), 1);
4869 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4871 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4873 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4874 check_closed_broadcast!(nodes[1], true);
4875 check_added_monitors!(nodes[1], 1);
4876 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4878 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4879 assert_eq!(node_txn.len(), 2);
4880 assert_eq!(node_txn[0].input.len(), 2);
4881 check_spends!(node_txn[0], revoked_local_txn[0]);
4883 mine_transaction(&nodes[1], &node_txn[0]);
4884 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4886 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4887 assert_eq!(spend_txn.len(), 1);
4888 check_spends!(spend_txn[0], node_txn[0]);
4892 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4893 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4894 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4899 // Create some initial channels
4900 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4902 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4903 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4904 assert_eq!(revoked_local_txn[0].input.len(), 1);
4905 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4907 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4909 // A will generate HTLC-Timeout from revoked commitment tx
4910 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4911 check_closed_broadcast!(nodes[0], true);
4912 check_added_monitors!(nodes[0], 1);
4913 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4914 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4916 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4917 assert_eq!(revoked_htlc_txn.len(), 2);
4918 check_spends!(revoked_htlc_txn[0], chan_1.3);
4919 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4920 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4921 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4922 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4924 // B will generate justice tx from A's revoked commitment/HTLC tx
4925 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4926 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4927 check_closed_broadcast!(nodes[1], true);
4928 check_added_monitors!(nodes[1], 1);
4929 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4931 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4932 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4933 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4934 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4935 // transactions next...
4936 assert_eq!(node_txn[0].input.len(), 3);
4937 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4939 assert_eq!(node_txn[1].input.len(), 2);
4940 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4941 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4942 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4944 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4945 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4948 assert_eq!(node_txn[2].input.len(), 1);
4949 check_spends!(node_txn[2], chan_1.3);
4951 mine_transaction(&nodes[1], &node_txn[1]);
4952 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4954 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4955 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4956 assert_eq!(spend_txn.len(), 1);
4957 assert_eq!(spend_txn[0].input.len(), 1);
4958 check_spends!(spend_txn[0], node_txn[1]);
4962 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4963 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4964 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4967 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4969 // Create some initial channels
4970 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4972 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4973 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4974 assert_eq!(revoked_local_txn[0].input.len(), 1);
4975 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4977 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4978 assert_eq!(revoked_local_txn[0].output.len(), 2);
4980 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4982 // B will generate HTLC-Success from revoked commitment tx
4983 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4984 check_closed_broadcast!(nodes[1], true);
4985 check_added_monitors!(nodes[1], 1);
4986 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4987 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4989 assert_eq!(revoked_htlc_txn.len(), 2);
4990 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4991 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4992 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4994 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4995 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4996 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4998 // A will generate justice tx from B's revoked commitment/HTLC tx
4999 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5000 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5001 check_closed_broadcast!(nodes[0], true);
5002 check_added_monitors!(nodes[0], 1);
5003 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5005 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5006 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5008 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5009 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5010 // transactions next...
5011 assert_eq!(node_txn[0].input.len(), 2);
5012 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5013 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5014 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5016 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5017 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5020 assert_eq!(node_txn[1].input.len(), 1);
5021 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5023 check_spends!(node_txn[2], chan_1.3);
5025 mine_transaction(&nodes[0], &node_txn[1]);
5026 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5028 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5029 // didn't try to generate any new transactions.
5031 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5032 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5033 assert_eq!(spend_txn.len(), 3);
5034 assert_eq!(spend_txn[0].input.len(), 1);
5035 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5036 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5037 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5038 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5042 fn test_onchain_to_onchain_claim() {
5043 // Test that in case of channel closure, we detect the state of output and claim HTLC
5044 // on downstream peer's remote commitment tx.
5045 // First, have C claim an HTLC against its own latest commitment transaction.
5046 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5048 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5051 let chanmon_cfgs = create_chanmon_cfgs(3);
5052 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5053 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5054 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5056 // Create some initial channels
5057 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5058 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5060 // Ensure all nodes are at the same height
5061 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5062 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5063 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5064 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5066 // Rebalance the network a bit by relaying one payment through all the channels ...
5067 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5068 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5070 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5071 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5072 check_spends!(commitment_tx[0], chan_2.3);
5073 nodes[2].node.claim_funds(payment_preimage);
5074 check_added_monitors!(nodes[2], 1);
5075 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5076 assert!(updates.update_add_htlcs.is_empty());
5077 assert!(updates.update_fail_htlcs.is_empty());
5078 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5079 assert!(updates.update_fail_malformed_htlcs.is_empty());
5081 mine_transaction(&nodes[2], &commitment_tx[0]);
5082 check_closed_broadcast!(nodes[2], true);
5083 check_added_monitors!(nodes[2], 1);
5084 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5086 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5087 assert_eq!(c_txn.len(), 3);
5088 assert_eq!(c_txn[0], c_txn[2]);
5089 assert_eq!(commitment_tx[0], c_txn[1]);
5090 check_spends!(c_txn[1], chan_2.3);
5091 check_spends!(c_txn[2], c_txn[1]);
5092 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5093 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5094 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5095 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5097 // 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
5098 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5099 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5100 check_added_monitors!(nodes[1], 1);
5101 let events = nodes[1].node.get_and_clear_pending_events();
5102 assert_eq!(events.len(), 2);
5104 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5105 _ => panic!("Unexpected event"),
5108 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5109 assert_eq!(fee_earned_msat, Some(1000));
5110 assert_eq!(claim_from_onchain_tx, true);
5112 _ => panic!("Unexpected event"),
5115 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5116 // ChannelMonitor: claim tx
5117 assert_eq!(b_txn.len(), 1);
5118 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5121 check_added_monitors!(nodes[1], 1);
5122 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5123 assert_eq!(msg_events.len(), 3);
5124 match msg_events[0] {
5125 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5126 _ => panic!("Unexpected event"),
5128 match msg_events[1] {
5129 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5130 _ => panic!("Unexpected event"),
5132 match msg_events[2] {
5133 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, .. } } => {
5134 assert!(update_add_htlcs.is_empty());
5135 assert!(update_fail_htlcs.is_empty());
5136 assert_eq!(update_fulfill_htlcs.len(), 1);
5137 assert!(update_fail_malformed_htlcs.is_empty());
5138 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5140 _ => panic!("Unexpected event"),
5142 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5143 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5144 mine_transaction(&nodes[1], &commitment_tx[0]);
5145 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5146 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5147 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5148 assert_eq!(b_txn.len(), 3);
5149 check_spends!(b_txn[1], chan_1.3);
5150 check_spends!(b_txn[2], b_txn[1]);
5151 check_spends!(b_txn[0], commitment_tx[0]);
5152 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5153 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5154 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5156 check_closed_broadcast!(nodes[1], true);
5157 check_added_monitors!(nodes[1], 1);
5161 fn test_duplicate_payment_hash_one_failure_one_success() {
5162 // Topology : A --> B --> C --> D
5163 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5164 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5165 // we forward one of the payments onwards to D.
5166 let chanmon_cfgs = create_chanmon_cfgs(4);
5167 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5168 // When this test was written, the default base fee floated based on the HTLC count.
5169 // It is now fixed, so we simply set the fee to the expected value here.
5170 let mut config = test_default_channel_config();
5171 config.channel_options.forwarding_fee_base_msat = 196;
5172 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5173 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5174 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5176 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5177 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5178 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5180 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5181 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5182 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5183 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5184 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5186 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5188 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5189 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5190 // script push size limit so that the below script length checks match
5191 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5192 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5193 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5195 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5196 assert_eq!(commitment_txn[0].input.len(), 1);
5197 check_spends!(commitment_txn[0], chan_2.3);
5199 mine_transaction(&nodes[1], &commitment_txn[0]);
5200 check_closed_broadcast!(nodes[1], true);
5201 check_added_monitors!(nodes[1], 1);
5202 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5203 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5205 let htlc_timeout_tx;
5206 { // Extract one of the two HTLC-Timeout transaction
5207 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5208 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5209 assert_eq!(node_txn.len(), 4);
5210 check_spends!(node_txn[0], chan_2.3);
5212 check_spends!(node_txn[1], commitment_txn[0]);
5213 assert_eq!(node_txn[1].input.len(), 1);
5214 check_spends!(node_txn[2], commitment_txn[0]);
5215 assert_eq!(node_txn[2].input.len(), 1);
5216 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5217 check_spends!(node_txn[3], commitment_txn[0]);
5218 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5220 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5221 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5222 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5223 htlc_timeout_tx = node_txn[1].clone();
5226 nodes[2].node.claim_funds(our_payment_preimage);
5227 mine_transaction(&nodes[2], &commitment_txn[0]);
5228 check_added_monitors!(nodes[2], 2);
5229 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5230 let events = nodes[2].node.get_and_clear_pending_msg_events();
5232 MessageSendEvent::UpdateHTLCs { .. } => {},
5233 _ => panic!("Unexpected event"),
5236 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5237 _ => panic!("Unexepected event"),
5239 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5240 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)
5241 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5242 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5243 assert_eq!(htlc_success_txn[0].input.len(), 1);
5244 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5245 assert_eq!(htlc_success_txn[1].input.len(), 1);
5246 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5247 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5248 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5249 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5250 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5251 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5253 mine_transaction(&nodes[1], &htlc_timeout_tx);
5254 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5255 expect_pending_htlcs_forwardable!(nodes[1]);
5256 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5257 assert!(htlc_updates.update_add_htlcs.is_empty());
5258 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5259 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5260 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5261 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5262 check_added_monitors!(nodes[1], 1);
5264 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5265 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5267 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5269 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5271 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5272 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5273 // and nodes[2] fee) is rounded down and then claimed in full.
5274 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5275 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5276 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5277 assert!(updates.update_add_htlcs.is_empty());
5278 assert!(updates.update_fail_htlcs.is_empty());
5279 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5280 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5281 assert!(updates.update_fail_malformed_htlcs.is_empty());
5282 check_added_monitors!(nodes[1], 1);
5284 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5285 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5287 let events = nodes[0].node.get_and_clear_pending_events();
5289 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5290 assert_eq!(*payment_preimage, our_payment_preimage);
5291 assert_eq!(*payment_hash, duplicate_payment_hash);
5293 _ => panic!("Unexpected event"),
5298 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5299 let chanmon_cfgs = create_chanmon_cfgs(2);
5300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5302 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5304 // Create some initial channels
5305 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5307 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5308 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5309 assert_eq!(local_txn.len(), 1);
5310 assert_eq!(local_txn[0].input.len(), 1);
5311 check_spends!(local_txn[0], chan_1.3);
5313 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5314 nodes[1].node.claim_funds(payment_preimage);
5315 check_added_monitors!(nodes[1], 1);
5316 mine_transaction(&nodes[1], &local_txn[0]);
5317 check_added_monitors!(nodes[1], 1);
5318 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5319 let events = nodes[1].node.get_and_clear_pending_msg_events();
5321 MessageSendEvent::UpdateHTLCs { .. } => {},
5322 _ => panic!("Unexpected event"),
5325 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5326 _ => panic!("Unexepected event"),
5329 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5330 assert_eq!(node_txn.len(), 3);
5331 assert_eq!(node_txn[0], node_txn[2]);
5332 assert_eq!(node_txn[1], local_txn[0]);
5333 assert_eq!(node_txn[0].input.len(), 1);
5334 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5335 check_spends!(node_txn[0], local_txn[0]);
5339 mine_transaction(&nodes[1], &node_tx);
5340 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5342 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5343 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5344 assert_eq!(spend_txn.len(), 1);
5345 assert_eq!(spend_txn[0].input.len(), 1);
5346 check_spends!(spend_txn[0], node_tx);
5347 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5350 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5351 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5352 // unrevoked commitment transaction.
5353 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5354 // a remote RAA before they could be failed backwards (and combinations thereof).
5355 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5356 // use the same payment hashes.
5357 // Thus, we use a six-node network:
5362 // And test where C fails back to A/B when D announces its latest commitment transaction
5363 let chanmon_cfgs = create_chanmon_cfgs(6);
5364 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5365 // When this test was written, the default base fee floated based on the HTLC count.
5366 // It is now fixed, so we simply set the fee to the expected value here.
5367 let mut config = test_default_channel_config();
5368 config.channel_options.forwarding_fee_base_msat = 196;
5369 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5370 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5371 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5373 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5374 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5375 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5376 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5377 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5379 // Rebalance and check output sanity...
5380 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5381 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5382 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5384 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5386 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
5388 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
5389 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5391 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
5393 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
5395 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5397 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5398 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5400 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());
5402 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());
5405 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5407 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5408 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
5411 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
5413 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5414 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());
5416 // Double-check that six of the new HTLC were added
5417 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5418 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5419 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5420 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5422 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5423 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5424 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5425 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5426 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5427 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5428 check_added_monitors!(nodes[4], 0);
5429 expect_pending_htlcs_forwardable!(nodes[4]);
5430 check_added_monitors!(nodes[4], 1);
5432 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5433 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5434 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5435 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5436 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5437 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5439 // Fail 3rd below-dust and 7th above-dust HTLCs
5440 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5441 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5442 check_added_monitors!(nodes[5], 0);
5443 expect_pending_htlcs_forwardable!(nodes[5]);
5444 check_added_monitors!(nodes[5], 1);
5446 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5447 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5448 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5449 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5451 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5453 expect_pending_htlcs_forwardable!(nodes[3]);
5454 check_added_monitors!(nodes[3], 1);
5455 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5456 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5457 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5458 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5459 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5460 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5461 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5462 if deliver_last_raa {
5463 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5465 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5468 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5469 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5470 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5471 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5473 // We now broadcast the latest commitment transaction, which *should* result in failures for
5474 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5475 // the non-broadcast above-dust HTLCs.
5477 // Alternatively, we may broadcast the previous commitment transaction, which should only
5478 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5479 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5481 if announce_latest {
5482 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5484 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5486 let events = nodes[2].node.get_and_clear_pending_events();
5487 let close_event = if deliver_last_raa {
5488 assert_eq!(events.len(), 2);
5491 assert_eq!(events.len(), 1);
5495 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5496 _ => panic!("Unexpected event"),
5499 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5500 check_closed_broadcast!(nodes[2], true);
5501 if deliver_last_raa {
5502 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5504 expect_pending_htlcs_forwardable!(nodes[2]);
5506 check_added_monitors!(nodes[2], 3);
5508 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5509 assert_eq!(cs_msgs.len(), 2);
5510 let mut a_done = false;
5511 for msg in cs_msgs {
5513 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5514 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5515 // should be failed-backwards here.
5516 let target = if *node_id == nodes[0].node.get_our_node_id() {
5517 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5518 for htlc in &updates.update_fail_htlcs {
5519 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 });
5521 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5526 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5527 for htlc in &updates.update_fail_htlcs {
5528 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5530 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5531 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5534 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5535 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5536 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5537 if announce_latest {
5538 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5539 if *node_id == nodes[0].node.get_our_node_id() {
5540 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5543 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5545 _ => panic!("Unexpected event"),
5549 let as_events = nodes[0].node.get_and_clear_pending_events();
5550 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5551 let mut as_failds = HashSet::new();
5552 let mut as_updates = 0;
5553 for event in as_events.iter() {
5554 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5555 assert!(as_failds.insert(*payment_hash));
5556 if *payment_hash != payment_hash_2 {
5557 assert_eq!(*rejected_by_dest, deliver_last_raa);
5559 assert!(!rejected_by_dest);
5561 if network_update.is_some() {
5564 } else { panic!("Unexpected event"); }
5566 assert!(as_failds.contains(&payment_hash_1));
5567 assert!(as_failds.contains(&payment_hash_2));
5568 if announce_latest {
5569 assert!(as_failds.contains(&payment_hash_3));
5570 assert!(as_failds.contains(&payment_hash_5));
5572 assert!(as_failds.contains(&payment_hash_6));
5574 let bs_events = nodes[1].node.get_and_clear_pending_events();
5575 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5576 let mut bs_failds = HashSet::new();
5577 let mut bs_updates = 0;
5578 for event in bs_events.iter() {
5579 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5580 assert!(bs_failds.insert(*payment_hash));
5581 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5582 assert_eq!(*rejected_by_dest, deliver_last_raa);
5584 assert!(!rejected_by_dest);
5586 if network_update.is_some() {
5589 } else { panic!("Unexpected event"); }
5591 assert!(bs_failds.contains(&payment_hash_1));
5592 assert!(bs_failds.contains(&payment_hash_2));
5593 if announce_latest {
5594 assert!(bs_failds.contains(&payment_hash_4));
5596 assert!(bs_failds.contains(&payment_hash_5));
5598 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5599 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5600 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5601 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5602 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5603 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5607 fn test_fail_backwards_latest_remote_announce_a() {
5608 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5612 fn test_fail_backwards_latest_remote_announce_b() {
5613 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5617 fn test_fail_backwards_previous_remote_announce() {
5618 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5619 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5620 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5624 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5625 let chanmon_cfgs = create_chanmon_cfgs(2);
5626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5630 // Create some initial channels
5631 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5633 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5634 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5635 assert_eq!(local_txn[0].input.len(), 1);
5636 check_spends!(local_txn[0], chan_1.3);
5638 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5639 mine_transaction(&nodes[0], &local_txn[0]);
5640 check_closed_broadcast!(nodes[0], true);
5641 check_added_monitors!(nodes[0], 1);
5642 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5643 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5645 let htlc_timeout = {
5646 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5647 assert_eq!(node_txn.len(), 2);
5648 check_spends!(node_txn[0], chan_1.3);
5649 assert_eq!(node_txn[1].input.len(), 1);
5650 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5651 check_spends!(node_txn[1], local_txn[0]);
5655 mine_transaction(&nodes[0], &htlc_timeout);
5656 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5657 expect_payment_failed!(nodes[0], our_payment_hash, true);
5659 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5660 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5661 assert_eq!(spend_txn.len(), 3);
5662 check_spends!(spend_txn[0], local_txn[0]);
5663 assert_eq!(spend_txn[1].input.len(), 1);
5664 check_spends!(spend_txn[1], htlc_timeout);
5665 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5666 assert_eq!(spend_txn[2].input.len(), 2);
5667 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5668 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5669 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5673 fn test_key_derivation_params() {
5674 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5675 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5676 // let us re-derive the channel key set to then derive a delayed_payment_key.
5678 let chanmon_cfgs = create_chanmon_cfgs(3);
5680 // We manually create the node configuration to backup the seed.
5681 let seed = [42; 32];
5682 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5683 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);
5684 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() };
5685 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5686 node_cfgs.remove(0);
5687 node_cfgs.insert(0, node);
5689 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5690 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5692 // Create some initial channels
5693 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5695 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5696 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5697 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5699 // Ensure all nodes are at the same height
5700 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5701 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5702 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5703 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5705 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5706 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5707 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5708 assert_eq!(local_txn_1[0].input.len(), 1);
5709 check_spends!(local_txn_1[0], chan_1.3);
5711 // We check funding pubkey are unique
5712 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]));
5713 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]));
5714 if from_0_funding_key_0 == from_1_funding_key_0
5715 || from_0_funding_key_0 == from_1_funding_key_1
5716 || from_0_funding_key_1 == from_1_funding_key_0
5717 || from_0_funding_key_1 == from_1_funding_key_1 {
5718 panic!("Funding pubkeys aren't unique");
5721 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5722 mine_transaction(&nodes[0], &local_txn_1[0]);
5723 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5724 check_closed_broadcast!(nodes[0], true);
5725 check_added_monitors!(nodes[0], 1);
5726 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5728 let htlc_timeout = {
5729 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5730 assert_eq!(node_txn[1].input.len(), 1);
5731 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5732 check_spends!(node_txn[1], local_txn_1[0]);
5736 mine_transaction(&nodes[0], &htlc_timeout);
5737 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5738 expect_payment_failed!(nodes[0], our_payment_hash, true);
5740 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5741 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5742 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5743 assert_eq!(spend_txn.len(), 3);
5744 check_spends!(spend_txn[0], local_txn_1[0]);
5745 assert_eq!(spend_txn[1].input.len(), 1);
5746 check_spends!(spend_txn[1], htlc_timeout);
5747 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5748 assert_eq!(spend_txn[2].input.len(), 2);
5749 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5750 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5751 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5755 fn test_static_output_closing_tx() {
5756 let chanmon_cfgs = create_chanmon_cfgs(2);
5757 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5758 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5759 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5761 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5763 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5764 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5766 mine_transaction(&nodes[0], &closing_tx);
5767 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5768 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5770 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5771 assert_eq!(spend_txn.len(), 1);
5772 check_spends!(spend_txn[0], closing_tx);
5774 mine_transaction(&nodes[1], &closing_tx);
5775 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5776 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5778 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5779 assert_eq!(spend_txn.len(), 1);
5780 check_spends!(spend_txn[0], closing_tx);
5783 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5784 let chanmon_cfgs = create_chanmon_cfgs(2);
5785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5788 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5790 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5792 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5793 // present in B's local commitment transaction, but none of A's commitment transactions.
5794 assert!(nodes[1].node.claim_funds(payment_preimage));
5795 check_added_monitors!(nodes[1], 1);
5797 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5798 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5799 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5801 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5802 check_added_monitors!(nodes[0], 1);
5803 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5804 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5805 check_added_monitors!(nodes[1], 1);
5807 let starting_block = nodes[1].best_block_info();
5808 let mut block = Block {
5809 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5812 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5813 connect_block(&nodes[1], &block);
5814 block.header.prev_blockhash = block.block_hash();
5816 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5817 check_closed_broadcast!(nodes[1], true);
5818 check_added_monitors!(nodes[1], 1);
5819 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5822 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5823 let chanmon_cfgs = create_chanmon_cfgs(2);
5824 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5825 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5826 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5827 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5829 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5830 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5831 check_added_monitors!(nodes[0], 1);
5833 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5835 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5836 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5837 // to "time out" the HTLC.
5839 let starting_block = nodes[1].best_block_info();
5840 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5842 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5843 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5844 header.prev_blockhash = header.block_hash();
5846 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5847 check_closed_broadcast!(nodes[0], true);
5848 check_added_monitors!(nodes[0], 1);
5849 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5852 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5853 let chanmon_cfgs = create_chanmon_cfgs(3);
5854 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5855 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5856 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5857 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5859 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5860 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5861 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5862 // actually revoked.
5863 let htlc_value = if use_dust { 50000 } else { 3000000 };
5864 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5865 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5866 expect_pending_htlcs_forwardable!(nodes[1]);
5867 check_added_monitors!(nodes[1], 1);
5869 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5870 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5871 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5872 check_added_monitors!(nodes[0], 1);
5873 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5874 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5875 check_added_monitors!(nodes[1], 1);
5876 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5877 check_added_monitors!(nodes[1], 1);
5878 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5880 if check_revoke_no_close {
5881 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5882 check_added_monitors!(nodes[0], 1);
5885 let starting_block = nodes[1].best_block_info();
5886 let mut block = Block {
5887 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5890 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5891 connect_block(&nodes[0], &block);
5892 block.header.prev_blockhash = block.block_hash();
5894 if !check_revoke_no_close {
5895 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5896 check_closed_broadcast!(nodes[0], true);
5897 check_added_monitors!(nodes[0], 1);
5898 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5900 let events = nodes[0].node.get_and_clear_pending_events();
5901 assert_eq!(events.len(), 2);
5902 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5903 assert_eq!(*payment_hash, our_payment_hash);
5904 } else { panic!("Unexpected event"); }
5905 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5906 assert_eq!(*payment_hash, our_payment_hash);
5907 } else { panic!("Unexpected event"); }
5911 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5912 // There are only a few cases to test here:
5913 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5914 // broadcastable commitment transactions result in channel closure,
5915 // * its included in an unrevoked-but-previous remote commitment transaction,
5916 // * its included in the latest remote or local commitment transactions.
5917 // We test each of the three possible commitment transactions individually and use both dust and
5919 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5920 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5921 // tested for at least one of the cases in other tests.
5923 fn htlc_claim_single_commitment_only_a() {
5924 do_htlc_claim_local_commitment_only(true);
5925 do_htlc_claim_local_commitment_only(false);
5927 do_htlc_claim_current_remote_commitment_only(true);
5928 do_htlc_claim_current_remote_commitment_only(false);
5932 fn htlc_claim_single_commitment_only_b() {
5933 do_htlc_claim_previous_remote_commitment_only(true, false);
5934 do_htlc_claim_previous_remote_commitment_only(false, false);
5935 do_htlc_claim_previous_remote_commitment_only(true, true);
5936 do_htlc_claim_previous_remote_commitment_only(false, true);
5941 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5942 let chanmon_cfgs = create_chanmon_cfgs(2);
5943 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5944 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5945 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5946 //Force duplicate channel ids
5947 for node in nodes.iter() {
5948 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5951 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5952 let channel_value_satoshis=10000;
5953 let push_msat=10001;
5954 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5955 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5956 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5958 //Create a second channel with a channel_id collision
5959 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5963 fn bolt2_open_channel_sending_node_checks_part2() {
5964 let chanmon_cfgs = create_chanmon_cfgs(2);
5965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5967 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5969 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5970 let channel_value_satoshis=2^24;
5971 let push_msat=10001;
5972 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5974 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5975 let channel_value_satoshis=10000;
5976 // Test when push_msat is equal to 1000 * funding_satoshis.
5977 let push_msat=1000*channel_value_satoshis+1;
5978 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5980 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5981 let channel_value_satoshis=10000;
5982 let push_msat=10001;
5983 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
5984 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5985 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5987 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5988 // 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
5989 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5991 // 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.
5992 assert!(BREAKDOWN_TIMEOUT>0);
5993 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5995 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5996 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5997 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5999 // 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.
6000 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6001 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6002 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6003 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6004 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6008 fn bolt2_open_channel_sane_dust_limit() {
6009 let chanmon_cfgs = create_chanmon_cfgs(2);
6010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6012 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6014 let channel_value_satoshis=1000000;
6015 let push_msat=10001;
6016 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6017 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6018 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6019 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6021 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6022 let events = nodes[1].node.get_and_clear_pending_msg_events();
6023 let err_msg = match events[0] {
6024 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6027 _ => panic!("Unexpected event"),
6029 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6032 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6033 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6034 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6035 // is no longer affordable once it's freed.
6037 fn test_fail_holding_cell_htlc_upon_free() {
6038 let chanmon_cfgs = create_chanmon_cfgs(2);
6039 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6040 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6041 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6042 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6044 // First nodes[0] generates an update_fee, setting the channel's
6045 // pending_update_fee.
6047 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6048 *feerate_lock += 20;
6050 nodes[0].node.timer_tick_occurred();
6051 check_added_monitors!(nodes[0], 1);
6053 let events = nodes[0].node.get_and_clear_pending_msg_events();
6054 assert_eq!(events.len(), 1);
6055 let (update_msg, commitment_signed) = match events[0] {
6056 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6057 (update_fee.as_ref(), commitment_signed)
6059 _ => panic!("Unexpected event"),
6062 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6064 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6065 let channel_reserve = chan_stat.channel_reserve_msat;
6066 let feerate = get_feerate!(nodes[0], chan.2);
6068 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6069 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6070 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6072 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6073 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6074 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6075 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6077 // Flush the pending fee update.
6078 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6079 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6080 check_added_monitors!(nodes[1], 1);
6081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6082 check_added_monitors!(nodes[0], 1);
6084 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6085 // HTLC, but now that the fee has been raised the payment will now fail, causing
6086 // us to surface its failure to the user.
6087 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6088 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6089 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);
6090 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 {}",
6091 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6092 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6094 // Check that the payment failed to be sent out.
6095 let events = nodes[0].node.get_and_clear_pending_events();
6096 assert_eq!(events.len(), 1);
6098 &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, .. } => {
6099 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6100 assert_eq!(our_payment_hash.clone(), *payment_hash);
6101 assert_eq!(*rejected_by_dest, false);
6102 assert_eq!(*all_paths_failed, true);
6103 assert_eq!(*network_update, None);
6104 assert_eq!(*short_channel_id, None);
6105 assert_eq!(*error_code, None);
6106 assert_eq!(*error_data, None);
6108 _ => panic!("Unexpected event"),
6112 // Test that if multiple HTLCs are released from the holding cell and one is
6113 // valid but the other is no longer valid upon release, the valid HTLC can be
6114 // successfully completed while the other one fails as expected.
6116 fn test_free_and_fail_holding_cell_htlcs() {
6117 let chanmon_cfgs = create_chanmon_cfgs(2);
6118 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6119 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6120 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6121 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6123 // First nodes[0] generates an update_fee, setting the channel's
6124 // pending_update_fee.
6126 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6127 *feerate_lock += 200;
6129 nodes[0].node.timer_tick_occurred();
6130 check_added_monitors!(nodes[0], 1);
6132 let events = nodes[0].node.get_and_clear_pending_msg_events();
6133 assert_eq!(events.len(), 1);
6134 let (update_msg, commitment_signed) = match events[0] {
6135 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6136 (update_fee.as_ref(), commitment_signed)
6138 _ => panic!("Unexpected event"),
6141 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6143 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6144 let channel_reserve = chan_stat.channel_reserve_msat;
6145 let feerate = get_feerate!(nodes[0], chan.2);
6147 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6149 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6150 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6151 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6153 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6154 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6155 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6156 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6157 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6158 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6159 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6161 // Flush the pending fee update.
6162 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6163 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6164 check_added_monitors!(nodes[1], 1);
6165 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6166 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6167 check_added_monitors!(nodes[0], 2);
6169 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6170 // but now that the fee has been raised the second payment will now fail, causing us
6171 // to surface its failure to the user. The first payment should succeed.
6172 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6173 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6174 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);
6175 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 {}",
6176 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6177 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6179 // Check that the second payment failed to be sent out.
6180 let events = nodes[0].node.get_and_clear_pending_events();
6181 assert_eq!(events.len(), 1);
6183 &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, .. } => {
6184 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6185 assert_eq!(payment_hash_2.clone(), *payment_hash);
6186 assert_eq!(*rejected_by_dest, false);
6187 assert_eq!(*all_paths_failed, true);
6188 assert_eq!(*network_update, None);
6189 assert_eq!(*short_channel_id, None);
6190 assert_eq!(*error_code, None);
6191 assert_eq!(*error_data, None);
6193 _ => panic!("Unexpected event"),
6196 // Complete the first payment and the RAA from the fee update.
6197 let (payment_event, send_raa_event) = {
6198 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6199 assert_eq!(msgs.len(), 2);
6200 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6202 let raa = match send_raa_event {
6203 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6204 _ => panic!("Unexpected event"),
6206 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6207 check_added_monitors!(nodes[1], 1);
6208 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6209 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6210 let events = nodes[1].node.get_and_clear_pending_events();
6211 assert_eq!(events.len(), 1);
6213 Event::PendingHTLCsForwardable { .. } => {},
6214 _ => panic!("Unexpected event"),
6216 nodes[1].node.process_pending_htlc_forwards();
6217 let events = nodes[1].node.get_and_clear_pending_events();
6218 assert_eq!(events.len(), 1);
6220 Event::PaymentReceived { .. } => {},
6221 _ => panic!("Unexpected event"),
6223 nodes[1].node.claim_funds(payment_preimage_1);
6224 check_added_monitors!(nodes[1], 1);
6225 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6226 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6227 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6228 expect_payment_sent!(nodes[0], payment_preimage_1);
6231 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6232 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6233 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6236 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6237 let chanmon_cfgs = create_chanmon_cfgs(3);
6238 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6239 // When this test was written, the default base fee floated based on the HTLC count.
6240 // It is now fixed, so we simply set the fee to the expected value here.
6241 let mut config = test_default_channel_config();
6242 config.channel_options.forwarding_fee_base_msat = 196;
6243 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6244 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6245 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6246 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6248 // First nodes[1] generates an update_fee, setting the channel's
6249 // pending_update_fee.
6251 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6252 *feerate_lock += 20;
6254 nodes[1].node.timer_tick_occurred();
6255 check_added_monitors!(nodes[1], 1);
6257 let events = nodes[1].node.get_and_clear_pending_msg_events();
6258 assert_eq!(events.len(), 1);
6259 let (update_msg, commitment_signed) = match events[0] {
6260 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6261 (update_fee.as_ref(), commitment_signed)
6263 _ => panic!("Unexpected event"),
6266 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6268 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6269 let channel_reserve = chan_stat.channel_reserve_msat;
6270 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6272 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6274 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6275 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6276 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6277 let payment_event = {
6278 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6279 check_added_monitors!(nodes[0], 1);
6281 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6282 assert_eq!(events.len(), 1);
6284 SendEvent::from_event(events.remove(0))
6286 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6287 check_added_monitors!(nodes[1], 0);
6288 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6289 expect_pending_htlcs_forwardable!(nodes[1]);
6291 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6292 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6294 // Flush the pending fee update.
6295 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6296 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6297 check_added_monitors!(nodes[2], 1);
6298 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6299 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6300 check_added_monitors!(nodes[1], 2);
6302 // A final RAA message is generated to finalize the fee update.
6303 let events = nodes[1].node.get_and_clear_pending_msg_events();
6304 assert_eq!(events.len(), 1);
6306 let raa_msg = match &events[0] {
6307 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6310 _ => panic!("Unexpected event"),
6313 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6314 check_added_monitors!(nodes[2], 1);
6315 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6317 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6318 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6319 assert_eq!(process_htlc_forwards_event.len(), 1);
6320 match &process_htlc_forwards_event[0] {
6321 &Event::PendingHTLCsForwardable { .. } => {},
6322 _ => panic!("Unexpected event"),
6325 // In response, we call ChannelManager's process_pending_htlc_forwards
6326 nodes[1].node.process_pending_htlc_forwards();
6327 check_added_monitors!(nodes[1], 1);
6329 // This causes the HTLC to be failed backwards.
6330 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6331 assert_eq!(fail_event.len(), 1);
6332 let (fail_msg, commitment_signed) = match &fail_event[0] {
6333 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6334 assert_eq!(updates.update_add_htlcs.len(), 0);
6335 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6336 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6337 assert_eq!(updates.update_fail_htlcs.len(), 1);
6338 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6340 _ => panic!("Unexpected event"),
6343 // Pass the failure messages back to nodes[0].
6344 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6345 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6347 // Complete the HTLC failure+removal process.
6348 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6349 check_added_monitors!(nodes[0], 1);
6350 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6351 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6352 check_added_monitors!(nodes[1], 2);
6353 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6354 assert_eq!(final_raa_event.len(), 1);
6355 let raa = match &final_raa_event[0] {
6356 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6357 _ => panic!("Unexpected event"),
6359 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6360 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6361 check_added_monitors!(nodes[0], 1);
6364 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6365 // 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.
6366 //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.
6369 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6370 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6371 let chanmon_cfgs = create_chanmon_cfgs(2);
6372 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6373 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6374 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6375 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6377 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6378 route.paths[0][0].fee_msat = 100;
6380 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6381 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6382 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6383 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6387 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6388 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6389 let chanmon_cfgs = create_chanmon_cfgs(2);
6390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6392 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6393 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6395 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6396 route.paths[0][0].fee_msat = 0;
6397 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6398 assert_eq!(err, "Cannot send 0-msat HTLC"));
6400 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6401 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6405 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6406 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6407 let chanmon_cfgs = create_chanmon_cfgs(2);
6408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6410 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6411 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6413 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6414 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6415 check_added_monitors!(nodes[0], 1);
6416 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6417 updates.update_add_htlcs[0].amount_msat = 0;
6419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6420 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6421 check_closed_broadcast!(nodes[1], true).unwrap();
6422 check_added_monitors!(nodes[1], 1);
6423 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6427 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6428 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6429 //It is enforced when constructing a route.
6430 let chanmon_cfgs = create_chanmon_cfgs(2);
6431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6433 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6434 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6436 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6437 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6438 assert_eq!(err, &"Channel CLTV overflowed?"));
6442 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6443 //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.
6444 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6445 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6446 let chanmon_cfgs = create_chanmon_cfgs(2);
6447 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6449 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6450 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6451 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6453 for i in 0..max_accepted_htlcs {
6454 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6455 let payment_event = {
6456 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6457 check_added_monitors!(nodes[0], 1);
6459 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6460 assert_eq!(events.len(), 1);
6461 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6462 assert_eq!(htlcs[0].htlc_id, i);
6466 SendEvent::from_event(events.remove(0))
6468 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6469 check_added_monitors!(nodes[1], 0);
6470 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6472 expect_pending_htlcs_forwardable!(nodes[1]);
6473 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6475 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6476 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6477 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6479 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6480 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6484 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6485 //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.
6486 let chanmon_cfgs = create_chanmon_cfgs(2);
6487 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6488 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6489 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6490 let channel_value = 100000;
6491 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6492 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6494 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6496 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6497 // Manually create a route over our max in flight (which our router normally automatically
6499 route.paths[0][0].fee_msat = max_in_flight + 1;
6500 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6501 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)));
6503 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6504 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);
6506 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6509 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6511 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6512 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6513 let chanmon_cfgs = create_chanmon_cfgs(2);
6514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6516 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6517 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6518 let htlc_minimum_msat: u64;
6520 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6521 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6522 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6525 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6526 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6527 check_added_monitors!(nodes[0], 1);
6528 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6529 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6530 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6531 assert!(nodes[1].node.list_channels().is_empty());
6532 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6533 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()));
6534 check_added_monitors!(nodes[1], 1);
6535 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6539 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6540 //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
6541 let chanmon_cfgs = create_chanmon_cfgs(2);
6542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6545 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6547 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6548 let channel_reserve = chan_stat.channel_reserve_msat;
6549 let feerate = get_feerate!(nodes[0], chan.2);
6550 // The 2* and +1 are for the fee spike reserve.
6551 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6553 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6554 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6555 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6556 check_added_monitors!(nodes[0], 1);
6557 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6559 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6560 // at this time channel-initiatee receivers are not required to enforce that senders
6561 // respect the fee_spike_reserve.
6562 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6563 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6565 assert!(nodes[1].node.list_channels().is_empty());
6566 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6567 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6568 check_added_monitors!(nodes[1], 1);
6569 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6573 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6574 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6575 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6576 let chanmon_cfgs = create_chanmon_cfgs(2);
6577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6579 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6580 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6582 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6583 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6584 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6585 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6586 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6587 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6589 let mut msg = msgs::UpdateAddHTLC {
6593 payment_hash: our_payment_hash,
6594 cltv_expiry: htlc_cltv,
6595 onion_routing_packet: onion_packet.clone(),
6598 for i in 0..super::channel::OUR_MAX_HTLCS {
6599 msg.htlc_id = i as u64;
6600 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6602 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6603 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6605 assert!(nodes[1].node.list_channels().is_empty());
6606 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6607 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6608 check_added_monitors!(nodes[1], 1);
6609 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6613 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6614 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6615 let chanmon_cfgs = create_chanmon_cfgs(2);
6616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6618 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6619 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6621 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6622 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6623 check_added_monitors!(nodes[0], 1);
6624 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6625 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6626 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6628 assert!(nodes[1].node.list_channels().is_empty());
6629 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6630 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6631 check_added_monitors!(nodes[1], 1);
6632 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6636 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6637 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6638 let chanmon_cfgs = create_chanmon_cfgs(2);
6639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6643 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6644 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6645 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6646 check_added_monitors!(nodes[0], 1);
6647 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6648 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6649 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6651 assert!(nodes[1].node.list_channels().is_empty());
6652 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6653 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6654 check_added_monitors!(nodes[1], 1);
6655 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6659 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6660 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6661 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6662 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6663 let chanmon_cfgs = create_chanmon_cfgs(2);
6664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6666 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6668 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6669 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6670 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6671 check_added_monitors!(nodes[0], 1);
6672 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6673 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6675 //Disconnect and Reconnect
6676 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6677 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6678 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6679 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6680 assert_eq!(reestablish_1.len(), 1);
6681 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6682 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6683 assert_eq!(reestablish_2.len(), 1);
6684 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6685 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6686 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6687 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6690 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6691 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6692 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6693 check_added_monitors!(nodes[1], 1);
6694 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6696 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6698 assert!(nodes[1].node.list_channels().is_empty());
6699 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6700 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6701 check_added_monitors!(nodes[1], 1);
6702 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6706 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6707 //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.
6709 let chanmon_cfgs = create_chanmon_cfgs(2);
6710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6712 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6713 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6714 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6715 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6717 check_added_monitors!(nodes[0], 1);
6718 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6719 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6721 let update_msg = msgs::UpdateFulfillHTLC{
6724 payment_preimage: our_payment_preimage,
6727 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6729 assert!(nodes[0].node.list_channels().is_empty());
6730 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6731 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()));
6732 check_added_monitors!(nodes[0], 1);
6733 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6737 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6738 //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.
6740 let chanmon_cfgs = create_chanmon_cfgs(2);
6741 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6742 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6743 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6744 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6746 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6747 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6748 check_added_monitors!(nodes[0], 1);
6749 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6750 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6752 let update_msg = msgs::UpdateFailHTLC{
6755 reason: msgs::OnionErrorPacket { data: Vec::new()},
6758 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6760 assert!(nodes[0].node.list_channels().is_empty());
6761 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6762 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()));
6763 check_added_monitors!(nodes[0], 1);
6764 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6768 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6769 //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.
6771 let chanmon_cfgs = create_chanmon_cfgs(2);
6772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6777 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6778 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6779 check_added_monitors!(nodes[0], 1);
6780 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6781 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6782 let update_msg = msgs::UpdateFailMalformedHTLC{
6785 sha256_of_onion: [1; 32],
6786 failure_code: 0x8000,
6789 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6791 assert!(nodes[0].node.list_channels().is_empty());
6792 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6793 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()));
6794 check_added_monitors!(nodes[0], 1);
6795 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6799 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6800 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6802 let chanmon_cfgs = create_chanmon_cfgs(2);
6803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6805 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6806 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6808 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6810 nodes[1].node.claim_funds(our_payment_preimage);
6811 check_added_monitors!(nodes[1], 1);
6813 let events = nodes[1].node.get_and_clear_pending_msg_events();
6814 assert_eq!(events.len(), 1);
6815 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6817 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, .. } } => {
6818 assert!(update_add_htlcs.is_empty());
6819 assert_eq!(update_fulfill_htlcs.len(), 1);
6820 assert!(update_fail_htlcs.is_empty());
6821 assert!(update_fail_malformed_htlcs.is_empty());
6822 assert!(update_fee.is_none());
6823 update_fulfill_htlcs[0].clone()
6825 _ => panic!("Unexpected event"),
6829 update_fulfill_msg.htlc_id = 1;
6831 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6833 assert!(nodes[0].node.list_channels().is_empty());
6834 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6835 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6836 check_added_monitors!(nodes[0], 1);
6837 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6841 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6842 //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.
6844 let chanmon_cfgs = create_chanmon_cfgs(2);
6845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6847 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6848 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6850 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6852 nodes[1].node.claim_funds(our_payment_preimage);
6853 check_added_monitors!(nodes[1], 1);
6855 let events = nodes[1].node.get_and_clear_pending_msg_events();
6856 assert_eq!(events.len(), 1);
6857 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6859 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, .. } } => {
6860 assert!(update_add_htlcs.is_empty());
6861 assert_eq!(update_fulfill_htlcs.len(), 1);
6862 assert!(update_fail_htlcs.is_empty());
6863 assert!(update_fail_malformed_htlcs.is_empty());
6864 assert!(update_fee.is_none());
6865 update_fulfill_htlcs[0].clone()
6867 _ => panic!("Unexpected event"),
6871 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6873 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6875 assert!(nodes[0].node.list_channels().is_empty());
6876 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6877 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6878 check_added_monitors!(nodes[0], 1);
6879 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6883 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6884 //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.
6886 let chanmon_cfgs = create_chanmon_cfgs(2);
6887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6889 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6890 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6892 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6893 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6894 check_added_monitors!(nodes[0], 1);
6896 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6897 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6900 check_added_monitors!(nodes[1], 0);
6901 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6903 let events = nodes[1].node.get_and_clear_pending_msg_events();
6905 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6907 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, .. } } => {
6908 assert!(update_add_htlcs.is_empty());
6909 assert!(update_fulfill_htlcs.is_empty());
6910 assert!(update_fail_htlcs.is_empty());
6911 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6912 assert!(update_fee.is_none());
6913 update_fail_malformed_htlcs[0].clone()
6915 _ => panic!("Unexpected event"),
6918 update_msg.failure_code &= !0x8000;
6919 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6921 assert!(nodes[0].node.list_channels().is_empty());
6922 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6923 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6924 check_added_monitors!(nodes[0], 1);
6925 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6929 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6930 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6931 // * 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.
6933 let chanmon_cfgs = create_chanmon_cfgs(3);
6934 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6935 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6936 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6937 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6938 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6940 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6943 let mut payment_event = {
6944 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6945 check_added_monitors!(nodes[0], 1);
6946 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6947 assert_eq!(events.len(), 1);
6948 SendEvent::from_event(events.remove(0))
6950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6951 check_added_monitors!(nodes[1], 0);
6952 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6953 expect_pending_htlcs_forwardable!(nodes[1]);
6954 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6955 assert_eq!(events_2.len(), 1);
6956 check_added_monitors!(nodes[1], 1);
6957 payment_event = SendEvent::from_event(events_2.remove(0));
6958 assert_eq!(payment_event.msgs.len(), 1);
6961 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6962 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6963 check_added_monitors!(nodes[2], 0);
6964 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6966 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6967 assert_eq!(events_3.len(), 1);
6968 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6970 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 } } => {
6971 assert!(update_add_htlcs.is_empty());
6972 assert!(update_fulfill_htlcs.is_empty());
6973 assert!(update_fail_htlcs.is_empty());
6974 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6975 assert!(update_fee.is_none());
6976 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6978 _ => panic!("Unexpected event"),
6982 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6984 check_added_monitors!(nodes[1], 0);
6985 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6986 expect_pending_htlcs_forwardable!(nodes[1]);
6987 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6988 assert_eq!(events_4.len(), 1);
6990 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6992 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, .. } } => {
6993 assert!(update_add_htlcs.is_empty());
6994 assert!(update_fulfill_htlcs.is_empty());
6995 assert_eq!(update_fail_htlcs.len(), 1);
6996 assert!(update_fail_malformed_htlcs.is_empty());
6997 assert!(update_fee.is_none());
6999 _ => panic!("Unexpected event"),
7002 check_added_monitors!(nodes[1], 1);
7005 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7006 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7007 // 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
7008 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7010 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7011 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7012 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7013 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7014 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7015 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7017 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7019 // We route 2 dust-HTLCs between A and B
7020 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7021 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7022 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7024 // Cache one local commitment tx as previous
7025 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7027 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7028 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7029 check_added_monitors!(nodes[1], 0);
7030 expect_pending_htlcs_forwardable!(nodes[1]);
7031 check_added_monitors!(nodes[1], 1);
7033 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7034 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7035 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7036 check_added_monitors!(nodes[0], 1);
7038 // Cache one local commitment tx as lastest
7039 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7041 let events = nodes[0].node.get_and_clear_pending_msg_events();
7043 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7044 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7046 _ => panic!("Unexpected event"),
7049 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7050 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7052 _ => panic!("Unexpected event"),
7055 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7056 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7057 if announce_latest {
7058 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7060 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7063 check_closed_broadcast!(nodes[0], true);
7064 check_added_monitors!(nodes[0], 1);
7065 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7067 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7068 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7069 let events = nodes[0].node.get_and_clear_pending_events();
7070 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7071 assert_eq!(events.len(), 2);
7072 let mut first_failed = false;
7073 for event in events {
7075 Event::PaymentPathFailed { payment_hash, .. } => {
7076 if payment_hash == payment_hash_1 {
7077 assert!(!first_failed);
7078 first_failed = true;
7080 assert_eq!(payment_hash, payment_hash_2);
7083 _ => panic!("Unexpected event"),
7089 fn test_failure_delay_dust_htlc_local_commitment() {
7090 do_test_failure_delay_dust_htlc_local_commitment(true);
7091 do_test_failure_delay_dust_htlc_local_commitment(false);
7094 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7095 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7096 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7097 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7098 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7099 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7100 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7102 let chanmon_cfgs = create_chanmon_cfgs(3);
7103 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7104 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7105 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7106 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7108 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7110 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7111 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7113 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7114 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7116 // We revoked bs_commitment_tx
7118 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7119 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7122 let mut timeout_tx = Vec::new();
7124 // We fail dust-HTLC 1 by broadcast of local commitment tx
7125 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7126 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7127 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7128 expect_payment_failed!(nodes[0], dust_hash, true);
7130 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7131 check_closed_broadcast!(nodes[0], true);
7132 check_added_monitors!(nodes[0], 1);
7133 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7134 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7135 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7136 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7137 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7138 mine_transaction(&nodes[0], &timeout_tx[0]);
7139 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7140 expect_payment_failed!(nodes[0], non_dust_hash, true);
7142 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7143 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7144 check_closed_broadcast!(nodes[0], true);
7145 check_added_monitors!(nodes[0], 1);
7146 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7147 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7148 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7149 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7151 expect_payment_failed!(nodes[0], dust_hash, true);
7152 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7153 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7154 mine_transaction(&nodes[0], &timeout_tx[0]);
7155 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7156 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7157 expect_payment_failed!(nodes[0], non_dust_hash, true);
7159 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7161 let events = nodes[0].node.get_and_clear_pending_events();
7162 assert_eq!(events.len(), 2);
7165 Event::PaymentPathFailed { payment_hash, .. } => {
7166 if payment_hash == dust_hash { first = true; }
7167 else { first = false; }
7169 _ => panic!("Unexpected event"),
7172 Event::PaymentPathFailed { payment_hash, .. } => {
7173 if first { assert_eq!(payment_hash, non_dust_hash); }
7174 else { assert_eq!(payment_hash, dust_hash); }
7176 _ => panic!("Unexpected event"),
7183 fn test_sweep_outbound_htlc_failure_update() {
7184 do_test_sweep_outbound_htlc_failure_update(false, true);
7185 do_test_sweep_outbound_htlc_failure_update(false, false);
7186 do_test_sweep_outbound_htlc_failure_update(true, false);
7190 fn test_user_configurable_csv_delay() {
7191 // We test our channel constructors yield errors when we pass them absurd csv delay
7193 let mut low_our_to_self_config = UserConfig::default();
7194 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7195 let mut high_their_to_self_config = UserConfig::default();
7196 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7197 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7198 let chanmon_cfgs = create_chanmon_cfgs(2);
7199 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7200 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7201 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7203 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7204 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0, &low_our_to_self_config, 0) {
7206 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())); },
7207 _ => panic!("Unexpected event"),
7209 } else { assert!(false) }
7211 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7212 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7213 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7214 open_channel.to_self_delay = 200;
7215 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &low_our_to_self_config, 0, &nodes[0].logger) {
7217 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())); },
7218 _ => panic!("Unexpected event"),
7220 } else { assert!(false); }
7222 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7223 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7224 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()));
7225 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7226 accept_channel.to_self_delay = 200;
7227 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7229 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7231 &ErrorAction::SendErrorMessage { ref msg } => {
7232 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()));
7233 reason_msg = msg.data.clone();
7237 } else { panic!(); }
7238 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7240 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7241 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7242 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7243 open_channel.to_self_delay = 200;
7244 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &high_their_to_self_config, 0, &nodes[0].logger) {
7246 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())); },
7247 _ => panic!("Unexpected event"),
7249 } else { assert!(false); }
7253 fn test_data_loss_protect() {
7254 // We want to be sure that :
7255 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7256 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7257 // * we close channel in case of detecting other being fallen behind
7258 // * we are able to claim our own outputs thanks to to_remote being static
7259 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7265 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7266 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7267 // during signing due to revoked tx
7268 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7269 let keys_manager = &chanmon_cfgs[0].keys_manager;
7272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7274 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7276 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7278 // Cache node A state before any channel update
7279 let previous_node_state = nodes[0].node.encode();
7280 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7281 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7283 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7284 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7286 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7287 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7289 // Restore node A from previous state
7290 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7291 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7292 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7293 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7294 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7295 persister = test_utils::TestPersister::new();
7296 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7298 let mut channel_monitors = HashMap::new();
7299 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7300 <(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 {
7301 keys_manager: keys_manager,
7302 fee_estimator: &fee_estimator,
7303 chain_monitor: &monitor,
7305 tx_broadcaster: &tx_broadcaster,
7306 default_config: UserConfig::default(),
7310 nodes[0].node = &node_state_0;
7311 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7312 nodes[0].chain_monitor = &monitor;
7313 nodes[0].chain_source = &chain_source;
7315 check_added_monitors!(nodes[0], 1);
7317 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7318 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7320 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7322 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7323 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7324 check_added_monitors!(nodes[0], 1);
7327 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7328 assert_eq!(node_txn.len(), 0);
7331 let mut reestablish_1 = Vec::with_capacity(1);
7332 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7333 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7334 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7335 reestablish_1.push(msg.clone());
7336 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7337 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7339 &ErrorAction::SendErrorMessage { ref msg } => {
7340 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");
7342 _ => panic!("Unexpected event!"),
7345 panic!("Unexpected event")
7349 // Check we close channel detecting A is fallen-behind
7350 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7351 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7352 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7353 check_added_monitors!(nodes[1], 1);
7355 // Check A is able to claim to_remote output
7356 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7357 assert_eq!(node_txn.len(), 1);
7358 check_spends!(node_txn[0], chan.3);
7359 assert_eq!(node_txn[0].output.len(), 2);
7360 mine_transaction(&nodes[0], &node_txn[0]);
7361 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7362 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() });
7363 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7364 assert_eq!(spend_txn.len(), 1);
7365 check_spends!(spend_txn[0], node_txn[0]);
7369 fn test_check_htlc_underpaying() {
7370 // Send payment through A -> B but A is maliciously
7371 // sending a probe payment (i.e less than expected value0
7372 // to B, B should refuse payment.
7374 let chanmon_cfgs = create_chanmon_cfgs(2);
7375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7377 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7379 // Create some initial channels
7380 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7382 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7383 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7384 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, nodes[0].network_graph, None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer).unwrap();
7385 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7386 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7387 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7388 check_added_monitors!(nodes[0], 1);
7390 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7391 assert_eq!(events.len(), 1);
7392 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7393 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7394 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7396 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7397 // and then will wait a second random delay before failing the HTLC back:
7398 expect_pending_htlcs_forwardable!(nodes[1]);
7399 expect_pending_htlcs_forwardable!(nodes[1]);
7401 // Node 3 is expecting payment of 100_000 but received 10_000,
7402 // it should fail htlc like we didn't know the preimage.
7403 nodes[1].node.process_pending_htlc_forwards();
7405 let events = nodes[1].node.get_and_clear_pending_msg_events();
7406 assert_eq!(events.len(), 1);
7407 let (update_fail_htlc, commitment_signed) = match events[0] {
7408 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 } } => {
7409 assert!(update_add_htlcs.is_empty());
7410 assert!(update_fulfill_htlcs.is_empty());
7411 assert_eq!(update_fail_htlcs.len(), 1);
7412 assert!(update_fail_malformed_htlcs.is_empty());
7413 assert!(update_fee.is_none());
7414 (update_fail_htlcs[0].clone(), commitment_signed)
7416 _ => panic!("Unexpected event"),
7418 check_added_monitors!(nodes[1], 1);
7420 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7421 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7423 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7424 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7425 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7426 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7430 fn test_announce_disable_channels() {
7431 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7432 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7434 let chanmon_cfgs = create_chanmon_cfgs(2);
7435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7437 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7439 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7440 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7441 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7444 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7445 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7447 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7448 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7449 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7450 assert_eq!(msg_events.len(), 3);
7451 let mut chans_disabled = HashMap::new();
7452 for e in msg_events {
7454 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7455 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7456 // Check that each channel gets updated exactly once
7457 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7458 panic!("Generated ChannelUpdate for wrong chan!");
7461 _ => panic!("Unexpected event"),
7465 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7466 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7467 assert_eq!(reestablish_1.len(), 3);
7468 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7469 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7470 assert_eq!(reestablish_2.len(), 3);
7472 // Reestablish chan_1
7473 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7474 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7475 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7476 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7477 // Reestablish chan_2
7478 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7479 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7480 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7481 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7482 // Reestablish chan_3
7483 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7484 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7485 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7486 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7488 nodes[0].node.timer_tick_occurred();
7489 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7490 nodes[0].node.timer_tick_occurred();
7491 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7492 assert_eq!(msg_events.len(), 3);
7493 for e in msg_events {
7495 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7496 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7497 match chans_disabled.remove(&msg.contents.short_channel_id) {
7498 // Each update should have a higher timestamp than the previous one, replacing
7500 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7501 None => panic!("Generated ChannelUpdate for wrong chan!"),
7504 _ => panic!("Unexpected event"),
7507 // Check that each channel gets updated exactly once
7508 assert!(chans_disabled.is_empty());
7512 fn test_priv_forwarding_rejection() {
7513 // If we have a private channel with outbound liquidity, and
7514 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7515 // to forward through that channel.
7516 let chanmon_cfgs = create_chanmon_cfgs(3);
7517 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7518 let mut no_announce_cfg = test_default_channel_config();
7519 no_announce_cfg.channel_options.announced_channel = false;
7520 no_announce_cfg.accept_forwards_to_priv_channels = false;
7521 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7522 let persister: test_utils::TestPersister;
7523 let new_chain_monitor: test_utils::TestChainMonitor;
7524 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7525 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7527 let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known()).2;
7529 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7530 // not send for private channels.
7531 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7532 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7533 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7534 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7535 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7537 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7538 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7539 nodes[2].node.handle_funding_created(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingCreated, nodes[2].node.get_our_node_id()));
7540 check_added_monitors!(nodes[2], 1);
7542 let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7543 nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7544 check_added_monitors!(nodes[1], 1);
7546 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7547 confirm_transaction_at(&nodes[1], &tx, conf_height);
7548 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7549 confirm_transaction_at(&nodes[2], &tx, conf_height);
7550 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7551 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7552 nodes[1].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id()));
7553 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7554 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7555 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7557 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7558 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7559 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7561 // We should always be able to forward through nodes[1] as long as its out through a public
7563 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7565 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7566 // to nodes[2], which should be rejected:
7567 let route_hint = RouteHint(vec![RouteHintHop {
7568 src_node_id: nodes[1].node.get_our_node_id(),
7569 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7570 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7571 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7572 htlc_minimum_msat: None,
7573 htlc_maximum_msat: None,
7575 let last_hops = vec![route_hint];
7576 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], last_hops, 10_000, TEST_FINAL_CLTV);
7578 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7579 check_added_monitors!(nodes[0], 1);
7580 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7582 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7584 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7585 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7586 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7587 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7588 assert!(htlc_fail_updates.update_fee.is_none());
7590 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7591 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7592 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7594 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7595 // to true. Sadly there is currently no way to change it at runtime.
7597 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7598 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7600 let nodes_1_serialized = nodes[1].node.encode();
7601 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7602 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7603 get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7604 get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7606 persister = test_utils::TestPersister::new();
7607 let keys_manager = &chanmon_cfgs[1].keys_manager;
7608 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);
7609 nodes[1].chain_monitor = &new_chain_monitor;
7611 let mut monitor_a_read = &monitor_a_serialized.0[..];
7612 let mut monitor_b_read = &monitor_b_serialized.0[..];
7613 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7614 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7615 assert!(monitor_a_read.is_empty());
7616 assert!(monitor_b_read.is_empty());
7618 no_announce_cfg.accept_forwards_to_priv_channels = true;
7620 let mut nodes_1_read = &nodes_1_serialized[..];
7621 let (_, nodes_1_deserialized_tmp) = {
7622 let mut channel_monitors = HashMap::new();
7623 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7624 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7625 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7626 default_config: no_announce_cfg,
7628 fee_estimator: node_cfgs[1].fee_estimator,
7629 chain_monitor: nodes[1].chain_monitor,
7630 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7631 logger: nodes[1].logger,
7635 assert!(nodes_1_read.is_empty());
7636 nodes_1_deserialized = nodes_1_deserialized_tmp;
7638 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7639 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7640 check_added_monitors!(nodes[1], 2);
7641 nodes[1].node = &nodes_1_deserialized;
7643 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7644 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7645 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7646 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7647 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7648 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7649 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7650 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7652 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7653 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7654 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7655 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7656 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7657 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7658 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7659 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7661 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7662 check_added_monitors!(nodes[0], 1);
7663 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7664 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7668 fn test_bump_penalty_txn_on_revoked_commitment() {
7669 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7670 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7672 let chanmon_cfgs = create_chanmon_cfgs(2);
7673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7675 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7677 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7679 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7680 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7681 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7683 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7684 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7685 assert_eq!(revoked_txn[0].output.len(), 4);
7686 assert_eq!(revoked_txn[0].input.len(), 1);
7687 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7688 let revoked_txid = revoked_txn[0].txid();
7690 let mut penalty_sum = 0;
7691 for outp in revoked_txn[0].output.iter() {
7692 if outp.script_pubkey.is_v0_p2wsh() {
7693 penalty_sum += outp.value;
7697 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7698 let header_114 = connect_blocks(&nodes[1], 14);
7700 // Actually revoke tx by claiming a HTLC
7701 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7702 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7703 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7704 check_added_monitors!(nodes[1], 1);
7706 // One or more justice tx should have been broadcast, check it
7710 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7711 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7712 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7713 assert_eq!(node_txn[0].output.len(), 1);
7714 check_spends!(node_txn[0], revoked_txn[0]);
7715 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7716 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7717 penalty_1 = node_txn[0].txid();
7721 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7722 connect_blocks(&nodes[1], 15);
7723 let mut penalty_2 = penalty_1;
7724 let mut feerate_2 = 0;
7726 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7727 assert_eq!(node_txn.len(), 1);
7728 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7729 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7730 assert_eq!(node_txn[0].output.len(), 1);
7731 check_spends!(node_txn[0], revoked_txn[0]);
7732 penalty_2 = node_txn[0].txid();
7733 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7734 assert_ne!(penalty_2, penalty_1);
7735 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7736 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7737 // Verify 25% bump heuristic
7738 assert!(feerate_2 * 100 >= feerate_1 * 125);
7742 assert_ne!(feerate_2, 0);
7744 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7745 connect_blocks(&nodes[1], 1);
7747 let mut feerate_3 = 0;
7749 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7750 assert_eq!(node_txn.len(), 1);
7751 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7752 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7753 assert_eq!(node_txn[0].output.len(), 1);
7754 check_spends!(node_txn[0], revoked_txn[0]);
7755 penalty_3 = node_txn[0].txid();
7756 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7757 assert_ne!(penalty_3, penalty_2);
7758 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7759 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7760 // Verify 25% bump heuristic
7761 assert!(feerate_3 * 100 >= feerate_2 * 125);
7765 assert_ne!(feerate_3, 0);
7767 nodes[1].node.get_and_clear_pending_events();
7768 nodes[1].node.get_and_clear_pending_msg_events();
7772 fn test_bump_penalty_txn_on_revoked_htlcs() {
7773 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7774 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7776 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7777 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7780 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7782 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7783 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7784 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7785 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7786 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, &nodes[0].network_graph, None,
7787 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7788 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7789 let payee = Payee::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7790 let route = get_route(&nodes[1].node.get_our_node_id(), &payee, nodes[1].network_graph, None,
7791 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7792 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7794 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7795 assert_eq!(revoked_local_txn[0].input.len(), 1);
7796 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7798 // Revoke local commitment tx
7799 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7801 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7802 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7803 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7804 check_closed_broadcast!(nodes[1], true);
7805 check_added_monitors!(nodes[1], 1);
7806 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7807 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7809 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7810 assert_eq!(revoked_htlc_txn.len(), 3);
7811 check_spends!(revoked_htlc_txn[1], chan.3);
7813 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7814 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7815 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7817 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7818 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7819 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7820 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7822 // Broadcast set of revoked txn on A
7823 let hash_128 = connect_blocks(&nodes[0], 40);
7824 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7825 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7826 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7827 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7828 let events = nodes[0].node.get_and_clear_pending_events();
7829 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7831 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7832 _ => panic!("Unexpected event"),
7838 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7839 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7840 // Verify claim tx are spending revoked HTLC txn
7842 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7843 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7844 // which are included in the same block (they are broadcasted because we scan the
7845 // transactions linearly and generate claims as we go, they likely should be removed in the
7847 assert_eq!(node_txn[0].input.len(), 1);
7848 check_spends!(node_txn[0], revoked_local_txn[0]);
7849 assert_eq!(node_txn[1].input.len(), 1);
7850 check_spends!(node_txn[1], revoked_local_txn[0]);
7851 assert_eq!(node_txn[2].input.len(), 1);
7852 check_spends!(node_txn[2], revoked_local_txn[0]);
7854 // Each of the three justice transactions claim a separate (single) output of the three
7855 // available, which we check here:
7856 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7857 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7858 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7860 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7861 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7863 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7864 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7865 // a remote commitment tx has already been confirmed).
7866 check_spends!(node_txn[3], chan.3);
7868 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7869 // output, checked above).
7870 assert_eq!(node_txn[4].input.len(), 2);
7871 assert_eq!(node_txn[4].output.len(), 1);
7872 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7874 first = node_txn[4].txid();
7875 // Store both feerates for later comparison
7876 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7877 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7878 penalty_txn = vec![node_txn[2].clone()];
7882 // Connect one more block to see if bumped penalty are issued for HTLC txn
7883 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7884 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7885 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7886 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7888 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7889 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7891 check_spends!(node_txn[0], revoked_local_txn[0]);
7892 check_spends!(node_txn[1], revoked_local_txn[0]);
7893 // Note that these are both bogus - they spend outputs already claimed in block 129:
7894 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7895 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7897 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7898 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7904 // Few more blocks to confirm penalty txn
7905 connect_blocks(&nodes[0], 4);
7906 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7907 let header_144 = connect_blocks(&nodes[0], 9);
7909 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7910 assert_eq!(node_txn.len(), 1);
7912 assert_eq!(node_txn[0].input.len(), 2);
7913 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7914 // Verify bumped tx is different and 25% bump heuristic
7915 assert_ne!(first, node_txn[0].txid());
7916 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7917 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7918 assert!(feerate_2 * 100 > feerate_1 * 125);
7919 let txn = vec![node_txn[0].clone()];
7923 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7924 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7926 connect_blocks(&nodes[0], 20);
7928 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7929 // We verify than no new transaction has been broadcast because previously
7930 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7931 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7932 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7933 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7934 // up bumped justice generation.
7935 assert_eq!(node_txn.len(), 0);
7938 check_closed_broadcast!(nodes[0], true);
7939 check_added_monitors!(nodes[0], 1);
7943 fn test_bump_penalty_txn_on_remote_commitment() {
7944 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7945 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7948 // Provide preimage for one
7949 // Check aggregation
7951 let chanmon_cfgs = create_chanmon_cfgs(2);
7952 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7953 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7954 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7956 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7957 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7958 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7960 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7961 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7962 assert_eq!(remote_txn[0].output.len(), 4);
7963 assert_eq!(remote_txn[0].input.len(), 1);
7964 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7966 // Claim a HTLC without revocation (provide B monitor with preimage)
7967 nodes[1].node.claim_funds(payment_preimage);
7968 mine_transaction(&nodes[1], &remote_txn[0]);
7969 check_added_monitors!(nodes[1], 2);
7970 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7972 // One or more claim tx should have been broadcast, check it
7976 let feerate_timeout;
7977 let feerate_preimage;
7979 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7980 // 9 transactions including:
7981 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7982 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7983 // 2 * HTLC-Success (one RBF bump we'll check later)
7985 assert_eq!(node_txn.len(), 8);
7986 assert_eq!(node_txn[0].input.len(), 1);
7987 assert_eq!(node_txn[6].input.len(), 1);
7988 check_spends!(node_txn[0], remote_txn[0]);
7989 check_spends!(node_txn[6], remote_txn[0]);
7990 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7991 preimage_bump = node_txn[3].clone();
7993 check_spends!(node_txn[1], chan.3);
7994 check_spends!(node_txn[2], node_txn[1]);
7995 assert_eq!(node_txn[1], node_txn[4]);
7996 assert_eq!(node_txn[2], node_txn[5]);
7998 timeout = node_txn[6].txid();
7999 let index = node_txn[6].input[0].previous_output.vout;
8000 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8001 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8003 preimage = node_txn[0].txid();
8004 let index = node_txn[0].input[0].previous_output.vout;
8005 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8006 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8010 assert_ne!(feerate_timeout, 0);
8011 assert_ne!(feerate_preimage, 0);
8013 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8014 connect_blocks(&nodes[1], 15);
8016 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8017 assert_eq!(node_txn.len(), 1);
8018 assert_eq!(node_txn[0].input.len(), 1);
8019 assert_eq!(preimage_bump.input.len(), 1);
8020 check_spends!(node_txn[0], remote_txn[0]);
8021 check_spends!(preimage_bump, remote_txn[0]);
8023 let index = preimage_bump.input[0].previous_output.vout;
8024 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8025 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8026 assert!(new_feerate * 100 > feerate_timeout * 125);
8027 assert_ne!(timeout, preimage_bump.txid());
8029 let index = node_txn[0].input[0].previous_output.vout;
8030 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8031 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8032 assert!(new_feerate * 100 > feerate_preimage * 125);
8033 assert_ne!(preimage, node_txn[0].txid());
8038 nodes[1].node.get_and_clear_pending_events();
8039 nodes[1].node.get_and_clear_pending_msg_events();
8043 fn test_counterparty_raa_skip_no_crash() {
8044 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8045 // commitment transaction, we would have happily carried on and provided them the next
8046 // commitment transaction based on one RAA forward. This would probably eventually have led to
8047 // channel closure, but it would not have resulted in funds loss. Still, our
8048 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8049 // check simply that the channel is closed in response to such an RAA, but don't check whether
8050 // we decide to punish our counterparty for revoking their funds (as we don't currently
8052 let chanmon_cfgs = create_chanmon_cfgs(2);
8053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8055 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8056 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8058 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8059 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8061 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8063 // Make signer believe we got a counterparty signature, so that it allows the revocation
8064 keys.get_enforcement_state().last_holder_commitment -= 1;
8065 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8067 // Must revoke without gaps
8068 keys.get_enforcement_state().last_holder_commitment -= 1;
8069 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8071 keys.get_enforcement_state().last_holder_commitment -= 1;
8072 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8073 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8076 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8077 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8078 check_added_monitors!(nodes[1], 1);
8079 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8083 fn test_bump_txn_sanitize_tracking_maps() {
8084 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8085 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8087 let chanmon_cfgs = create_chanmon_cfgs(2);
8088 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8089 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8090 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8092 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8093 // Lock HTLC in both directions
8094 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8095 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8097 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8098 assert_eq!(revoked_local_txn[0].input.len(), 1);
8099 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8101 // Revoke local commitment tx
8102 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8104 // Broadcast set of revoked txn on A
8105 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8106 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8107 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8109 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8110 check_closed_broadcast!(nodes[0], true);
8111 check_added_monitors!(nodes[0], 1);
8112 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8114 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8115 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8116 check_spends!(node_txn[0], revoked_local_txn[0]);
8117 check_spends!(node_txn[1], revoked_local_txn[0]);
8118 check_spends!(node_txn[2], revoked_local_txn[0]);
8119 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8123 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8124 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8125 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8127 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8128 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8129 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8134 fn test_channel_conf_timeout() {
8135 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8136 // confirm within 2016 blocks, as recommended by BOLT 2.
8137 let chanmon_cfgs = create_chanmon_cfgs(2);
8138 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8139 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8140 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8142 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8144 // The outbound node should wait forever for confirmation:
8145 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8146 // copied here instead of directly referencing the constant.
8147 connect_blocks(&nodes[0], 2016);
8148 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8150 // The inbound node should fail the channel after exactly 2016 blocks
8151 connect_blocks(&nodes[1], 2015);
8152 check_added_monitors!(nodes[1], 0);
8153 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8155 connect_blocks(&nodes[1], 1);
8156 check_added_monitors!(nodes[1], 1);
8157 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8158 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8159 assert_eq!(close_ev.len(), 1);
8161 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8162 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8163 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8165 _ => panic!("Unexpected event"),
8170 fn test_override_channel_config() {
8171 let chanmon_cfgs = create_chanmon_cfgs(2);
8172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8174 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8176 // Node0 initiates a channel to node1 using the override config.
8177 let mut override_config = UserConfig::default();
8178 override_config.own_channel_config.our_to_self_delay = 200;
8180 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8182 // Assert the channel created by node0 is using the override config.
8183 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8184 assert_eq!(res.channel_flags, 0);
8185 assert_eq!(res.to_self_delay, 200);
8189 fn test_override_0msat_htlc_minimum() {
8190 let mut zero_config = UserConfig::default();
8191 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8192 let chanmon_cfgs = create_chanmon_cfgs(2);
8193 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8194 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8195 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8197 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8198 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8199 assert_eq!(res.htlc_minimum_msat, 1);
8201 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8202 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8203 assert_eq!(res.htlc_minimum_msat, 1);
8207 fn test_simple_mpp() {
8208 // Simple test of sending a multi-path payment.
8209 let chanmon_cfgs = create_chanmon_cfgs(4);
8210 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8211 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8212 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8214 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8215 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8216 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8217 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8219 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8220 let path = route.paths[0].clone();
8221 route.paths.push(path);
8222 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8223 route.paths[0][0].short_channel_id = chan_1_id;
8224 route.paths[0][1].short_channel_id = chan_3_id;
8225 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8226 route.paths[1][0].short_channel_id = chan_2_id;
8227 route.paths[1][1].short_channel_id = chan_4_id;
8228 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8229 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8233 fn test_preimage_storage() {
8234 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8235 let chanmon_cfgs = create_chanmon_cfgs(2);
8236 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8237 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8238 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8240 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8243 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8244 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8245 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8246 check_added_monitors!(nodes[0], 1);
8247 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8248 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8249 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8250 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8252 // Note that after leaving the above scope we have no knowledge of any arguments or return
8253 // values from previous calls.
8254 expect_pending_htlcs_forwardable!(nodes[1]);
8255 let events = nodes[1].node.get_and_clear_pending_events();
8256 assert_eq!(events.len(), 1);
8258 Event::PaymentReceived { ref purpose, .. } => {
8260 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8261 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8263 _ => panic!("expected PaymentPurpose::InvoicePayment")
8266 _ => panic!("Unexpected event"),
8271 #[allow(deprecated)]
8272 fn test_secret_timeout() {
8273 // Simple test of payment secret storage time outs. After
8274 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8275 let chanmon_cfgs = create_chanmon_cfgs(2);
8276 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8277 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8278 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8280 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8282 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8284 // We should fail to register the same payment hash twice, at least until we've connected a
8285 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8286 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8287 assert_eq!(err, "Duplicate payment hash");
8288 } else { panic!(); }
8290 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8292 header: BlockHeader {
8294 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8295 merkle_root: Default::default(),
8296 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8300 connect_block(&nodes[1], &block);
8301 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8302 assert_eq!(err, "Duplicate payment hash");
8303 } else { panic!(); }
8305 // If we then connect the second block, we should be able to register the same payment hash
8306 // again (this time getting a new payment secret).
8307 block.header.prev_blockhash = block.header.block_hash();
8308 block.header.time += 1;
8309 connect_block(&nodes[1], &block);
8310 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8311 assert_ne!(payment_secret_1, our_payment_secret);
8314 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8315 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8316 check_added_monitors!(nodes[0], 1);
8317 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8318 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8320 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8322 // Note that after leaving the above scope we have no knowledge of any arguments or return
8323 // values from previous calls.
8324 expect_pending_htlcs_forwardable!(nodes[1]);
8325 let events = nodes[1].node.get_and_clear_pending_events();
8326 assert_eq!(events.len(), 1);
8328 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8329 assert!(payment_preimage.is_none());
8330 assert_eq!(payment_secret, our_payment_secret);
8331 // We don't actually have the payment preimage with which to claim this payment!
8333 _ => panic!("Unexpected event"),
8338 fn test_bad_secret_hash() {
8339 // Simple test of unregistered payment hash/invalid payment secret handling
8340 let chanmon_cfgs = create_chanmon_cfgs(2);
8341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8343 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8345 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8347 let random_payment_hash = PaymentHash([42; 32]);
8348 let random_payment_secret = PaymentSecret([43; 32]);
8349 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8350 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8352 // All the below cases should end up being handled exactly identically, so we macro the
8353 // resulting events.
8354 macro_rules! handle_unknown_invalid_payment_data {
8356 check_added_monitors!(nodes[0], 1);
8357 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8358 let payment_event = SendEvent::from_event(events.pop().unwrap());
8359 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8360 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8362 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8363 // again to process the pending backwards-failure of the HTLC
8364 expect_pending_htlcs_forwardable!(nodes[1]);
8365 expect_pending_htlcs_forwardable!(nodes[1]);
8366 check_added_monitors!(nodes[1], 1);
8368 // We should fail the payment back
8369 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8370 match events.pop().unwrap() {
8371 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8372 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8373 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8375 _ => panic!("Unexpected event"),
8380 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8381 // Error data is the HTLC value (100,000) and current block height
8382 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8384 // Send a payment with the right payment hash but the wrong payment secret
8385 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8386 handle_unknown_invalid_payment_data!();
8387 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8389 // Send a payment with a random payment hash, but the right payment secret
8390 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8391 handle_unknown_invalid_payment_data!();
8392 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8394 // Send a payment with a random payment hash and random payment secret
8395 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8396 handle_unknown_invalid_payment_data!();
8397 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8401 fn test_update_err_monitor_lockdown() {
8402 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8403 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8404 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8406 // This scenario may happen in a watchtower setup, where watchtower process a block height
8407 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8408 // commitment at same time.
8410 let chanmon_cfgs = create_chanmon_cfgs(2);
8411 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8412 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8413 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8415 // Create some initial channel
8416 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8417 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8419 // Rebalance the network to generate htlc in the two directions
8420 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8422 // Route a HTLC from node 0 to node 1 (but don't settle)
8423 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8425 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8426 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8427 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8428 let persister = test_utils::TestPersister::new();
8430 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8431 let mut w = test_utils::TestVecWriter(Vec::new());
8432 monitor.write(&mut w).unwrap();
8433 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8434 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8435 assert!(new_monitor == *monitor);
8436 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);
8437 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8440 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8441 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8442 // transaction lock time requirements here.
8443 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8444 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8446 // Try to update ChannelMonitor
8447 assert!(nodes[1].node.claim_funds(preimage));
8448 check_added_monitors!(nodes[1], 1);
8449 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8450 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8451 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8452 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8453 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8454 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8455 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8456 } else { assert!(false); }
8457 } else { assert!(false); };
8458 // Our local monitor is in-sync and hasn't processed yet timeout
8459 check_added_monitors!(nodes[0], 1);
8460 let events = nodes[0].node.get_and_clear_pending_events();
8461 assert_eq!(events.len(), 1);
8465 fn test_concurrent_monitor_claim() {
8466 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8467 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8468 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8469 // state N+1 confirms. Alice claims output from state N+1.
8471 let chanmon_cfgs = create_chanmon_cfgs(2);
8472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8474 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8476 // Create some initial channel
8477 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8478 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8480 // Rebalance the network to generate htlc in the two directions
8481 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8483 // Route a HTLC from node 0 to node 1 (but don't settle)
8484 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8486 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8487 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8488 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8489 let persister = test_utils::TestPersister::new();
8490 let watchtower_alice = {
8491 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8492 let mut w = test_utils::TestVecWriter(Vec::new());
8493 monitor.write(&mut w).unwrap();
8494 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8495 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8496 assert!(new_monitor == *monitor);
8497 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);
8498 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8501 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8502 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8503 // transaction lock time requirements here.
8504 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8505 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8507 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8509 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8510 assert_eq!(txn.len(), 2);
8514 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8515 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8516 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8517 let persister = test_utils::TestPersister::new();
8518 let watchtower_bob = {
8519 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8520 let mut w = test_utils::TestVecWriter(Vec::new());
8521 monitor.write(&mut w).unwrap();
8522 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8523 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8524 assert!(new_monitor == *monitor);
8525 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);
8526 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8529 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8530 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8532 // Route another payment to generate another update with still previous HTLC pending
8533 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8535 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8537 check_added_monitors!(nodes[1], 1);
8539 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8540 assert_eq!(updates.update_add_htlcs.len(), 1);
8541 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8542 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8543 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8544 // Watchtower Alice should already have seen the block and reject the update
8545 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8546 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8547 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8548 } else { assert!(false); }
8549 } else { assert!(false); };
8550 // Our local monitor is in-sync and hasn't processed yet timeout
8551 check_added_monitors!(nodes[0], 1);
8553 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8554 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8555 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8557 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8560 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8561 assert_eq!(txn.len(), 2);
8562 bob_state_y = txn[0].clone();
8566 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8567 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8568 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);
8570 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8571 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8572 // the onchain detection of the HTLC output
8573 assert_eq!(htlc_txn.len(), 2);
8574 check_spends!(htlc_txn[0], bob_state_y);
8575 check_spends!(htlc_txn[1], bob_state_y);
8580 fn test_pre_lockin_no_chan_closed_update() {
8581 // Test that if a peer closes a channel in response to a funding_created message we don't
8582 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8585 // Doing so would imply a channel monitor update before the initial channel monitor
8586 // registration, violating our API guarantees.
8588 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8589 // then opening a second channel with the same funding output as the first (which is not
8590 // rejected because the first channel does not exist in the ChannelManager) and closing it
8591 // before receiving funding_signed.
8592 let chanmon_cfgs = create_chanmon_cfgs(2);
8593 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8594 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8595 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8597 // Create an initial channel
8598 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8599 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8600 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8601 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8602 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8604 // Move the first channel through the funding flow...
8605 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8607 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8608 check_added_monitors!(nodes[0], 0);
8610 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8611 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8612 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8613 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8614 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8618 fn test_htlc_no_detection() {
8619 // This test is a mutation to underscore the detection logic bug we had
8620 // before #653. HTLC value routed is above the remaining balance, thus
8621 // inverting HTLC and `to_remote` output. HTLC will come second and
8622 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8623 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8624 // outputs order detection for correct spending children filtring.
8626 let chanmon_cfgs = create_chanmon_cfgs(2);
8627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8629 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8631 // Create some initial channels
8632 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8634 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8635 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8636 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8637 assert_eq!(local_txn[0].input.len(), 1);
8638 assert_eq!(local_txn[0].output.len(), 3);
8639 check_spends!(local_txn[0], chan_1.3);
8641 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8642 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8643 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8644 // We deliberately connect the local tx twice as this should provoke a failure calling
8645 // this test before #653 fix.
8646 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);
8647 check_closed_broadcast!(nodes[0], true);
8648 check_added_monitors!(nodes[0], 1);
8649 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8650 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8652 let htlc_timeout = {
8653 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8654 assert_eq!(node_txn[1].input.len(), 1);
8655 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8656 check_spends!(node_txn[1], local_txn[0]);
8660 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8661 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8662 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8663 expect_payment_failed!(nodes[0], our_payment_hash, true);
8666 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8667 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8668 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8669 // Carol, Alice would be the upstream node, and Carol the downstream.)
8671 // Steps of the test:
8672 // 1) Alice sends a HTLC to Carol through Bob.
8673 // 2) Carol doesn't settle the HTLC.
8674 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8675 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8676 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8677 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8678 // 5) Carol release the preimage to Bob off-chain.
8679 // 6) Bob claims the offered output on the broadcasted commitment.
8680 let chanmon_cfgs = create_chanmon_cfgs(3);
8681 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8682 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8683 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8685 // Create some initial channels
8686 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8687 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8689 // Steps (1) and (2):
8690 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8691 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8693 // Check that Alice's commitment transaction now contains an output for this HTLC.
8694 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8695 check_spends!(alice_txn[0], chan_ab.3);
8696 assert_eq!(alice_txn[0].output.len(), 2);
8697 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8698 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8699 assert_eq!(alice_txn.len(), 2);
8701 // Steps (3) and (4):
8702 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8703 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8704 let mut force_closing_node = 0; // Alice force-closes
8705 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8706 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8707 check_closed_broadcast!(nodes[force_closing_node], true);
8708 check_added_monitors!(nodes[force_closing_node], 1);
8709 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8710 if go_onchain_before_fulfill {
8711 let txn_to_broadcast = match broadcast_alice {
8712 true => alice_txn.clone(),
8713 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8715 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8716 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8717 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8718 if broadcast_alice {
8719 check_closed_broadcast!(nodes[1], true);
8720 check_added_monitors!(nodes[1], 1);
8721 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8723 assert_eq!(bob_txn.len(), 1);
8724 check_spends!(bob_txn[0], chan_ab.3);
8728 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8729 // process of removing the HTLC from their commitment transactions.
8730 assert!(nodes[2].node.claim_funds(payment_preimage));
8731 check_added_monitors!(nodes[2], 1);
8732 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8733 assert!(carol_updates.update_add_htlcs.is_empty());
8734 assert!(carol_updates.update_fail_htlcs.is_empty());
8735 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8736 assert!(carol_updates.update_fee.is_none());
8737 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8739 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8740 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8741 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8742 if !go_onchain_before_fulfill && broadcast_alice {
8743 let events = nodes[1].node.get_and_clear_pending_msg_events();
8744 assert_eq!(events.len(), 1);
8746 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8747 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8749 _ => panic!("Unexpected event"),
8752 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8753 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8754 // Carol<->Bob's updated commitment transaction info.
8755 check_added_monitors!(nodes[1], 2);
8757 let events = nodes[1].node.get_and_clear_pending_msg_events();
8758 assert_eq!(events.len(), 2);
8759 let bob_revocation = match events[0] {
8760 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8761 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8764 _ => panic!("Unexpected event"),
8766 let bob_updates = match events[1] {
8767 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8768 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8771 _ => panic!("Unexpected event"),
8774 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8775 check_added_monitors!(nodes[2], 1);
8776 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8777 check_added_monitors!(nodes[2], 1);
8779 let events = nodes[2].node.get_and_clear_pending_msg_events();
8780 assert_eq!(events.len(), 1);
8781 let carol_revocation = match events[0] {
8782 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8783 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8786 _ => panic!("Unexpected event"),
8788 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8789 check_added_monitors!(nodes[1], 1);
8791 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8792 // here's where we put said channel's commitment tx on-chain.
8793 let mut txn_to_broadcast = alice_txn.clone();
8794 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8795 if !go_onchain_before_fulfill {
8796 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8797 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8798 // If Bob was the one to force-close, he will have already passed these checks earlier.
8799 if broadcast_alice {
8800 check_closed_broadcast!(nodes[1], true);
8801 check_added_monitors!(nodes[1], 1);
8802 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8804 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8805 if broadcast_alice {
8806 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8807 // new block being connected. The ChannelManager being notified triggers a monitor update,
8808 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8809 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8811 assert_eq!(bob_txn.len(), 3);
8812 check_spends!(bob_txn[1], chan_ab.3);
8814 assert_eq!(bob_txn.len(), 2);
8815 check_spends!(bob_txn[0], chan_ab.3);
8820 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8821 // broadcasted commitment transaction.
8823 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8824 if go_onchain_before_fulfill {
8825 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8826 assert_eq!(bob_txn.len(), 2);
8828 let script_weight = match broadcast_alice {
8829 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8830 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8832 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8833 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8834 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8835 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8836 if broadcast_alice && !go_onchain_before_fulfill {
8837 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8838 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8840 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8841 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8847 fn test_onchain_htlc_settlement_after_close() {
8848 do_test_onchain_htlc_settlement_after_close(true, true);
8849 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8850 do_test_onchain_htlc_settlement_after_close(true, false);
8851 do_test_onchain_htlc_settlement_after_close(false, false);
8855 fn test_duplicate_chan_id() {
8856 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8857 // already open we reject it and keep the old channel.
8859 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8860 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8861 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8862 // updating logic for the existing channel.
8863 let chanmon_cfgs = create_chanmon_cfgs(2);
8864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8868 // Create an initial channel
8869 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8870 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8871 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8872 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()));
8874 // Try to create a second channel with the same temporary_channel_id as the first and check
8875 // that it is rejected.
8876 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8878 let events = nodes[1].node.get_and_clear_pending_msg_events();
8879 assert_eq!(events.len(), 1);
8881 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8882 // Technically, at this point, nodes[1] would be justified in thinking both the
8883 // first (valid) and second (invalid) channels are closed, given they both have
8884 // the same non-temporary channel_id. However, currently we do not, so we just
8885 // move forward with it.
8886 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8887 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8889 _ => panic!("Unexpected event"),
8893 // Move the first channel through the funding flow...
8894 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8896 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8897 check_added_monitors!(nodes[0], 0);
8899 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8900 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8902 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8903 assert_eq!(added_monitors.len(), 1);
8904 assert_eq!(added_monitors[0].0, funding_output);
8905 added_monitors.clear();
8907 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8909 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8910 let channel_id = funding_outpoint.to_channel_id();
8912 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8915 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8916 // Technically this is allowed by the spec, but we don't support it and there's little reason
8917 // to. Still, it shouldn't cause any other issues.
8918 open_chan_msg.temporary_channel_id = channel_id;
8919 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8921 let events = nodes[1].node.get_and_clear_pending_msg_events();
8922 assert_eq!(events.len(), 1);
8924 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8925 // Technically, at this point, nodes[1] would be justified in thinking both
8926 // channels are closed, but currently we do not, so we just move forward with it.
8927 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8928 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8930 _ => panic!("Unexpected event"),
8934 // Now try to create a second channel which has a duplicate funding output.
8935 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8936 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8937 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8938 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()));
8939 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8941 let funding_created = {
8942 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8943 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8944 let logger = test_utils::TestLogger::new();
8945 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8947 check_added_monitors!(nodes[0], 0);
8948 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8949 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8950 // still needs to be cleared here.
8951 check_added_monitors!(nodes[1], 1);
8953 // ...still, nodes[1] will reject the duplicate channel.
8955 let events = nodes[1].node.get_and_clear_pending_msg_events();
8956 assert_eq!(events.len(), 1);
8958 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8959 // Technically, at this point, nodes[1] would be justified in thinking both
8960 // channels are closed, but currently we do not, so we just move forward with it.
8961 assert_eq!(msg.channel_id, channel_id);
8962 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8964 _ => panic!("Unexpected event"),
8968 // finally, finish creating the original channel and send a payment over it to make sure
8969 // everything is functional.
8970 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8972 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8973 assert_eq!(added_monitors.len(), 1);
8974 assert_eq!(added_monitors[0].0, funding_output);
8975 added_monitors.clear();
8978 let events_4 = nodes[0].node.get_and_clear_pending_events();
8979 assert_eq!(events_4.len(), 0);
8980 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8981 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8983 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8984 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8985 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8986 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8990 fn test_error_chans_closed() {
8991 // Test that we properly handle error messages, closing appropriate channels.
8993 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8994 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8995 // we can test various edge cases around it to ensure we don't regress.
8996 let chanmon_cfgs = create_chanmon_cfgs(3);
8997 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8998 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8999 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9001 // Create some initial channels
9002 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9003 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9004 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9006 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9007 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9008 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9010 // Closing a channel from a different peer has no effect
9011 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9012 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9014 // Closing one channel doesn't impact others
9015 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9016 check_added_monitors!(nodes[0], 1);
9017 check_closed_broadcast!(nodes[0], false);
9018 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9019 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9020 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9021 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);
9022 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);
9024 // A null channel ID should close all channels
9025 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9026 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9027 check_added_monitors!(nodes[0], 2);
9028 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9029 let events = nodes[0].node.get_and_clear_pending_msg_events();
9030 assert_eq!(events.len(), 2);
9032 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9033 assert_eq!(msg.contents.flags & 2, 2);
9035 _ => panic!("Unexpected event"),
9038 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9039 assert_eq!(msg.contents.flags & 2, 2);
9041 _ => panic!("Unexpected event"),
9043 // Note that at this point users of a standard PeerHandler will end up calling
9044 // peer_disconnected with no_connection_possible set to false, duplicating the
9045 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9046 // users with their own peer handling logic. We duplicate the call here, however.
9047 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9048 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9050 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9051 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9052 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9056 fn test_invalid_funding_tx() {
9057 // Test that we properly handle invalid funding transactions sent to us from a peer.
9059 // Previously, all other major lightning implementations had failed to properly sanitize
9060 // funding transactions from their counterparties, leading to a multi-implementation critical
9061 // security vulnerability (though we always sanitized properly, we've previously had
9062 // un-released crashes in the sanitization process).
9063 let chanmon_cfgs = create_chanmon_cfgs(2);
9064 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9065 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9066 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9068 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9069 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()));
9070 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()));
9072 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9073 for output in tx.output.iter_mut() {
9074 // Make the confirmed funding transaction have a bogus script_pubkey
9075 output.script_pubkey = bitcoin::Script::new();
9078 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9079 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()));
9080 check_added_monitors!(nodes[1], 1);
9082 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()));
9083 check_added_monitors!(nodes[0], 1);
9085 let events_1 = nodes[0].node.get_and_clear_pending_events();
9086 assert_eq!(events_1.len(), 0);
9088 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9089 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9090 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9092 let expected_err = "funding tx had wrong script/value or output index";
9093 confirm_transaction_at(&nodes[1], &tx, 1);
9094 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9095 check_added_monitors!(nodes[1], 1);
9096 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9097 assert_eq!(events_2.len(), 1);
9098 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9099 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9100 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9101 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9102 } else { panic!(); }
9103 } else { panic!(); }
9104 assert_eq!(nodes[1].node.list_channels().len(), 0);
9107 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9108 // In the first version of the chain::Confirm interface, after a refactor was made to not
9109 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9110 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9111 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9112 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9113 // spending transaction until height N+1 (or greater). This was due to the way
9114 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9115 // spending transaction at the height the input transaction was confirmed at, not whether we
9116 // should broadcast a spending transaction at the current height.
9117 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9118 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9119 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9120 // until we learned about an additional block.
9122 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9123 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9124 let chanmon_cfgs = create_chanmon_cfgs(3);
9125 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9126 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9127 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9128 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9130 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9131 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9132 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9133 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9134 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9136 nodes[1].node.force_close_channel(&channel_id).unwrap();
9137 check_closed_broadcast!(nodes[1], true);
9138 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9139 check_added_monitors!(nodes[1], 1);
9140 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9141 assert_eq!(node_txn.len(), 1);
9143 let conf_height = nodes[1].best_block_info().1;
9144 if !test_height_before_timelock {
9145 connect_blocks(&nodes[1], 24 * 6);
9147 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9148 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9149 if test_height_before_timelock {
9150 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9151 // generate any events or broadcast any transactions
9152 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9153 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9155 // We should broadcast an HTLC transaction spending our funding transaction first
9156 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9157 assert_eq!(spending_txn.len(), 2);
9158 assert_eq!(spending_txn[0], node_txn[0]);
9159 check_spends!(spending_txn[1], node_txn[0]);
9160 // We should also generate a SpendableOutputs event with the to_self output (as its
9162 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9163 assert_eq!(descriptor_spend_txn.len(), 1);
9165 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9166 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9167 // additional block built on top of the current chain.
9168 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9169 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9170 expect_pending_htlcs_forwardable!(nodes[1]);
9171 check_added_monitors!(nodes[1], 1);
9173 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9174 assert!(updates.update_add_htlcs.is_empty());
9175 assert!(updates.update_fulfill_htlcs.is_empty());
9176 assert_eq!(updates.update_fail_htlcs.len(), 1);
9177 assert!(updates.update_fail_malformed_htlcs.is_empty());
9178 assert!(updates.update_fee.is_none());
9179 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9180 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9181 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9186 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9187 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9188 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9192 fn test_forwardable_regen() {
9193 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9194 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9196 // We test it for both payment receipt and payment forwarding.
9198 let chanmon_cfgs = create_chanmon_cfgs(3);
9199 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9200 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9201 let persister: test_utils::TestPersister;
9202 let new_chain_monitor: test_utils::TestChainMonitor;
9203 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9204 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9205 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9206 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9208 // First send a payment to nodes[1]
9209 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9210 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9211 check_added_monitors!(nodes[0], 1);
9213 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9214 assert_eq!(events.len(), 1);
9215 let payment_event = SendEvent::from_event(events.pop().unwrap());
9216 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9217 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9219 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9221 // Next send a payment which is forwarded by nodes[1]
9222 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9223 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9224 check_added_monitors!(nodes[0], 1);
9226 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9227 assert_eq!(events.len(), 1);
9228 let payment_event = SendEvent::from_event(events.pop().unwrap());
9229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9230 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9232 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9234 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9236 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9237 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9238 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9240 let nodes_1_serialized = nodes[1].node.encode();
9241 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9242 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9243 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9244 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9246 persister = test_utils::TestPersister::new();
9247 let keys_manager = &chanmon_cfgs[1].keys_manager;
9248 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);
9249 nodes[1].chain_monitor = &new_chain_monitor;
9251 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9252 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9253 &mut chan_0_monitor_read, keys_manager).unwrap();
9254 assert!(chan_0_monitor_read.is_empty());
9255 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9256 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9257 &mut chan_1_monitor_read, keys_manager).unwrap();
9258 assert!(chan_1_monitor_read.is_empty());
9260 let mut nodes_1_read = &nodes_1_serialized[..];
9261 let (_, nodes_1_deserialized_tmp) = {
9262 let mut channel_monitors = HashMap::new();
9263 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9264 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9265 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9266 default_config: UserConfig::default(),
9268 fee_estimator: node_cfgs[1].fee_estimator,
9269 chain_monitor: nodes[1].chain_monitor,
9270 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9271 logger: nodes[1].logger,
9275 nodes_1_deserialized = nodes_1_deserialized_tmp;
9276 assert!(nodes_1_read.is_empty());
9278 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9279 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9280 nodes[1].node = &nodes_1_deserialized;
9281 check_added_monitors!(nodes[1], 2);
9283 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9284 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9285 // the commitment state.
9286 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9288 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9290 expect_pending_htlcs_forwardable!(nodes[1]);
9291 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9292 check_added_monitors!(nodes[1], 1);
9294 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9295 assert_eq!(events.len(), 1);
9296 let payment_event = SendEvent::from_event(events.pop().unwrap());
9297 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9298 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9299 expect_pending_htlcs_forwardable!(nodes[2]);
9300 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9302 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9303 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9307 fn test_keysend_payments_to_public_node() {
9308 let chanmon_cfgs = create_chanmon_cfgs(2);
9309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9311 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9313 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9314 let network_graph = nodes[0].network_graph;
9315 let payer_pubkey = nodes[0].node.get_our_node_id();
9316 let payee_pubkey = nodes[1].node.get_our_node_id();
9317 let params = RouteParameters {
9318 payee: Payee::for_keysend(payee_pubkey),
9319 final_value_msat: 10000,
9320 final_cltv_expiry_delta: 40,
9322 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9323 let route = find_route(&payer_pubkey, ¶ms, network_graph, None, nodes[0].logger, &scorer).unwrap();
9325 let test_preimage = PaymentPreimage([42; 32]);
9326 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9327 check_added_monitors!(nodes[0], 1);
9328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9329 assert_eq!(events.len(), 1);
9330 let event = events.pop().unwrap();
9331 let path = vec![&nodes[1]];
9332 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9333 claim_payment(&nodes[0], &path, test_preimage);
9337 fn test_keysend_payments_to_private_node() {
9338 let chanmon_cfgs = create_chanmon_cfgs(2);
9339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9341 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9343 let payer_pubkey = nodes[0].node.get_our_node_id();
9344 let payee_pubkey = nodes[1].node.get_our_node_id();
9345 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9346 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9348 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9349 let params = RouteParameters {
9350 payee: Payee::for_keysend(payee_pubkey),
9351 final_value_msat: 10000,
9352 final_cltv_expiry_delta: 40,
9354 let network_graph = nodes[0].network_graph;
9355 let first_hops = nodes[0].node.list_usable_channels();
9356 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9357 let route = find_route(
9358 &payer_pubkey, ¶ms, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9359 nodes[0].logger, &scorer
9362 let test_preimage = PaymentPreimage([42; 32]);
9363 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9364 check_added_monitors!(nodes[0], 1);
9365 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9366 assert_eq!(events.len(), 1);
9367 let event = events.pop().unwrap();
9368 let path = vec![&nodes[1]];
9369 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9370 claim_payment(&nodes[0], &path, test_preimage);
9373 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9374 #[derive(Clone, Copy, PartialEq)]
9375 enum ExposureEvent {
9376 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9378 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9380 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9381 AtUpdateFeeOutbound,
9384 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9385 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9388 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9389 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9390 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9391 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9392 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9393 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9394 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9395 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9397 let chanmon_cfgs = create_chanmon_cfgs(2);
9398 let mut config = test_default_channel_config();
9399 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9402 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9404 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9405 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9406 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9407 open_channel.max_accepted_htlcs = 60;
9409 open_channel.dust_limit_satoshis = 546;
9411 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9412 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9413 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9415 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9418 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9419 chan.holder_dust_limit_satoshis = 546;
9423 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9424 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()));
9425 check_added_monitors!(nodes[1], 1);
9427 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()));
9428 check_added_monitors!(nodes[0], 1);
9430 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9431 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9432 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9434 let dust_buffer_feerate = {
9435 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9436 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9437 chan.get_dust_buffer_feerate(None) as u64
9439 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_TIMEOUT_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9440 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9442 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_SUCCESS_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9443 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9445 let dust_htlc_on_counterparty_tx: u64 = 25;
9446 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9449 if dust_outbound_balance {
9450 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9451 // Outbound dust balance: 4372 sats
9452 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9453 for i in 0..dust_outbound_htlc_on_holder_tx {
9454 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9455 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9458 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9459 // Inbound dust balance: 4372 sats
9460 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9461 for _ in 0..dust_inbound_htlc_on_holder_tx {
9462 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9466 if dust_outbound_balance {
9467 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9468 // Outbound dust balance: 5000 sats
9469 for i in 0..dust_htlc_on_counterparty_tx {
9470 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9471 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9474 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9475 // Inbound dust balance: 5000 sats
9476 for _ in 0..dust_htlc_on_counterparty_tx {
9477 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9482 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9483 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9484 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 });
9485 let mut config = UserConfig::default();
9486 // With default dust exposure: 5000 sats
9488 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9489 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9490 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)));
9492 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)));
9494 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9495 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 });
9496 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9497 check_added_monitors!(nodes[1], 1);
9498 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9499 assert_eq!(events.len(), 1);
9500 let payment_event = SendEvent::from_event(events.remove(0));
9501 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9502 // With default dust exposure: 5000 sats
9504 // Outbound dust balance: 6399 sats
9505 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9506 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9507 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);
9509 // Outbound dust balance: 5200 sats
9510 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);
9512 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9513 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9514 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9516 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9517 *feerate_lock = *feerate_lock * 10;
9519 nodes[0].node.timer_tick_occurred();
9520 check_added_monitors!(nodes[0], 1);
9521 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);
9524 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9525 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9526 added_monitors.clear();
9530 fn test_max_dust_htlc_exposure() {
9531 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9532 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9533 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9534 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9535 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9536 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9537 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9538 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9539 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9540 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9541 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9542 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);