1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
59 fn test_insane_channel_opens() {
60 // Stand up a network of 2 nodes
61 let chanmon_cfgs = create_chanmon_cfgs(2);
62 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
63 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
64 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
66 // Instantiate channel parameters where we push the maximum msats given our
68 let channel_value_sat = 31337; // same as funding satoshis
69 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
70 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
72 // Have node0 initiate a channel to node1 with aforementioned parameters
73 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
75 // Extract the channel open message from node0 to node1
76 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
78 // Test helper that asserts we get the correct error string given a mutator
79 // that supposedly makes the channel open message insane
80 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
81 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
82 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
83 assert_eq!(msg_events.len(), 1);
84 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
85 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
87 &ErrorAction::SendErrorMessage { .. } => {
88 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
90 _ => panic!("unexpected event!"),
92 } else { assert!(false); }
95 use ln::channel::MAX_FUNDING_SATOSHIS;
96 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
98 // Test all mutations that would make the channel open message insane
99 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
101 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
103 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
105 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
107 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
109 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
111 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
113 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
116 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
117 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
118 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
119 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
120 // in normal testing, we test it explicitly here.
121 let chanmon_cfgs = create_chanmon_cfgs(2);
122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126 // Have node0 initiate a channel to node1 with aforementioned parameters
127 let mut push_amt = 100_000_000;
128 let feerate_per_kw = 253;
129 let opt_anchors = false;
130 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
131 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
133 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
134 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
135 if !send_from_initiator {
136 open_channel_message.channel_reserve_satoshis = 0;
137 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
139 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
141 // Extract the channel accept message from node1 to node0
142 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
143 if send_from_initiator {
144 accept_channel_message.channel_reserve_satoshis = 0;
145 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
147 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
150 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
151 chan.holder_selected_channel_reserve_satoshis = 0;
152 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
155 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
156 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
157 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
159 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
160 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
161 if send_from_initiator {
162 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
163 // Note that for outbound channels we have to consider the commitment tx fee and the
164 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
165 // well as an additional HTLC.
166 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
168 send_payment(&nodes[1], &[&nodes[0]], push_amt);
173 fn test_counterparty_no_reserve() {
174 do_test_counterparty_no_reserve(true);
175 do_test_counterparty_no_reserve(false);
179 fn test_async_inbound_update_fee() {
180 let chanmon_cfgs = create_chanmon_cfgs(2);
181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
184 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
187 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
191 // send (1) commitment_signed -.
192 // <- update_add_htlc/commitment_signed
193 // send (2) RAA (awaiting remote revoke) -.
194 // (1) commitment_signed is delivered ->
195 // .- send (3) RAA (awaiting remote revoke)
196 // (2) RAA is delivered ->
197 // .- send (4) commitment_signed
198 // <- (3) RAA is delivered
199 // send (5) commitment_signed -.
200 // <- (4) commitment_signed is delivered
202 // (5) commitment_signed is delivered ->
204 // (6) RAA is delivered ->
206 // First nodes[0] generates an update_fee
208 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
211 nodes[0].node.timer_tick_occurred();
212 check_added_monitors!(nodes[0], 1);
214 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
215 assert_eq!(events_0.len(), 1);
216 let (update_msg, commitment_signed) = match events_0[0] { // (1)
217 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
218 (update_fee.as_ref(), commitment_signed)
220 _ => panic!("Unexpected event"),
223 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
225 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
226 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
227 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
228 check_added_monitors!(nodes[1], 1);
230 let payment_event = {
231 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
232 assert_eq!(events_1.len(), 1);
233 SendEvent::from_event(events_1.remove(0))
235 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
236 assert_eq!(payment_event.msgs.len(), 1);
238 // ...now when the messages get delivered everyone should be happy
239 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
240 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
241 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
242 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
243 check_added_monitors!(nodes[0], 1);
245 // deliver(1), generate (3):
246 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
247 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
248 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
249 check_added_monitors!(nodes[1], 1);
251 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
252 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
253 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
254 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
255 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
256 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
257 assert!(bs_update.update_fee.is_none()); // (4)
258 check_added_monitors!(nodes[1], 1);
260 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
261 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
262 assert!(as_update.update_add_htlcs.is_empty()); // (5)
263 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
264 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
265 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
266 assert!(as_update.update_fee.is_none()); // (5)
267 check_added_monitors!(nodes[0], 1);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
270 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // only (6) so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
275 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
276 check_added_monitors!(nodes[1], 1);
278 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
279 check_added_monitors!(nodes[0], 1);
281 let events_2 = nodes[0].node.get_and_clear_pending_events();
282 assert_eq!(events_2.len(), 1);
284 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
285 _ => panic!("Unexpected event"),
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
289 check_added_monitors!(nodes[1], 1);
293 fn test_update_fee_unordered_raa() {
294 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
295 // crash in an earlier version of the update_fee patch)
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
303 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
305 // First nodes[0] generates an update_fee
307 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
310 nodes[0].node.timer_tick_occurred();
311 check_added_monitors!(nodes[0], 1);
313 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
314 assert_eq!(events_0.len(), 1);
315 let update_msg = match events_0[0] { // (1)
316 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
319 _ => panic!("Unexpected event"),
322 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
324 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
325 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
326 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
327 check_added_monitors!(nodes[1], 1);
329 let payment_event = {
330 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
331 assert_eq!(events_1.len(), 1);
332 SendEvent::from_event(events_1.remove(0))
334 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
335 assert_eq!(payment_event.msgs.len(), 1);
337 // ...now when the messages get delivered everyone should be happy
338 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
339 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
340 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
341 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
342 check_added_monitors!(nodes[0], 1);
344 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
345 check_added_monitors!(nodes[1], 1);
347 // We can't continue, sadly, because our (1) now has a bogus signature
351 fn test_multi_flight_update_fee() {
352 let chanmon_cfgs = create_chanmon_cfgs(2);
353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
356 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
359 // update_fee/commitment_signed ->
360 // .- send (1) RAA and (2) commitment_signed
361 // update_fee (never committed) ->
363 // We have to manually generate the above update_fee, it is allowed by the protocol but we
364 // don't track which updates correspond to which revoke_and_ack responses so we're in
365 // AwaitingRAA mode and will not generate the update_fee yet.
366 // <- (1) RAA delivered
367 // (3) is generated and send (4) CS -.
368 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
369 // know the per_commitment_point to use for it.
370 // <- (2) commitment_signed delivered
372 // B should send no response here
373 // (4) commitment_signed delivered ->
374 // <- RAA/commitment_signed delivered
377 // First nodes[0] generates an update_fee
380 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
381 initial_feerate = *feerate_lock;
382 *feerate_lock = initial_feerate + 20;
384 nodes[0].node.timer_tick_occurred();
385 check_added_monitors!(nodes[0], 1);
387 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
388 assert_eq!(events_0.len(), 1);
389 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
390 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
391 (update_fee.as_ref().unwrap(), commitment_signed)
393 _ => panic!("Unexpected event"),
396 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
397 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
398 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
399 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
400 check_added_monitors!(nodes[1], 1);
402 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
405 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406 *feerate_lock = initial_feerate + 40;
408 nodes[0].node.timer_tick_occurred();
409 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
410 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
412 // Create the (3) update_fee message that nodes[0] will generate before it does...
413 let mut update_msg_2 = msgs::UpdateFee {
414 channel_id: update_msg_1.channel_id.clone(),
415 feerate_per_kw: (initial_feerate + 30) as u32,
418 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
420 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
422 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
424 // Deliver (1), generating (3) and (4)
425 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
426 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
427 check_added_monitors!(nodes[0], 1);
428 assert!(as_second_update.update_add_htlcs.is_empty());
429 assert!(as_second_update.update_fulfill_htlcs.is_empty());
430 assert!(as_second_update.update_fail_htlcs.is_empty());
431 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
432 // Check that the update_fee newly generated matches what we delivered:
433 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
434 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
436 // Deliver (2) commitment_signed
437 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
438 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
439 check_added_monitors!(nodes[0], 1);
440 // No commitment_signed so get_event_msg's assert(len == 1) passes
442 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
443 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
444 check_added_monitors!(nodes[1], 1);
447 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
448 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
449 check_added_monitors!(nodes[1], 1);
451 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
452 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
453 check_added_monitors!(nodes[0], 1);
455 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
456 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
457 // No commitment_signed so get_event_msg's assert(len == 1) passes
458 check_added_monitors!(nodes[0], 1);
460 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
461 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
462 check_added_monitors!(nodes[1], 1);
465 fn do_test_sanity_on_in_flight_opens(steps: u8) {
466 // Previously, we had issues deserializing channels when we hadn't connected the first block
467 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
468 // serialization round-trips and simply do steps towards opening a channel and then drop the
471 let chanmon_cfgs = create_chanmon_cfgs(2);
472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
476 if steps & 0b1000_0000 != 0{
478 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
481 connect_block(&nodes[0], &block);
482 connect_block(&nodes[1], &block);
485 if steps & 0x0f == 0 { return; }
486 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
487 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
489 if steps & 0x0f == 1 { return; }
490 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
491 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
493 if steps & 0x0f == 2 { return; }
494 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
496 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
498 if steps & 0x0f == 3 { return; }
499 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
500 check_added_monitors!(nodes[0], 0);
501 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
503 if steps & 0x0f == 4 { return; }
504 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
506 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
507 assert_eq!(added_monitors.len(), 1);
508 assert_eq!(added_monitors[0].0, funding_output);
509 added_monitors.clear();
511 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
513 if steps & 0x0f == 5 { return; }
514 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
516 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
517 assert_eq!(added_monitors.len(), 1);
518 assert_eq!(added_monitors[0].0, funding_output);
519 added_monitors.clear();
522 let events_4 = nodes[0].node.get_and_clear_pending_events();
523 assert_eq!(events_4.len(), 0);
525 if steps & 0x0f == 6 { return; }
526 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
528 if steps & 0x0f == 7 { return; }
529 confirm_transaction_at(&nodes[0], &tx, 2);
530 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
531 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
535 fn test_sanity_on_in_flight_opens() {
536 do_test_sanity_on_in_flight_opens(0);
537 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
538 do_test_sanity_on_in_flight_opens(1);
539 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
540 do_test_sanity_on_in_flight_opens(2);
541 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
542 do_test_sanity_on_in_flight_opens(3);
543 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
544 do_test_sanity_on_in_flight_opens(4);
545 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
546 do_test_sanity_on_in_flight_opens(5);
547 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
548 do_test_sanity_on_in_flight_opens(6);
549 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
550 do_test_sanity_on_in_flight_opens(7);
551 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
552 do_test_sanity_on_in_flight_opens(8);
553 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
557 fn test_update_fee_vanilla() {
558 let chanmon_cfgs = create_chanmon_cfgs(2);
559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
562 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
565 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
568 nodes[0].node.timer_tick_occurred();
569 check_added_monitors!(nodes[0], 1);
571 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
572 assert_eq!(events_0.len(), 1);
573 let (update_msg, commitment_signed) = match events_0[0] {
574 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
575 (update_fee.as_ref(), commitment_signed)
577 _ => panic!("Unexpected event"),
579 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
581 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
582 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
583 check_added_monitors!(nodes[1], 1);
585 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
586 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
587 check_added_monitors!(nodes[0], 1);
589 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
590 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
591 // No commitment_signed so get_event_msg's assert(len == 1) passes
592 check_added_monitors!(nodes[0], 1);
594 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
595 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
596 check_added_monitors!(nodes[1], 1);
600 fn test_update_fee_that_funder_cannot_afford() {
601 let chanmon_cfgs = create_chanmon_cfgs(2);
602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605 let channel_value = 5000;
607 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
608 let channel_id = chan.2;
609 let secp_ctx = Secp256k1::new();
610 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
612 let opt_anchors = false;
614 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
615 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
616 // calculate two different feerates here - the expected local limit as well as the expected
618 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
619 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
621 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
622 *feerate_lock = feerate;
624 nodes[0].node.timer_tick_occurred();
625 check_added_monitors!(nodes[0], 1);
626 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
628 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
630 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
632 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
634 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
636 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
637 assert_eq!(commitment_tx.output.len(), 2);
638 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
639 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
640 actual_fee = channel_value - actual_fee;
641 assert_eq!(total_fee, actual_fee);
645 // Increment the feerate by a small constant, accounting for rounding errors
646 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
649 nodes[0].node.timer_tick_occurred();
650 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
651 check_added_monitors!(nodes[0], 0);
653 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
655 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
656 // needed to sign the new commitment tx and (2) sign the new commitment tx.
657 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
658 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
659 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
660 let chan_signer = local_chan.get_signer();
661 let pubkeys = chan_signer.pubkeys();
662 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
663 pubkeys.funding_pubkey)
665 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
666 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
667 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
668 let chan_signer = remote_chan.get_signer();
669 let pubkeys = chan_signer.pubkeys();
670 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
671 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
672 pubkeys.funding_pubkey)
675 // Assemble the set of keys we can use for signatures for our commitment_signed message.
676 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
677 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
680 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
681 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
682 let local_chan_signer = local_chan.get_signer();
683 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
684 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
685 INITIAL_COMMITMENT_NUMBER - 1,
687 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
688 opt_anchors, local_funding, remote_funding,
689 commit_tx_keys.clone(),
690 non_buffer_feerate + 4,
692 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
694 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
697 let commit_signed_msg = msgs::CommitmentSigned {
700 htlc_signatures: res.1
703 let update_fee = msgs::UpdateFee {
705 feerate_per_kw: non_buffer_feerate + 4,
708 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
710 //While producing the commitment_signed response after handling a received update_fee request the
711 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
712 //Should produce and error.
713 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
714 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
715 check_added_monitors!(nodes[1], 1);
716 check_closed_broadcast!(nodes[1], true);
717 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
721 fn test_update_fee_with_fundee_update_add_htlc() {
722 let chanmon_cfgs = create_chanmon_cfgs(2);
723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
725 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
726 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
729 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
732 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
735 nodes[0].node.timer_tick_occurred();
736 check_added_monitors!(nodes[0], 1);
738 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
739 assert_eq!(events_0.len(), 1);
740 let (update_msg, commitment_signed) = match events_0[0] {
741 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
742 (update_fee.as_ref(), commitment_signed)
744 _ => panic!("Unexpected event"),
746 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
748 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
749 check_added_monitors!(nodes[1], 1);
751 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
753 // nothing happens since node[1] is in AwaitingRemoteRevoke
754 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
756 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
757 assert_eq!(added_monitors.len(), 0);
758 added_monitors.clear();
760 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
761 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762 // node[1] has nothing to do
764 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
765 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
766 check_added_monitors!(nodes[0], 1);
768 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
769 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
770 // No commitment_signed so get_event_msg's assert(len == 1) passes
771 check_added_monitors!(nodes[0], 1);
772 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
773 check_added_monitors!(nodes[1], 1);
774 // AwaitingRemoteRevoke ends here
776 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
777 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
778 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
779 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
780 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
781 assert_eq!(commitment_update.update_fee.is_none(), true);
783 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
784 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
785 check_added_monitors!(nodes[0], 1);
786 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
788 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
789 check_added_monitors!(nodes[1], 1);
790 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
792 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
793 check_added_monitors!(nodes[1], 1);
794 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
795 // No commitment_signed so get_event_msg's assert(len == 1) passes
797 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
798 check_added_monitors!(nodes[0], 1);
799 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
801 expect_pending_htlcs_forwardable!(nodes[0]);
803 let events = nodes[0].node.get_and_clear_pending_events();
804 assert_eq!(events.len(), 1);
806 Event::PaymentReceived { .. } => { },
807 _ => panic!("Unexpected event"),
810 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
812 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
813 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
814 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
815 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
816 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
820 fn test_update_fee() {
821 let chanmon_cfgs = create_chanmon_cfgs(2);
822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
825 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
826 let channel_id = chan.2;
829 // (1) update_fee/commitment_signed ->
830 // <- (2) revoke_and_ack
831 // .- send (3) commitment_signed
832 // (4) update_fee/commitment_signed ->
833 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
834 // <- (3) commitment_signed delivered
835 // send (6) revoke_and_ack -.
836 // <- (5) deliver revoke_and_ack
837 // (6) deliver revoke_and_ack ->
838 // .- send (7) commitment_signed in response to (4)
839 // <- (7) deliver commitment_signed
842 // Create and deliver (1)...
845 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
846 feerate = *feerate_lock;
847 *feerate_lock = feerate + 20;
849 nodes[0].node.timer_tick_occurred();
850 check_added_monitors!(nodes[0], 1);
852 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
853 assert_eq!(events_0.len(), 1);
854 let (update_msg, commitment_signed) = match events_0[0] {
855 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
856 (update_fee.as_ref(), commitment_signed)
858 _ => panic!("Unexpected event"),
860 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
862 // Generate (2) and (3):
863 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
864 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
865 check_added_monitors!(nodes[1], 1);
868 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 check_added_monitors!(nodes[0], 1);
872 // Create and deliver (4)...
874 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
875 *feerate_lock = feerate + 30;
877 nodes[0].node.timer_tick_occurred();
878 check_added_monitors!(nodes[0], 1);
879 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
880 assert_eq!(events_0.len(), 1);
881 let (update_msg, commitment_signed) = match events_0[0] {
882 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
883 (update_fee.as_ref(), commitment_signed)
885 _ => panic!("Unexpected event"),
888 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
890 check_added_monitors!(nodes[1], 1);
892 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
893 // No commitment_signed so get_event_msg's assert(len == 1) passes
895 // Handle (3), creating (6):
896 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
897 check_added_monitors!(nodes[0], 1);
898 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
899 // No commitment_signed so get_event_msg's assert(len == 1) passes
902 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
903 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
904 check_added_monitors!(nodes[0], 1);
906 // Deliver (6), creating (7):
907 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
908 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
909 assert!(commitment_update.update_add_htlcs.is_empty());
910 assert!(commitment_update.update_fulfill_htlcs.is_empty());
911 assert!(commitment_update.update_fail_htlcs.is_empty());
912 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
913 assert!(commitment_update.update_fee.is_none());
914 check_added_monitors!(nodes[1], 1);
917 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
918 check_added_monitors!(nodes[0], 1);
919 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
920 // No commitment_signed so get_event_msg's assert(len == 1) passes
922 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
923 check_added_monitors!(nodes[1], 1);
924 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
926 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
927 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
928 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
929 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
930 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
934 fn fake_network_test() {
935 // Simple test which builds a network of ChannelManagers, connects them to each other, and
936 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
937 let chanmon_cfgs = create_chanmon_cfgs(4);
938 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
939 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
940 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
942 // Create some initial channels
943 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
944 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
945 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
947 // Rebalance the network a bit by relaying one payment through all the channels...
948 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
949 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
950 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
951 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
953 // Send some more payments
954 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
955 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
956 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
958 // Test failure packets
959 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
960 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
962 // Add a new channel that skips 3
963 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
965 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
966 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
967 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
968 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
969 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
970 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
971 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
973 // Do some rebalance loop payments, simultaneously
974 let mut hops = Vec::with_capacity(3);
976 pubkey: nodes[2].node.get_our_node_id(),
977 node_features: NodeFeatures::empty(),
978 short_channel_id: chan_2.0.contents.short_channel_id,
979 channel_features: ChannelFeatures::empty(),
981 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
984 pubkey: nodes[3].node.get_our_node_id(),
985 node_features: NodeFeatures::empty(),
986 short_channel_id: chan_3.0.contents.short_channel_id,
987 channel_features: ChannelFeatures::empty(),
989 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
992 pubkey: nodes[1].node.get_our_node_id(),
993 node_features: NodeFeatures::known(),
994 short_channel_id: chan_4.0.contents.short_channel_id,
995 channel_features: ChannelFeatures::known(),
997 cltv_expiry_delta: TEST_FINAL_CLTV,
999 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1000 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1001 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1003 let mut hops = Vec::with_capacity(3);
1004 hops.push(RouteHop {
1005 pubkey: nodes[3].node.get_our_node_id(),
1006 node_features: NodeFeatures::empty(),
1007 short_channel_id: chan_4.0.contents.short_channel_id,
1008 channel_features: ChannelFeatures::empty(),
1010 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1012 hops.push(RouteHop {
1013 pubkey: nodes[2].node.get_our_node_id(),
1014 node_features: NodeFeatures::empty(),
1015 short_channel_id: chan_3.0.contents.short_channel_id,
1016 channel_features: ChannelFeatures::empty(),
1018 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1020 hops.push(RouteHop {
1021 pubkey: nodes[1].node.get_our_node_id(),
1022 node_features: NodeFeatures::known(),
1023 short_channel_id: chan_2.0.contents.short_channel_id,
1024 channel_features: ChannelFeatures::known(),
1026 cltv_expiry_delta: TEST_FINAL_CLTV,
1028 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1029 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1030 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1032 // Claim the rebalances...
1033 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1034 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1036 // Add a duplicate new channel from 2 to 4
1037 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1039 // Send some payments across both channels
1040 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1041 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1042 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1045 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1046 let events = nodes[0].node.get_and_clear_pending_msg_events();
1047 assert_eq!(events.len(), 0);
1048 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1050 //TODO: Test that routes work again here as we've been notified that the channel is full
1052 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1053 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1054 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1056 // Close down the channels...
1057 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1058 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1059 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1060 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1061 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1062 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1063 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1064 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1065 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1066 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1067 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1068 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1069 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1070 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1075 fn holding_cell_htlc_counting() {
1076 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1077 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1078 // commitment dance rounds.
1079 let chanmon_cfgs = create_chanmon_cfgs(3);
1080 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1081 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1082 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1083 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1084 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1086 let mut payments = Vec::new();
1087 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1088 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1089 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1090 payments.push((payment_preimage, payment_hash));
1092 check_added_monitors!(nodes[1], 1);
1094 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1095 assert_eq!(events.len(), 1);
1096 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1097 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1099 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1100 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1102 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1104 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1105 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1106 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1110 // This should also be true if we try to forward a payment.
1111 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1113 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1114 check_added_monitors!(nodes[0], 1);
1117 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1122 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1123 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1124 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1125 // fails), the second will process the resulting failure and fail the HTLC backward.
1126 expect_pending_htlcs_forwardable!(nodes[1]);
1127 expect_pending_htlcs_forwardable!(nodes[1]);
1128 check_added_monitors!(nodes[1], 1);
1130 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1131 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1132 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1134 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1136 // Now forward all the pending HTLCs and claim them back
1137 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1138 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1139 check_added_monitors!(nodes[2], 1);
1141 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1142 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1143 check_added_monitors!(nodes[1], 1);
1144 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1146 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1147 check_added_monitors!(nodes[1], 1);
1148 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1150 for ref update in as_updates.update_add_htlcs.iter() {
1151 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1153 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1154 check_added_monitors!(nodes[2], 1);
1155 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1156 check_added_monitors!(nodes[2], 1);
1157 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1159 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1160 check_added_monitors!(nodes[1], 1);
1161 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162 check_added_monitors!(nodes[1], 1);
1163 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1165 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1166 check_added_monitors!(nodes[2], 1);
1168 expect_pending_htlcs_forwardable!(nodes[2]);
1170 let events = nodes[2].node.get_and_clear_pending_events();
1171 assert_eq!(events.len(), payments.len());
1172 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1174 &Event::PaymentReceived { ref payment_hash, .. } => {
1175 assert_eq!(*payment_hash, *hash);
1177 _ => panic!("Unexpected event"),
1181 for (preimage, _) in payments.drain(..) {
1182 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1185 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1189 fn duplicate_htlc_test() {
1190 // Test that we accept duplicate payment_hash HTLCs across the network and that
1191 // claiming/failing them are all separate and don't affect each other
1192 let chanmon_cfgs = create_chanmon_cfgs(6);
1193 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1194 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1195 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1197 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1198 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1199 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1200 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1201 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1202 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1204 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1206 *nodes[0].network_payment_count.borrow_mut() -= 1;
1207 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1209 *nodes[0].network_payment_count.borrow_mut() -= 1;
1210 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1212 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1213 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1214 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1218 fn test_duplicate_htlc_different_direction_onchain() {
1219 // Test that ChannelMonitor doesn't generate 2 preimage txn
1220 // when we have 2 HTLCs with same preimage that go across a node
1221 // in opposite directions, even with the same payment secret.
1222 let chanmon_cfgs = create_chanmon_cfgs(2);
1223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1225 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1227 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1230 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1232 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1234 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1235 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1236 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1238 // Provide preimage to node 0 by claiming payment
1239 nodes[0].node.claim_funds(payment_preimage);
1240 check_added_monitors!(nodes[0], 1);
1242 // Broadcast node 1 commitment txn
1243 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1245 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1246 let mut has_both_htlcs = 0; // check htlcs match ones committed
1247 for outp in remote_txn[0].output.iter() {
1248 if outp.value == 800_000 / 1000 {
1249 has_both_htlcs += 1;
1250 } else if outp.value == 900_000 / 1000 {
1251 has_both_htlcs += 1;
1254 assert_eq!(has_both_htlcs, 2);
1256 mine_transaction(&nodes[0], &remote_txn[0]);
1257 check_added_monitors!(nodes[0], 1);
1258 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1259 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1261 // Check we only broadcast 1 timeout tx
1262 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1263 assert_eq!(claim_txn.len(), 8);
1264 assert_eq!(claim_txn[1], claim_txn[4]);
1265 assert_eq!(claim_txn[2], claim_txn[5]);
1266 check_spends!(claim_txn[1], chan_1.3);
1267 check_spends!(claim_txn[2], claim_txn[1]);
1268 check_spends!(claim_txn[7], claim_txn[1]);
1270 assert_eq!(claim_txn[0].input.len(), 1);
1271 assert_eq!(claim_txn[3].input.len(), 1);
1272 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1274 assert_eq!(claim_txn[0].input.len(), 1);
1275 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1276 check_spends!(claim_txn[0], remote_txn[0]);
1277 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1278 assert_eq!(claim_txn[6].input.len(), 1);
1279 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1280 check_spends!(claim_txn[6], remote_txn[0]);
1281 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1283 let events = nodes[0].node.get_and_clear_pending_msg_events();
1284 assert_eq!(events.len(), 3);
1287 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1288 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1289 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1290 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1292 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1293 assert!(update_add_htlcs.is_empty());
1294 assert!(update_fail_htlcs.is_empty());
1295 assert_eq!(update_fulfill_htlcs.len(), 1);
1296 assert!(update_fail_malformed_htlcs.is_empty());
1297 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1299 _ => panic!("Unexpected event"),
1305 fn test_basic_channel_reserve() {
1306 let chanmon_cfgs = create_chanmon_cfgs(2);
1307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1309 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1310 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1312 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1313 let channel_reserve = chan_stat.channel_reserve_msat;
1315 // The 2* and +1 are for the fee spike reserve.
1316 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1317 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1318 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1319 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1321 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1323 &APIError::ChannelUnavailable{ref err} =>
1324 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1325 _ => panic!("Unexpected error variant"),
1328 _ => panic!("Unexpected error variant"),
1330 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1331 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1333 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1337 fn test_fee_spike_violation_fails_htlc() {
1338 let chanmon_cfgs = create_chanmon_cfgs(2);
1339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1342 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1344 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1345 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1346 let secp_ctx = Secp256k1::new();
1347 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1349 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1351 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1352 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1353 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1354 let msg = msgs::UpdateAddHTLC {
1357 amount_msat: htlc_msat,
1358 payment_hash: payment_hash,
1359 cltv_expiry: htlc_cltv,
1360 onion_routing_packet: onion_packet,
1363 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1365 // Now manually create the commitment_signed message corresponding to the update_add
1366 // nodes[0] just sent. In the code for construction of this message, "local" refers
1367 // to the sender of the message, and "remote" refers to the receiver.
1369 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1371 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1373 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1374 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1375 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1376 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1377 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1378 let chan_signer = local_chan.get_signer();
1379 // Make the signer believe we validated another commitment, so we can release the secret
1380 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1382 let pubkeys = chan_signer.pubkeys();
1383 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1384 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1385 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1386 chan_signer.pubkeys().funding_pubkey)
1388 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1389 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1390 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1391 let chan_signer = remote_chan.get_signer();
1392 let pubkeys = chan_signer.pubkeys();
1393 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1394 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1395 chan_signer.pubkeys().funding_pubkey)
1398 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1399 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1400 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1402 // Build the remote commitment transaction so we can sign it, and then later use the
1403 // signature for the commitment_signed message.
1404 let local_chan_balance = 1313;
1406 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1408 amount_msat: 3460001,
1409 cltv_expiry: htlc_cltv,
1411 transaction_output_index: Some(1),
1414 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1417 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1418 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1419 let local_chan_signer = local_chan.get_signer();
1420 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1424 local_chan.opt_anchors(), local_funding, remote_funding,
1425 commit_tx_keys.clone(),
1427 &mut vec![(accepted_htlc_info, ())],
1428 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1430 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1433 let commit_signed_msg = msgs::CommitmentSigned {
1436 htlc_signatures: res.1
1439 // Send the commitment_signed message to the nodes[1].
1440 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1441 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1443 // Send the RAA to nodes[1].
1444 let raa_msg = msgs::RevokeAndACK {
1446 per_commitment_secret: local_secret,
1447 next_per_commitment_point: next_local_point
1449 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1451 let events = nodes[1].node.get_and_clear_pending_msg_events();
1452 assert_eq!(events.len(), 1);
1453 // Make sure the HTLC failed in the way we expect.
1455 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1456 assert_eq!(update_fail_htlcs.len(), 1);
1457 update_fail_htlcs[0].clone()
1459 _ => panic!("Unexpected event"),
1461 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1462 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1464 check_added_monitors!(nodes[1], 2);
1468 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1469 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1470 // Set the fee rate for the channel very high, to the point where the fundee
1471 // sending any above-dust amount would result in a channel reserve violation.
1472 // In this test we check that we would be prevented from sending an HTLC in
1474 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1479 let opt_anchors = false;
1481 let mut push_amt = 100_000_000;
1482 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1483 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1485 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1487 // Sending exactly enough to hit the reserve amount should be accepted
1488 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1489 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1492 // However one more HTLC should be significantly over the reserve amount and fail.
1493 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1494 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1495 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1496 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1497 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1501 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1502 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1503 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1506 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1508 let opt_anchors = false;
1510 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1511 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1512 // transaction fee with 0 HTLCs (183 sats)).
1513 let mut push_amt = 100_000_000;
1514 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1515 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1516 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1518 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1519 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1520 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1523 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1524 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1525 let secp_ctx = Secp256k1::new();
1526 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1527 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1528 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1529 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1530 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1531 let msg = msgs::UpdateAddHTLC {
1533 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1534 amount_msat: htlc_msat,
1535 payment_hash: payment_hash,
1536 cltv_expiry: htlc_cltv,
1537 onion_routing_packet: onion_packet,
1540 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1541 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1542 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1543 assert_eq!(nodes[0].node.list_channels().len(), 0);
1544 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1545 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1546 check_added_monitors!(nodes[0], 1);
1547 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1551 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1552 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1553 // calculating our commitment transaction fee (this was previously broken).
1554 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1555 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1561 let opt_anchors = false;
1563 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1564 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1565 // transaction fee with 0 HTLCs (183 sats)).
1566 let mut push_amt = 100_000_000;
1567 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1568 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1569 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1571 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1572 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1573 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1574 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1575 // commitment transaction fee.
1576 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1578 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1579 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1580 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1583 // One more than the dust amt should fail, however.
1584 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1585 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1586 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1590 fn test_chan_init_feerate_unaffordability() {
1591 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1592 // channel reserve and feerate requirements.
1593 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1594 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1599 let opt_anchors = false;
1601 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1603 let mut push_amt = 100_000_000;
1604 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1605 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1606 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1608 // During open, we don't have a "counterparty channel reserve" to check against, so that
1609 // requirement only comes into play on the open_channel handling side.
1610 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1611 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1612 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1613 open_channel_msg.push_msat += 1;
1614 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1616 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1617 assert_eq!(msg_events.len(), 1);
1618 match msg_events[0] {
1619 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1620 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1622 _ => panic!("Unexpected event"),
1627 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1628 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1629 // calculating our counterparty's commitment transaction fee (this was previously broken).
1630 let chanmon_cfgs = create_chanmon_cfgs(2);
1631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1633 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1634 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1636 let payment_amt = 46000; // Dust amount
1637 // In the previous code, these first four payments would succeed.
1638 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1639 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1640 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1641 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1643 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1644 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1645 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1646 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1647 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1648 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1650 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1651 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1652 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1653 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1658 let chanmon_cfgs = create_chanmon_cfgs(3);
1659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1661 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1662 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1663 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1666 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1667 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1668 let feerate = get_feerate!(nodes[0], chan.2);
1669 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1671 // Add a 2* and +1 for the fee spike reserve.
1672 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1673 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1674 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1676 // Add a pending HTLC.
1677 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1678 let payment_event_1 = {
1679 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1680 check_added_monitors!(nodes[0], 1);
1682 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1683 assert_eq!(events.len(), 1);
1684 SendEvent::from_event(events.remove(0))
1686 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1688 // Attempt to trigger a channel reserve violation --> payment failure.
1689 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1690 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1691 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1692 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1694 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1695 let secp_ctx = Secp256k1::new();
1696 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1697 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1698 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1699 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1700 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1701 let msg = msgs::UpdateAddHTLC {
1704 amount_msat: htlc_msat + 1,
1705 payment_hash: our_payment_hash_1,
1706 cltv_expiry: htlc_cltv,
1707 onion_routing_packet: onion_packet,
1710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1711 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1712 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1713 assert_eq!(nodes[1].node.list_channels().len(), 1);
1714 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1715 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1716 check_added_monitors!(nodes[1], 1);
1717 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1721 fn test_inbound_outbound_capacity_is_not_zero() {
1722 let chanmon_cfgs = create_chanmon_cfgs(2);
1723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1726 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1727 let channels0 = node_chanmgrs[0].list_channels();
1728 let channels1 = node_chanmgrs[1].list_channels();
1729 assert_eq!(channels0.len(), 1);
1730 assert_eq!(channels1.len(), 1);
1732 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1733 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1734 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1736 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1737 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1740 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1741 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1745 fn test_channel_reserve_holding_cell_htlcs() {
1746 let chanmon_cfgs = create_chanmon_cfgs(3);
1747 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1748 // When this test was written, the default base fee floated based on the HTLC count.
1749 // It is now fixed, so we simply set the fee to the expected value here.
1750 let mut config = test_default_channel_config();
1751 config.channel_options.forwarding_fee_base_msat = 239;
1752 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1753 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1754 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1755 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1757 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1758 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1760 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1761 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1763 macro_rules! expect_forward {
1765 let mut events = $node.node.get_and_clear_pending_msg_events();
1766 assert_eq!(events.len(), 1);
1767 check_added_monitors!($node, 1);
1768 let payment_event = SendEvent::from_event(events.remove(0));
1773 let feemsat = 239; // set above
1774 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1775 let feerate = get_feerate!(nodes[0], chan_1.2);
1776 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1778 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1780 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1782 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1783 route.paths[0].last_mut().unwrap().fee_msat += 1;
1784 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1785 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1786 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1787 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1788 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1791 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1792 // nodes[0]'s wealth
1794 let amt_msat = recv_value_0 + total_fee_msat;
1795 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1796 // Also, ensure that each payment has enough to be over the dust limit to
1797 // ensure it'll be included in each commit tx fee calculation.
1798 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1799 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1800 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1803 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1805 let (stat01_, stat11_, stat12_, stat22_) = (
1806 get_channel_value_stat!(nodes[0], chan_1.2),
1807 get_channel_value_stat!(nodes[1], chan_1.2),
1808 get_channel_value_stat!(nodes[1], chan_2.2),
1809 get_channel_value_stat!(nodes[2], chan_2.2),
1812 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1813 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1814 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1815 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1816 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1819 // adding pending output.
1820 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1821 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1822 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1823 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1824 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1825 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1826 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1827 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1828 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1830 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1831 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1832 let amt_msat_1 = recv_value_1 + total_fee_msat;
1834 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1835 let payment_event_1 = {
1836 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1837 check_added_monitors!(nodes[0], 1);
1839 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1840 assert_eq!(events.len(), 1);
1841 SendEvent::from_event(events.remove(0))
1843 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1845 // channel reserve test with htlc pending output > 0
1846 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1848 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1849 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1850 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1851 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1854 // split the rest to test holding cell
1855 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1856 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1857 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1858 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1860 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1861 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1864 // now see if they go through on both sides
1865 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1866 // but this will stuck in the holding cell
1867 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1868 check_added_monitors!(nodes[0], 0);
1869 let events = nodes[0].node.get_and_clear_pending_events();
1870 assert_eq!(events.len(), 0);
1872 // test with outbound holding cell amount > 0
1874 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1875 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1876 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1877 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1878 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1881 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1882 // this will also stuck in the holding cell
1883 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1884 check_added_monitors!(nodes[0], 0);
1885 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1888 // flush the pending htlc
1889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1890 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1891 check_added_monitors!(nodes[1], 1);
1893 // the pending htlc should be promoted to committed
1894 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1895 check_added_monitors!(nodes[0], 1);
1896 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1898 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1899 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1900 // No commitment_signed so get_event_msg's assert(len == 1) passes
1901 check_added_monitors!(nodes[0], 1);
1903 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1905 check_added_monitors!(nodes[1], 1);
1907 expect_pending_htlcs_forwardable!(nodes[1]);
1909 let ref payment_event_11 = expect_forward!(nodes[1]);
1910 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1911 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1913 expect_pending_htlcs_forwardable!(nodes[2]);
1914 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1916 // flush the htlcs in the holding cell
1917 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1918 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1920 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1921 expect_pending_htlcs_forwardable!(nodes[1]);
1923 let ref payment_event_3 = expect_forward!(nodes[1]);
1924 assert_eq!(payment_event_3.msgs.len(), 2);
1925 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1926 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1928 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1929 expect_pending_htlcs_forwardable!(nodes[2]);
1931 let events = nodes[2].node.get_and_clear_pending_events();
1932 assert_eq!(events.len(), 2);
1934 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1935 assert_eq!(our_payment_hash_21, *payment_hash);
1936 assert_eq!(recv_value_21, amt);
1938 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1939 assert!(payment_preimage.is_none());
1940 assert_eq!(our_payment_secret_21, *payment_secret);
1942 _ => panic!("expected PaymentPurpose::InvoicePayment")
1945 _ => panic!("Unexpected event"),
1948 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1949 assert_eq!(our_payment_hash_22, *payment_hash);
1950 assert_eq!(recv_value_22, amt);
1952 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1953 assert!(payment_preimage.is_none());
1954 assert_eq!(our_payment_secret_22, *payment_secret);
1956 _ => panic!("expected PaymentPurpose::InvoicePayment")
1959 _ => panic!("Unexpected event"),
1962 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1963 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1964 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1966 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1967 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1968 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1970 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1971 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
1972 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1973 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1974 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1976 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1977 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1981 fn channel_reserve_in_flight_removes() {
1982 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1983 // can send to its counterparty, but due to update ordering, the other side may not yet have
1984 // considered those HTLCs fully removed.
1985 // This tests that we don't count HTLCs which will not be included in the next remote
1986 // commitment transaction towards the reserve value (as it implies no commitment transaction
1987 // will be generated which violates the remote reserve value).
1988 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1990 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1991 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1992 // you only consider the value of the first HTLC, it may not),
1993 // * start routing a third HTLC from A to B,
1994 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1995 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1996 // * deliver the first fulfill from B
1997 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1999 // * deliver A's response CS and RAA.
2000 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2001 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2002 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2003 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2004 let chanmon_cfgs = create_chanmon_cfgs(2);
2005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2007 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2008 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2010 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2011 // Route the first two HTLCs.
2012 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2013 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2015 // Start routing the third HTLC (this is just used to get everyone in the right state).
2016 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2018 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2019 check_added_monitors!(nodes[0], 1);
2020 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2021 assert_eq!(events.len(), 1);
2022 SendEvent::from_event(events.remove(0))
2025 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2026 // initial fulfill/CS.
2027 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2028 check_added_monitors!(nodes[1], 1);
2029 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2031 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2032 // remove the second HTLC when we send the HTLC back from B to A.
2033 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2034 check_added_monitors!(nodes[1], 1);
2035 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2037 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2039 check_added_monitors!(nodes[0], 1);
2040 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2041 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2044 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2045 check_added_monitors!(nodes[1], 1);
2046 // B is already AwaitingRAA, so cant generate a CS here
2047 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2049 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2050 check_added_monitors!(nodes[1], 1);
2051 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2053 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2054 check_added_monitors!(nodes[0], 1);
2055 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2057 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2058 check_added_monitors!(nodes[1], 1);
2059 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2061 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2062 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2063 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2064 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2065 // on-chain as necessary).
2066 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2068 check_added_monitors!(nodes[0], 1);
2069 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2070 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2072 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2073 check_added_monitors!(nodes[1], 1);
2074 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2076 expect_pending_htlcs_forwardable!(nodes[1]);
2077 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2079 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2080 // resolve the second HTLC from A's point of view.
2081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082 check_added_monitors!(nodes[0], 1);
2083 expect_payment_path_successful!(nodes[0]);
2084 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2087 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2088 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2090 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2091 check_added_monitors!(nodes[1], 1);
2092 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2093 assert_eq!(events.len(), 1);
2094 SendEvent::from_event(events.remove(0))
2097 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2098 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2099 check_added_monitors!(nodes[0], 1);
2100 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2102 // Now just resolve all the outstanding messages/HTLCs for completeness...
2104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105 check_added_monitors!(nodes[1], 1);
2106 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2108 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2109 check_added_monitors!(nodes[1], 1);
2111 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2112 check_added_monitors!(nodes[0], 1);
2113 expect_payment_path_successful!(nodes[0]);
2114 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2116 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2117 check_added_monitors!(nodes[1], 1);
2118 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2120 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121 check_added_monitors!(nodes[0], 1);
2123 expect_pending_htlcs_forwardable!(nodes[0]);
2124 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2126 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2127 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2131 fn channel_monitor_network_test() {
2132 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2133 // tests that ChannelMonitor is able to recover from various states.
2134 let chanmon_cfgs = create_chanmon_cfgs(5);
2135 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2136 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2137 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2139 // Create some initial channels
2140 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2141 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2142 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2143 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2145 // Make sure all nodes are at the same starting height
2146 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2147 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2148 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2149 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2150 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2152 // Rebalance the network a bit by relaying one payment through all the channels...
2153 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2154 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2155 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2156 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2158 // Simple case with no pending HTLCs:
2159 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2160 check_added_monitors!(nodes[1], 1);
2161 check_closed_broadcast!(nodes[1], false);
2163 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2164 assert_eq!(node_txn.len(), 1);
2165 mine_transaction(&nodes[0], &node_txn[0]);
2166 check_added_monitors!(nodes[0], 1);
2167 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2169 check_closed_broadcast!(nodes[0], true);
2170 assert_eq!(nodes[0].node.list_channels().len(), 0);
2171 assert_eq!(nodes[1].node.list_channels().len(), 1);
2172 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2173 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2175 // One pending HTLC is discarded by the force-close:
2176 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2178 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2179 // broadcasted until we reach the timelock time).
2180 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2181 check_closed_broadcast!(nodes[1], false);
2182 check_added_monitors!(nodes[1], 1);
2184 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2185 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2186 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2187 mine_transaction(&nodes[2], &node_txn[0]);
2188 check_added_monitors!(nodes[2], 1);
2189 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2191 check_closed_broadcast!(nodes[2], true);
2192 assert_eq!(nodes[1].node.list_channels().len(), 0);
2193 assert_eq!(nodes[2].node.list_channels().len(), 1);
2194 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2195 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2197 macro_rules! claim_funds {
2198 ($node: expr, $prev_node: expr, $preimage: expr) => {
2200 assert!($node.node.claim_funds($preimage));
2201 check_added_monitors!($node, 1);
2203 let events = $node.node.get_and_clear_pending_msg_events();
2204 assert_eq!(events.len(), 1);
2206 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2207 assert!(update_add_htlcs.is_empty());
2208 assert!(update_fail_htlcs.is_empty());
2209 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2211 _ => panic!("Unexpected event"),
2217 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2218 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2219 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2220 check_added_monitors!(nodes[2], 1);
2221 check_closed_broadcast!(nodes[2], false);
2222 let node2_commitment_txid;
2224 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2225 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2226 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2227 node2_commitment_txid = node_txn[0].txid();
2229 // Claim the payment on nodes[3], giving it knowledge of the preimage
2230 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2231 mine_transaction(&nodes[3], &node_txn[0]);
2232 check_added_monitors!(nodes[3], 1);
2233 check_preimage_claim(&nodes[3], &node_txn);
2235 check_closed_broadcast!(nodes[3], true);
2236 assert_eq!(nodes[2].node.list_channels().len(), 0);
2237 assert_eq!(nodes[3].node.list_channels().len(), 1);
2238 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2239 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2241 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2242 // confusing us in the following tests.
2243 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2245 // One pending HTLC to time out:
2246 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2247 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2250 let (close_chan_update_1, close_chan_update_2) = {
2251 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2252 let events = nodes[3].node.get_and_clear_pending_msg_events();
2253 assert_eq!(events.len(), 2);
2254 let close_chan_update_1 = match events[0] {
2255 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2258 _ => panic!("Unexpected event"),
2261 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2262 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2264 _ => panic!("Unexpected event"),
2266 check_added_monitors!(nodes[3], 1);
2268 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2270 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2271 node_txn.retain(|tx| {
2272 if tx.input[0].previous_output.txid == node2_commitment_txid {
2278 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2280 // Claim the payment on nodes[4], giving it knowledge of the preimage
2281 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2283 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2284 let events = nodes[4].node.get_and_clear_pending_msg_events();
2285 assert_eq!(events.len(), 2);
2286 let close_chan_update_2 = match events[0] {
2287 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2290 _ => panic!("Unexpected event"),
2293 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2294 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2296 _ => panic!("Unexpected event"),
2298 check_added_monitors!(nodes[4], 1);
2299 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2301 mine_transaction(&nodes[4], &node_txn[0]);
2302 check_preimage_claim(&nodes[4], &node_txn);
2303 (close_chan_update_1, close_chan_update_2)
2305 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2306 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2307 assert_eq!(nodes[3].node.list_channels().len(), 0);
2308 assert_eq!(nodes[4].node.list_channels().len(), 0);
2310 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2311 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2312 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2316 fn test_justice_tx() {
2317 // Test justice txn built on revoked HTLC-Success tx, against both sides
2318 let mut alice_config = UserConfig::default();
2319 alice_config.channel_options.announced_channel = true;
2320 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2321 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2322 let mut bob_config = UserConfig::default();
2323 bob_config.channel_options.announced_channel = true;
2324 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2325 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2326 let user_cfgs = [Some(alice_config), Some(bob_config)];
2327 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2328 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2329 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2333 // Create some new channels:
2334 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2336 // A pending HTLC which will be revoked:
2337 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338 // Get the will-be-revoked local txn from nodes[0]
2339 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2340 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2341 assert_eq!(revoked_local_txn[0].input.len(), 1);
2342 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2343 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2344 assert_eq!(revoked_local_txn[1].input.len(), 1);
2345 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2346 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2347 // Revoke the old state
2348 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2351 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2353 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2354 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2355 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2357 check_spends!(node_txn[0], revoked_local_txn[0]);
2358 node_txn.swap_remove(0);
2359 node_txn.truncate(1);
2361 check_added_monitors!(nodes[1], 1);
2362 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2363 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2365 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2366 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2367 // Verify broadcast of revoked HTLC-timeout
2368 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2369 check_added_monitors!(nodes[0], 1);
2370 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2371 // Broadcast revoked HTLC-timeout on node 1
2372 mine_transaction(&nodes[1], &node_txn[1]);
2373 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2375 get_announce_close_broadcast_events(&nodes, 0, 1);
2377 assert_eq!(nodes[0].node.list_channels().len(), 0);
2378 assert_eq!(nodes[1].node.list_channels().len(), 0);
2380 // We test justice_tx build by A on B's revoked HTLC-Success tx
2381 // Create some new channels:
2382 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2384 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2388 // A pending HTLC which will be revoked:
2389 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2390 // Get the will-be-revoked local txn from B
2391 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2392 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2393 assert_eq!(revoked_local_txn[0].input.len(), 1);
2394 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2395 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2396 // Revoke the old state
2397 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2399 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2401 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2402 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2403 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2405 check_spends!(node_txn[0], revoked_local_txn[0]);
2406 node_txn.swap_remove(0);
2408 check_added_monitors!(nodes[0], 1);
2409 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2411 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2412 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2414 check_added_monitors!(nodes[1], 1);
2415 mine_transaction(&nodes[0], &node_txn[1]);
2416 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2417 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2419 get_announce_close_broadcast_events(&nodes, 0, 1);
2420 assert_eq!(nodes[0].node.list_channels().len(), 0);
2421 assert_eq!(nodes[1].node.list_channels().len(), 0);
2425 fn revoked_output_claim() {
2426 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2427 // transaction is broadcast by its counterparty
2428 let chanmon_cfgs = create_chanmon_cfgs(2);
2429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2434 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2435 assert_eq!(revoked_local_txn.len(), 1);
2436 // Only output is the full channel value back to nodes[0]:
2437 assert_eq!(revoked_local_txn[0].output.len(), 1);
2438 // Send a payment through, updating everyone's latest commitment txn
2439 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2441 // Inform nodes[1] that nodes[0] broadcast a stale tx
2442 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443 check_added_monitors!(nodes[1], 1);
2444 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2445 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2446 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2448 check_spends!(node_txn[0], revoked_local_txn[0]);
2449 check_spends!(node_txn[1], chan_1.3);
2451 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2452 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453 get_announce_close_broadcast_events(&nodes, 0, 1);
2454 check_added_monitors!(nodes[0], 1);
2455 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2459 fn claim_htlc_outputs_shared_tx() {
2460 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2461 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2462 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2467 // Create some new channel:
2468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2470 // Rebalance the network to generate htlc in the two directions
2471 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2472 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2473 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2476 // Get the will-be-revoked local txn from node[0]
2477 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2478 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2479 assert_eq!(revoked_local_txn[0].input.len(), 1);
2480 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2481 assert_eq!(revoked_local_txn[1].input.len(), 1);
2482 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2483 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2484 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2486 //Revoke the old state
2487 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2490 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2491 check_added_monitors!(nodes[0], 1);
2492 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2493 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2494 check_added_monitors!(nodes[1], 1);
2495 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2496 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2497 expect_payment_failed!(nodes[1], payment_hash_2, true);
2499 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2500 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2502 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2503 check_spends!(node_txn[0], revoked_local_txn[0]);
2505 let mut witness_lens = BTreeSet::new();
2506 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2507 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2508 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2509 assert_eq!(witness_lens.len(), 3);
2510 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2511 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2512 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2514 // Next nodes[1] broadcasts its current local tx state:
2515 assert_eq!(node_txn[1].input.len(), 1);
2516 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2518 get_announce_close_broadcast_events(&nodes, 0, 1);
2519 assert_eq!(nodes[0].node.list_channels().len(), 0);
2520 assert_eq!(nodes[1].node.list_channels().len(), 0);
2524 fn claim_htlc_outputs_single_tx() {
2525 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2526 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2527 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2532 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2534 // Rebalance the network to generate htlc in the two directions
2535 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2536 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2537 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2538 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2539 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2541 // Get the will-be-revoked local txn from node[0]
2542 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2544 //Revoke the old state
2545 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2548 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2549 check_added_monitors!(nodes[0], 1);
2550 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2551 check_added_monitors!(nodes[1], 1);
2552 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2553 let mut events = nodes[0].node.get_and_clear_pending_events();
2554 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2556 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2557 _ => panic!("Unexpected event"),
2560 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2561 expect_payment_failed!(nodes[1], payment_hash_2, true);
2563 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564 assert_eq!(node_txn.len(), 9);
2565 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2566 // ChannelManager: local commmitment + local HTLC-timeout (2)
2567 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2568 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2570 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2571 assert_eq!(node_txn[0].input.len(), 1);
2572 check_spends!(node_txn[0], chan_1.3);
2573 assert_eq!(node_txn[1].input.len(), 1);
2574 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2575 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2576 check_spends!(node_txn[1], node_txn[0]);
2578 // Justice transactions are indices 1-2-4
2579 assert_eq!(node_txn[2].input.len(), 1);
2580 assert_eq!(node_txn[3].input.len(), 1);
2581 assert_eq!(node_txn[4].input.len(), 1);
2583 check_spends!(node_txn[2], revoked_local_txn[0]);
2584 check_spends!(node_txn[3], revoked_local_txn[0]);
2585 check_spends!(node_txn[4], revoked_local_txn[0]);
2587 let mut witness_lens = BTreeSet::new();
2588 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2589 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2590 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2591 assert_eq!(witness_lens.len(), 3);
2592 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2593 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2594 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2596 get_announce_close_broadcast_events(&nodes, 0, 1);
2597 assert_eq!(nodes[0].node.list_channels().len(), 0);
2598 assert_eq!(nodes[1].node.list_channels().len(), 0);
2602 fn test_htlc_on_chain_success() {
2603 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2604 // the preimage backward accordingly. So here we test that ChannelManager is
2605 // broadcasting the right event to other nodes in payment path.
2606 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2607 // A --------------------> B ----------------------> C (preimage)
2608 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2609 // commitment transaction was broadcast.
2610 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2612 // B should be able to claim via preimage if A then broadcasts its local tx.
2613 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2614 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2615 // PaymentSent event).
2617 let chanmon_cfgs = create_chanmon_cfgs(3);
2618 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2620 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2622 // Create some initial channels
2623 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2624 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2626 // Ensure all nodes are at the same height
2627 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2628 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2629 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2630 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2632 // Rebalance the network a bit by relaying one payment through all the channels...
2633 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2634 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2636 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2637 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2639 // Broadcast legit commitment tx from C on B's chain
2640 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2641 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2642 assert_eq!(commitment_tx.len(), 1);
2643 check_spends!(commitment_tx[0], chan_2.3);
2644 nodes[2].node.claim_funds(our_payment_preimage);
2645 nodes[2].node.claim_funds(our_payment_preimage_2);
2646 check_added_monitors!(nodes[2], 2);
2647 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2648 assert!(updates.update_add_htlcs.is_empty());
2649 assert!(updates.update_fail_htlcs.is_empty());
2650 assert!(updates.update_fail_malformed_htlcs.is_empty());
2651 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2653 mine_transaction(&nodes[2], &commitment_tx[0]);
2654 check_closed_broadcast!(nodes[2], true);
2655 check_added_monitors!(nodes[2], 1);
2656 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2657 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2658 assert_eq!(node_txn.len(), 5);
2659 assert_eq!(node_txn[0], node_txn[3]);
2660 assert_eq!(node_txn[1], node_txn[4]);
2661 assert_eq!(node_txn[2], commitment_tx[0]);
2662 check_spends!(node_txn[0], commitment_tx[0]);
2663 check_spends!(node_txn[1], commitment_tx[0]);
2664 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2665 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2666 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2667 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2668 assert_eq!(node_txn[0].lock_time, 0);
2669 assert_eq!(node_txn[1].lock_time, 0);
2671 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2672 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2673 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2674 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2676 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2677 assert_eq!(added_monitors.len(), 1);
2678 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2679 added_monitors.clear();
2681 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2682 assert_eq!(forwarded_events.len(), 3);
2683 match forwarded_events[0] {
2684 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2685 _ => panic!("Unexpected event"),
2687 let chan_id = Some(chan_1.2);
2688 match forwarded_events[1] {
2689 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2690 assert_eq!(fee_earned_msat, Some(1000));
2691 assert_eq!(source_channel_id, chan_id);
2692 assert_eq!(claim_from_onchain_tx, true);
2696 match forwarded_events[2] {
2697 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
2698 assert_eq!(fee_earned_msat, Some(1000));
2699 assert_eq!(source_channel_id, chan_id);
2700 assert_eq!(claim_from_onchain_tx, true);
2704 let events = nodes[1].node.get_and_clear_pending_msg_events();
2706 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2707 assert_eq!(added_monitors.len(), 2);
2708 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2709 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2710 added_monitors.clear();
2712 assert_eq!(events.len(), 3);
2714 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2715 _ => panic!("Unexpected event"),
2718 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2719 _ => panic!("Unexpected event"),
2723 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, .. } } => {
2724 assert!(update_add_htlcs.is_empty());
2725 assert!(update_fail_htlcs.is_empty());
2726 assert_eq!(update_fulfill_htlcs.len(), 1);
2727 assert!(update_fail_malformed_htlcs.is_empty());
2728 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2730 _ => panic!("Unexpected event"),
2732 macro_rules! check_tx_local_broadcast {
2733 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2734 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2735 assert_eq!(node_txn.len(), 3);
2736 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2737 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2738 check_spends!(node_txn[1], $commitment_tx);
2739 check_spends!(node_txn[2], $commitment_tx);
2740 assert_ne!(node_txn[1].lock_time, 0);
2741 assert_ne!(node_txn[2].lock_time, 0);
2743 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2744 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2745 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2746 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2748 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2749 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2750 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2751 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2753 check_spends!(node_txn[0], $chan_tx);
2754 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2758 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2759 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2760 // timeout-claim of the output that nodes[2] just claimed via success.
2761 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2763 // Broadcast legit commitment tx from A on B's chain
2764 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2765 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2766 check_spends!(node_a_commitment_tx[0], chan_1.3);
2767 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2768 check_closed_broadcast!(nodes[1], true);
2769 check_added_monitors!(nodes[1], 1);
2770 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2771 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2772 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2773 let commitment_spend =
2774 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2775 check_spends!(node_txn[1], commitment_tx[0]);
2776 check_spends!(node_txn[2], commitment_tx[0]);
2777 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2780 check_spends!(node_txn[0], commitment_tx[0]);
2781 check_spends!(node_txn[1], commitment_tx[0]);
2782 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2786 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2787 assert_eq!(commitment_spend.input.len(), 2);
2788 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2789 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2790 assert_eq!(commitment_spend.lock_time, 0);
2791 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2792 check_spends!(node_txn[3], chan_1.3);
2793 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2794 check_spends!(node_txn[4], node_txn[3]);
2795 check_spends!(node_txn[5], node_txn[3]);
2796 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2797 // we already checked the same situation with A.
2799 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2800 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2801 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2802 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2803 check_closed_broadcast!(nodes[0], true);
2804 check_added_monitors!(nodes[0], 1);
2805 let events = nodes[0].node.get_and_clear_pending_events();
2806 assert_eq!(events.len(), 5);
2807 let mut first_claimed = false;
2808 for event in events {
2810 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2811 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2812 assert!(!first_claimed);
2813 first_claimed = true;
2815 assert_eq!(payment_preimage, our_payment_preimage_2);
2816 assert_eq!(payment_hash, payment_hash_2);
2819 Event::PaymentPathSuccessful { .. } => {},
2820 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2821 _ => panic!("Unexpected event"),
2824 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2827 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2828 // Test that in case of a unilateral close onchain, we detect the state of output and
2829 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2830 // broadcasting the right event to other nodes in payment path.
2831 // A ------------------> B ----------------------> C (timeout)
2832 // B's commitment tx C's commitment tx
2834 // B's HTLC timeout tx B's timeout tx
2836 let chanmon_cfgs = create_chanmon_cfgs(3);
2837 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2838 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2839 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2840 *nodes[0].connect_style.borrow_mut() = connect_style;
2841 *nodes[1].connect_style.borrow_mut() = connect_style;
2842 *nodes[2].connect_style.borrow_mut() = connect_style;
2844 // Create some intial channels
2845 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2846 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2848 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2849 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2850 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2852 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2854 // Broadcast legit commitment tx from C on B's chain
2855 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2856 check_spends!(commitment_tx[0], chan_2.3);
2857 nodes[2].node.fail_htlc_backwards(&payment_hash);
2858 check_added_monitors!(nodes[2], 0);
2859 expect_pending_htlcs_forwardable!(nodes[2]);
2860 check_added_monitors!(nodes[2], 1);
2862 let events = nodes[2].node.get_and_clear_pending_msg_events();
2863 assert_eq!(events.len(), 1);
2865 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, .. } } => {
2866 assert!(update_add_htlcs.is_empty());
2867 assert!(!update_fail_htlcs.is_empty());
2868 assert!(update_fulfill_htlcs.is_empty());
2869 assert!(update_fail_malformed_htlcs.is_empty());
2870 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2872 _ => panic!("Unexpected event"),
2874 mine_transaction(&nodes[2], &commitment_tx[0]);
2875 check_closed_broadcast!(nodes[2], true);
2876 check_added_monitors!(nodes[2], 1);
2877 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2878 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2879 assert_eq!(node_txn.len(), 1);
2880 check_spends!(node_txn[0], chan_2.3);
2881 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2883 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2884 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2885 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2886 mine_transaction(&nodes[1], &commitment_tx[0]);
2887 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2890 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2891 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2892 assert_eq!(node_txn[0], node_txn[3]);
2893 assert_eq!(node_txn[1], node_txn[4]);
2895 check_spends!(node_txn[2], commitment_tx[0]);
2896 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2898 check_spends!(node_txn[0], chan_2.3);
2899 check_spends!(node_txn[1], node_txn[0]);
2900 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2901 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2903 timeout_tx = node_txn[2].clone();
2907 mine_transaction(&nodes[1], &timeout_tx);
2908 check_added_monitors!(nodes[1], 1);
2909 check_closed_broadcast!(nodes[1], true);
2911 // B will rebroadcast a fee-bumped timeout transaction here.
2912 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2913 assert_eq!(node_txn.len(), 1);
2914 check_spends!(node_txn[0], commitment_tx[0]);
2917 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2919 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2920 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2921 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2922 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2923 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2924 if node_txn.len() == 1 {
2925 check_spends!(node_txn[0], chan_2.3);
2927 assert_eq!(node_txn.len(), 0);
2931 expect_pending_htlcs_forwardable!(nodes[1]);
2932 check_added_monitors!(nodes[1], 1);
2933 let events = nodes[1].node.get_and_clear_pending_msg_events();
2934 assert_eq!(events.len(), 1);
2936 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, .. } } => {
2937 assert!(update_add_htlcs.is_empty());
2938 assert!(!update_fail_htlcs.is_empty());
2939 assert!(update_fulfill_htlcs.is_empty());
2940 assert!(update_fail_malformed_htlcs.is_empty());
2941 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2943 _ => panic!("Unexpected event"),
2946 // Broadcast legit commitment tx from B on A's chain
2947 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2948 check_spends!(commitment_tx[0], chan_1.3);
2950 mine_transaction(&nodes[0], &commitment_tx[0]);
2951 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2953 check_closed_broadcast!(nodes[0], true);
2954 check_added_monitors!(nodes[0], 1);
2955 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2956 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2957 assert_eq!(node_txn.len(), 2);
2958 check_spends!(node_txn[0], chan_1.3);
2959 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2960 check_spends!(node_txn[1], commitment_tx[0]);
2961 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2965 fn test_htlc_on_chain_timeout() {
2966 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2967 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2968 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2972 fn test_simple_commitment_revoked_fail_backward() {
2973 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2974 // and fail backward accordingly.
2976 let chanmon_cfgs = create_chanmon_cfgs(3);
2977 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2978 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2979 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2981 // Create some initial channels
2982 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2983 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2985 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2986 // Get the will-be-revoked local txn from nodes[2]
2987 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2988 // Revoke the old state
2989 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2991 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2993 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2994 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2995 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2996 check_added_monitors!(nodes[1], 1);
2997 check_closed_broadcast!(nodes[1], true);
2999 expect_pending_htlcs_forwardable!(nodes[1]);
3000 check_added_monitors!(nodes[1], 1);
3001 let events = nodes[1].node.get_and_clear_pending_msg_events();
3002 assert_eq!(events.len(), 1);
3004 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, .. } } => {
3005 assert!(update_add_htlcs.is_empty());
3006 assert_eq!(update_fail_htlcs.len(), 1);
3007 assert!(update_fulfill_htlcs.is_empty());
3008 assert!(update_fail_malformed_htlcs.is_empty());
3009 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3011 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3012 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3013 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3015 _ => panic!("Unexpected event"),
3019 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3020 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3021 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3022 // commitment transaction anymore.
3023 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3024 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3025 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3026 // technically disallowed and we should probably handle it reasonably.
3027 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3028 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3030 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3031 // commitment_signed (implying it will be in the latest remote commitment transaction).
3032 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3033 // and once they revoke the previous commitment transaction (allowing us to send a new
3034 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3035 let chanmon_cfgs = create_chanmon_cfgs(3);
3036 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3037 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3038 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3040 // Create some initial channels
3041 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3042 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3044 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 });
3045 // Get the will-be-revoked local txn from nodes[2]
3046 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3047 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3048 // Revoke the old state
3049 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3051 let value = if use_dust {
3052 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3053 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3054 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3057 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3058 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3059 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3061 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3062 expect_pending_htlcs_forwardable!(nodes[2]);
3063 check_added_monitors!(nodes[2], 1);
3064 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3065 assert!(updates.update_add_htlcs.is_empty());
3066 assert!(updates.update_fulfill_htlcs.is_empty());
3067 assert!(updates.update_fail_malformed_htlcs.is_empty());
3068 assert_eq!(updates.update_fail_htlcs.len(), 1);
3069 assert!(updates.update_fee.is_none());
3070 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3071 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3072 // Drop the last RAA from 3 -> 2
3074 assert!(nodes[2].node.fail_htlc_backwards(&second_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 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3085 check_added_monitors!(nodes[1], 1);
3086 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3087 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3088 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3089 check_added_monitors!(nodes[2], 1);
3091 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3092 expect_pending_htlcs_forwardable!(nodes[2]);
3093 check_added_monitors!(nodes[2], 1);
3094 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3095 assert!(updates.update_add_htlcs.is_empty());
3096 assert!(updates.update_fulfill_htlcs.is_empty());
3097 assert!(updates.update_fail_malformed_htlcs.is_empty());
3098 assert_eq!(updates.update_fail_htlcs.len(), 1);
3099 assert!(updates.update_fee.is_none());
3100 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3101 // At this point first_payment_hash has dropped out of the latest two commitment
3102 // transactions that nodes[1] is tracking...
3103 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3104 check_added_monitors!(nodes[1], 1);
3105 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3106 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3107 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3108 check_added_monitors!(nodes[2], 1);
3110 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3111 // on nodes[2]'s RAA.
3112 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3113 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3114 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3115 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3116 check_added_monitors!(nodes[1], 0);
3119 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3120 // One monitor for the new revocation preimage, no second on as we won't generate a new
3121 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3122 check_added_monitors!(nodes[1], 1);
3123 let events = nodes[1].node.get_and_clear_pending_events();
3124 assert_eq!(events.len(), 1);
3126 Event::PendingHTLCsForwardable { .. } => { },
3127 _ => panic!("Unexpected event"),
3129 // Deliberately don't process the pending fail-back so they all fail back at once after
3130 // block connection just like the !deliver_bs_raa case
3133 let mut failed_htlcs = HashSet::new();
3134 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3136 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3137 check_added_monitors!(nodes[1], 1);
3138 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3139 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3141 let events = nodes[1].node.get_and_clear_pending_events();
3142 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3144 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3145 _ => panic!("Unexepected event"),
3148 Event::PaymentPathFailed { ref payment_hash, .. } => {
3149 assert_eq!(*payment_hash, fourth_payment_hash);
3151 _ => panic!("Unexpected event"),
3153 if !deliver_bs_raa {
3155 Event::PaymentFailed { ref payment_hash, .. } => {
3156 assert_eq!(*payment_hash, fourth_payment_hash);
3158 _ => panic!("Unexpected event"),
3161 Event::PendingHTLCsForwardable { .. } => { },
3162 _ => panic!("Unexpected event"),
3165 nodes[1].node.process_pending_htlc_forwards();
3166 check_added_monitors!(nodes[1], 1);
3168 let events = nodes[1].node.get_and_clear_pending_msg_events();
3169 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3170 match events[if deliver_bs_raa { 1 } else { 0 }] {
3171 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3172 _ => panic!("Unexpected event"),
3174 match events[if deliver_bs_raa { 2 } else { 1 }] {
3175 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3176 assert_eq!(channel_id, chan_2.2);
3177 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3179 _ => panic!("Unexpected event"),
3183 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, .. } } => {
3184 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3185 assert_eq!(update_add_htlcs.len(), 1);
3186 assert!(update_fulfill_htlcs.is_empty());
3187 assert!(update_fail_htlcs.is_empty());
3188 assert!(update_fail_malformed_htlcs.is_empty());
3190 _ => panic!("Unexpected event"),
3193 match events[if deliver_bs_raa { 3 } else { 2 }] {
3194 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, .. } } => {
3195 assert!(update_add_htlcs.is_empty());
3196 assert_eq!(update_fail_htlcs.len(), 3);
3197 assert!(update_fulfill_htlcs.is_empty());
3198 assert!(update_fail_malformed_htlcs.is_empty());
3199 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3201 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3202 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3203 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3205 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3207 let events = nodes[0].node.get_and_clear_pending_events();
3208 assert_eq!(events.len(), 3);
3210 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3211 assert!(failed_htlcs.insert(payment_hash.0));
3212 // If we delivered B's RAA we got an unknown preimage error, not something
3213 // that we should update our routing table for.
3214 if !deliver_bs_raa {
3215 assert!(network_update.is_some());
3218 _ => panic!("Unexpected event"),
3221 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3222 assert!(failed_htlcs.insert(payment_hash.0));
3223 assert!(network_update.is_some());
3225 _ => panic!("Unexpected event"),
3228 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3229 assert!(failed_htlcs.insert(payment_hash.0));
3230 assert!(network_update.is_some());
3232 _ => panic!("Unexpected event"),
3235 _ => panic!("Unexpected event"),
3238 assert!(failed_htlcs.contains(&first_payment_hash.0));
3239 assert!(failed_htlcs.contains(&second_payment_hash.0));
3240 assert!(failed_htlcs.contains(&third_payment_hash.0));
3244 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3245 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3246 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3247 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3248 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3252 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3253 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3254 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3255 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3256 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3260 fn fail_backward_pending_htlc_upon_channel_failure() {
3261 let chanmon_cfgs = create_chanmon_cfgs(2);
3262 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3263 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3264 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3265 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3267 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3269 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3270 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3271 check_added_monitors!(nodes[0], 1);
3273 let payment_event = {
3274 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3275 assert_eq!(events.len(), 1);
3276 SendEvent::from_event(events.remove(0))
3278 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3279 assert_eq!(payment_event.msgs.len(), 1);
3282 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3283 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3285 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3286 check_added_monitors!(nodes[0], 0);
3288 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3291 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3293 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3295 let secp_ctx = Secp256k1::new();
3296 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3297 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3298 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3299 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3300 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3302 // Send a 0-msat update_add_htlc to fail the channel.
3303 let update_add_htlc = msgs::UpdateAddHTLC {
3309 onion_routing_packet,
3311 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3313 let events = nodes[0].node.get_and_clear_pending_events();
3314 assert_eq!(events.len(), 2);
3315 // Check that Alice fails backward the pending HTLC from the second payment.
3317 Event::PaymentPathFailed { payment_hash, .. } => {
3318 assert_eq!(payment_hash, failed_payment_hash);
3320 _ => panic!("Unexpected event"),
3323 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3324 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3326 _ => panic!("Unexpected event {:?}", events[1]),
3328 check_closed_broadcast!(nodes[0], true);
3329 check_added_monitors!(nodes[0], 1);
3333 fn test_htlc_ignore_latest_remote_commitment() {
3334 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3335 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3336 let chanmon_cfgs = create_chanmon_cfgs(2);
3337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3339 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3340 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3342 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3343 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3344 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3345 check_closed_broadcast!(nodes[0], true);
3346 check_added_monitors!(nodes[0], 1);
3347 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3349 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3350 assert_eq!(node_txn.len(), 3);
3351 assert_eq!(node_txn[0], node_txn[1]);
3353 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3354 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3355 check_closed_broadcast!(nodes[1], true);
3356 check_added_monitors!(nodes[1], 1);
3357 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3359 // Duplicate the connect_block call since this may happen due to other listeners
3360 // registering new transactions
3361 header.prev_blockhash = header.block_hash();
3362 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3366 fn test_force_close_fail_back() {
3367 // Check which HTLCs are failed-backwards on channel force-closure
3368 let chanmon_cfgs = create_chanmon_cfgs(3);
3369 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3370 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3371 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3372 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3373 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3375 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3377 let mut payment_event = {
3378 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3379 check_added_monitors!(nodes[0], 1);
3381 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3382 assert_eq!(events.len(), 1);
3383 SendEvent::from_event(events.remove(0))
3386 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3387 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3389 expect_pending_htlcs_forwardable!(nodes[1]);
3391 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3392 assert_eq!(events_2.len(), 1);
3393 payment_event = SendEvent::from_event(events_2.remove(0));
3394 assert_eq!(payment_event.msgs.len(), 1);
3396 check_added_monitors!(nodes[1], 1);
3397 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3398 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3399 check_added_monitors!(nodes[2], 1);
3400 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3402 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3403 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3404 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3406 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3407 check_closed_broadcast!(nodes[2], true);
3408 check_added_monitors!(nodes[2], 1);
3409 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3411 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3412 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3413 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3414 // back to nodes[1] upon timeout otherwise.
3415 assert_eq!(node_txn.len(), 1);
3419 mine_transaction(&nodes[1], &tx);
3421 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3422 check_closed_broadcast!(nodes[1], true);
3423 check_added_monitors!(nodes[1], 1);
3424 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3426 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3428 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3429 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3431 mine_transaction(&nodes[2], &tx);
3432 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3433 assert_eq!(node_txn.len(), 1);
3434 assert_eq!(node_txn[0].input.len(), 1);
3435 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3436 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3437 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3439 check_spends!(node_txn[0], tx);
3443 fn test_dup_events_on_peer_disconnect() {
3444 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3445 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3446 // as we used to generate the event immediately upon receipt of the payment preimage in the
3447 // update_fulfill_htlc message.
3449 let chanmon_cfgs = create_chanmon_cfgs(2);
3450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3451 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3452 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3453 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3455 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3457 assert!(nodes[1].node.claim_funds(payment_preimage));
3458 check_added_monitors!(nodes[1], 1);
3459 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3460 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3461 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3463 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3464 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3466 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3467 expect_payment_path_successful!(nodes[0]);
3471 fn test_simple_peer_disconnect() {
3472 // Test that we can reconnect when there are no lost messages
3473 let chanmon_cfgs = create_chanmon_cfgs(3);
3474 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3475 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3476 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3477 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3478 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3480 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3481 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3482 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3484 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3485 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3486 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3487 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3489 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3490 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3491 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3493 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3494 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3495 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3496 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3498 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3499 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3501 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3502 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3504 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3506 let events = nodes[0].node.get_and_clear_pending_events();
3507 assert_eq!(events.len(), 3);
3509 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3510 assert_eq!(payment_preimage, payment_preimage_3);
3511 assert_eq!(payment_hash, payment_hash_3);
3513 _ => panic!("Unexpected event"),
3516 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3517 assert_eq!(payment_hash, payment_hash_5);
3518 assert!(rejected_by_dest);
3520 _ => panic!("Unexpected event"),
3523 Event::PaymentPathSuccessful { .. } => {},
3524 _ => panic!("Unexpected event"),
3528 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3529 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3532 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3533 // Test that we can reconnect when in-flight HTLC updates get dropped
3534 let chanmon_cfgs = create_chanmon_cfgs(2);
3535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3537 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3539 let mut as_funding_locked = None;
3540 if messages_delivered == 0 {
3541 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3542 as_funding_locked = Some(funding_locked);
3543 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3544 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3545 // it before the channel_reestablish message.
3547 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3550 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3552 let payment_event = {
3553 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3554 check_added_monitors!(nodes[0], 1);
3556 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3557 assert_eq!(events.len(), 1);
3558 SendEvent::from_event(events.remove(0))
3560 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3562 if messages_delivered < 2 {
3563 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3565 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3566 if messages_delivered >= 3 {
3567 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3568 check_added_monitors!(nodes[1], 1);
3569 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3571 if messages_delivered >= 4 {
3572 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3573 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3574 check_added_monitors!(nodes[0], 1);
3576 if messages_delivered >= 5 {
3577 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3578 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3579 // No commitment_signed so get_event_msg's assert(len == 1) passes
3580 check_added_monitors!(nodes[0], 1);
3582 if messages_delivered >= 6 {
3583 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3584 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3585 check_added_monitors!(nodes[1], 1);
3592 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3593 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3594 if messages_delivered < 3 {
3595 if simulate_broken_lnd {
3596 // lnd has a long-standing bug where they send a funding_locked prior to a
3597 // channel_reestablish if you reconnect prior to funding_locked time.
3599 // Here we simulate that behavior, delivering a funding_locked immediately on
3600 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3601 // in `reconnect_nodes` but we currently don't fail based on that.
3603 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3604 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3606 // Even if the funding_locked messages get exchanged, as long as nothing further was
3607 // received on either side, both sides will need to resend them.
3608 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3609 } else if messages_delivered == 3 {
3610 // nodes[0] still wants its RAA + commitment_signed
3611 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3612 } else if messages_delivered == 4 {
3613 // nodes[0] still wants its commitment_signed
3614 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3615 } else if messages_delivered == 5 {
3616 // nodes[1] still wants its final RAA
3617 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3618 } else if messages_delivered == 6 {
3619 // Everything was delivered...
3620 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3623 let events_1 = nodes[1].node.get_and_clear_pending_events();
3624 assert_eq!(events_1.len(), 1);
3626 Event::PendingHTLCsForwardable { .. } => { },
3627 _ => panic!("Unexpected event"),
3630 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3631 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3632 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634 nodes[1].node.process_pending_htlc_forwards();
3636 let events_2 = nodes[1].node.get_and_clear_pending_events();
3637 assert_eq!(events_2.len(), 1);
3639 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3640 assert_eq!(payment_hash_1, *payment_hash);
3641 assert_eq!(amt, 1000000);
3643 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3644 assert!(payment_preimage.is_none());
3645 assert_eq!(payment_secret_1, *payment_secret);
3647 _ => panic!("expected PaymentPurpose::InvoicePayment")
3650 _ => panic!("Unexpected event"),
3653 nodes[1].node.claim_funds(payment_preimage_1);
3654 check_added_monitors!(nodes[1], 1);
3656 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3657 assert_eq!(events_3.len(), 1);
3658 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3659 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3660 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3661 assert!(updates.update_add_htlcs.is_empty());
3662 assert!(updates.update_fail_htlcs.is_empty());
3663 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3664 assert!(updates.update_fail_malformed_htlcs.is_empty());
3665 assert!(updates.update_fee.is_none());
3666 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3668 _ => panic!("Unexpected event"),
3671 if messages_delivered >= 1 {
3672 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3674 let events_4 = nodes[0].node.get_and_clear_pending_events();
3675 assert_eq!(events_4.len(), 1);
3677 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3678 assert_eq!(payment_preimage_1, *payment_preimage);
3679 assert_eq!(payment_hash_1, *payment_hash);
3681 _ => panic!("Unexpected event"),
3684 if messages_delivered >= 2 {
3685 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3686 check_added_monitors!(nodes[0], 1);
3687 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3689 if messages_delivered >= 3 {
3690 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3691 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3692 check_added_monitors!(nodes[1], 1);
3694 if messages_delivered >= 4 {
3695 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3696 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3697 // No commitment_signed so get_event_msg's assert(len == 1) passes
3698 check_added_monitors!(nodes[1], 1);
3700 if messages_delivered >= 5 {
3701 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3702 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3703 check_added_monitors!(nodes[0], 1);
3710 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3711 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3712 if messages_delivered < 2 {
3713 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714 if messages_delivered < 1 {
3715 expect_payment_sent!(nodes[0], payment_preimage_1);
3717 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3719 } else if messages_delivered == 2 {
3720 // nodes[0] still wants its RAA + commitment_signed
3721 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3722 } else if messages_delivered == 3 {
3723 // nodes[0] still wants its commitment_signed
3724 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725 } else if messages_delivered == 4 {
3726 // nodes[1] still wants its final RAA
3727 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3728 } else if messages_delivered == 5 {
3729 // Everything was delivered...
3730 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733 if messages_delivered == 1 || messages_delivered == 2 {
3734 expect_payment_path_successful!(nodes[0]);
3737 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3738 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3739 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3741 if messages_delivered > 2 {
3742 expect_payment_path_successful!(nodes[0]);
3745 // Channel should still work fine...
3746 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3747 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3748 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3752 fn test_drop_messages_peer_disconnect_a() {
3753 do_test_drop_messages_peer_disconnect(0, true);
3754 do_test_drop_messages_peer_disconnect(0, false);
3755 do_test_drop_messages_peer_disconnect(1, false);
3756 do_test_drop_messages_peer_disconnect(2, false);
3760 fn test_drop_messages_peer_disconnect_b() {
3761 do_test_drop_messages_peer_disconnect(3, false);
3762 do_test_drop_messages_peer_disconnect(4, false);
3763 do_test_drop_messages_peer_disconnect(5, false);
3764 do_test_drop_messages_peer_disconnect(6, false);
3768 fn test_funding_peer_disconnect() {
3769 // Test that we can lock in our funding tx while disconnected
3770 let chanmon_cfgs = create_chanmon_cfgs(2);
3771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3773 let persister: test_utils::TestPersister;
3774 let new_chain_monitor: test_utils::TestChainMonitor;
3775 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3776 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3777 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3779 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3780 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3782 confirm_transaction(&nodes[0], &tx);
3783 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3784 assert!(events_1.is_empty());
3786 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3788 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3789 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3791 confirm_transaction(&nodes[1], &tx);
3792 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3793 assert!(events_2.is_empty());
3795 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3796 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3797 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
3798 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3800 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3801 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3802 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3803 assert_eq!(events_3.len(), 1);
3804 let as_funding_locked = match events_3[0] {
3805 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3806 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3809 _ => panic!("Unexpected event {:?}", events_3[0]),
3812 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3813 // announcement_signatures as well as channel_update.
3814 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3815 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3816 assert_eq!(events_4.len(), 3);
3818 let bs_funding_locked = match events_4[0] {
3819 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3820 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3821 chan_id = msg.channel_id;
3824 _ => panic!("Unexpected event {:?}", events_4[0]),
3826 let bs_announcement_sigs = match events_4[1] {
3827 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3828 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3831 _ => panic!("Unexpected event {:?}", events_4[1]),
3834 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3835 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3837 _ => panic!("Unexpected event {:?}", events_4[2]),
3840 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3841 // generates a duplicative private channel_update
3842 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3843 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3844 assert_eq!(events_5.len(), 1);
3846 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3847 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3849 _ => panic!("Unexpected event {:?}", events_5[0]),
3852 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3853 // announcement_signatures.
3854 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3855 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3856 assert_eq!(events_6.len(), 1);
3857 let as_announcement_sigs = match events_6[0] {
3858 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3859 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3862 _ => panic!("Unexpected event {:?}", events_6[0]),
3865 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3866 // broadcast the channel announcement globally, as well as re-send its (now-public)
3868 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3869 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3870 assert_eq!(events_7.len(), 1);
3871 let (chan_announcement, as_update) = match events_7[0] {
3872 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3873 (msg.clone(), update_msg.clone())
3875 _ => panic!("Unexpected event {:?}", events_7[0]),
3878 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3879 // same channel_announcement.
3880 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3881 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3882 assert_eq!(events_8.len(), 1);
3883 let bs_update = match events_8[0] {
3884 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3885 assert_eq!(*msg, chan_announcement);
3888 _ => panic!("Unexpected event {:?}", events_8[0]),
3891 // Provide the channel announcement and public updates to the network graph
3892 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3893 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3894 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3896 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3897 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3898 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3900 // Check that after deserialization and reconnection we can still generate an identical
3901 // channel_announcement from the cached signatures.
3902 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3904 let nodes_0_serialized = nodes[0].node.encode();
3905 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3906 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3908 persister = test_utils::TestPersister::new();
3909 let keys_manager = &chanmon_cfgs[0].keys_manager;
3910 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);
3911 nodes[0].chain_monitor = &new_chain_monitor;
3912 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3913 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3914 &mut chan_0_monitor_read, keys_manager).unwrap();
3915 assert!(chan_0_monitor_read.is_empty());
3917 let mut nodes_0_read = &nodes_0_serialized[..];
3918 let (_, nodes_0_deserialized_tmp) = {
3919 let mut channel_monitors = HashMap::new();
3920 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3921 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3922 default_config: UserConfig::default(),
3924 fee_estimator: node_cfgs[0].fee_estimator,
3925 chain_monitor: nodes[0].chain_monitor,
3926 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3927 logger: nodes[0].logger,
3931 nodes_0_deserialized = nodes_0_deserialized_tmp;
3932 assert!(nodes_0_read.is_empty());
3934 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3935 nodes[0].node = &nodes_0_deserialized;
3936 check_added_monitors!(nodes[0], 1);
3938 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3940 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3941 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3942 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3943 let mut found_announcement = false;
3944 for event in msgs.iter() {
3946 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3947 if *msg == chan_announcement { found_announcement = true; }
3949 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3950 _ => panic!("Unexpected event"),
3953 assert!(found_announcement);
3957 fn test_funding_locked_without_best_block_updated() {
3958 // Previously, if we were offline when a funding transaction was locked in, and then we came
3959 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3960 // generate a funding_locked until a later best_block_updated. This tests that we generate the
3961 // funding_locked immediately instead.
3962 let chanmon_cfgs = create_chanmon_cfgs(2);
3963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3965 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3966 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3968 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
3970 let conf_height = nodes[0].best_block_info().1 + 1;
3971 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3972 let block_txn = [funding_tx];
3973 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3974 let conf_block_header = nodes[0].get_block_header(conf_height);
3975 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3977 // Ensure nodes[0] generates a funding_locked after the transactions_confirmed
3978 let as_funding_locked = get_event_msg!(nodes[0], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id());
3979 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3983 fn test_drop_messages_peer_disconnect_dual_htlc() {
3984 // Test that we can handle reconnecting when both sides of a channel have pending
3985 // commitment_updates when we disconnect.
3986 let chanmon_cfgs = create_chanmon_cfgs(2);
3987 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3988 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3989 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3990 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3992 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3994 // Now try to send a second payment which will fail to send
3995 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3996 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3997 check_added_monitors!(nodes[0], 1);
3999 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4000 assert_eq!(events_1.len(), 1);
4002 MessageSendEvent::UpdateHTLCs { .. } => {},
4003 _ => panic!("Unexpected event"),
4006 assert!(nodes[1].node.claim_funds(payment_preimage_1));
4007 check_added_monitors!(nodes[1], 1);
4009 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4010 assert_eq!(events_2.len(), 1);
4012 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 } } => {
4013 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4014 assert!(update_add_htlcs.is_empty());
4015 assert_eq!(update_fulfill_htlcs.len(), 1);
4016 assert!(update_fail_htlcs.is_empty());
4017 assert!(update_fail_malformed_htlcs.is_empty());
4018 assert!(update_fee.is_none());
4020 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4021 let events_3 = nodes[0].node.get_and_clear_pending_events();
4022 assert_eq!(events_3.len(), 1);
4024 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4025 assert_eq!(*payment_preimage, payment_preimage_1);
4026 assert_eq!(*payment_hash, payment_hash_1);
4028 _ => panic!("Unexpected event"),
4031 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4032 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4033 // No commitment_signed so get_event_msg's assert(len == 1) passes
4034 check_added_monitors!(nodes[0], 1);
4036 _ => panic!("Unexpected event"),
4039 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4040 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4042 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4043 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4044 assert_eq!(reestablish_1.len(), 1);
4045 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4046 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4047 assert_eq!(reestablish_2.len(), 1);
4049 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4050 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4051 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4052 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4054 assert!(as_resp.0.is_none());
4055 assert!(bs_resp.0.is_none());
4057 assert!(bs_resp.1.is_none());
4058 assert!(bs_resp.2.is_none());
4060 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4062 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4063 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4064 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4065 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4066 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4067 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4068 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4069 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4070 // No commitment_signed so get_event_msg's assert(len == 1) passes
4071 check_added_monitors!(nodes[1], 1);
4073 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4074 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4075 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4076 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4077 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4078 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4079 assert!(bs_second_commitment_signed.update_fee.is_none());
4080 check_added_monitors!(nodes[1], 1);
4082 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4083 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4084 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4085 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4086 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4087 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4088 assert!(as_commitment_signed.update_fee.is_none());
4089 check_added_monitors!(nodes[0], 1);
4091 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4092 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4093 // No commitment_signed so get_event_msg's assert(len == 1) passes
4094 check_added_monitors!(nodes[0], 1);
4096 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4097 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4098 // No commitment_signed so get_event_msg's assert(len == 1) passes
4099 check_added_monitors!(nodes[1], 1);
4101 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4102 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4103 check_added_monitors!(nodes[1], 1);
4105 expect_pending_htlcs_forwardable!(nodes[1]);
4107 let events_5 = nodes[1].node.get_and_clear_pending_events();
4108 assert_eq!(events_5.len(), 1);
4110 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4111 assert_eq!(payment_hash_2, *payment_hash);
4113 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4114 assert!(payment_preimage.is_none());
4115 assert_eq!(payment_secret_2, *payment_secret);
4117 _ => panic!("expected PaymentPurpose::InvoicePayment")
4120 _ => panic!("Unexpected event"),
4123 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4124 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4125 check_added_monitors!(nodes[0], 1);
4127 expect_payment_path_successful!(nodes[0]);
4128 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4131 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4132 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4133 // to avoid our counterparty failing the channel.
4134 let chanmon_cfgs = create_chanmon_cfgs(2);
4135 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4136 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4137 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4139 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4141 let our_payment_hash = if send_partial_mpp {
4142 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4143 // Use the utility function send_payment_along_path to send the payment with MPP data which
4144 // indicates there are more HTLCs coming.
4145 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.
4146 let payment_id = PaymentId([42; 32]);
4147 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payment_params, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4148 check_added_monitors!(nodes[0], 1);
4149 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4150 assert_eq!(events.len(), 1);
4151 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4152 // hop should *not* yet generate any PaymentReceived event(s).
4153 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4156 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4159 let mut block = Block {
4160 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4163 connect_block(&nodes[0], &block);
4164 connect_block(&nodes[1], &block);
4165 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4166 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4167 block.header.prev_blockhash = block.block_hash();
4168 connect_block(&nodes[0], &block);
4169 connect_block(&nodes[1], &block);
4172 expect_pending_htlcs_forwardable!(nodes[1]);
4174 check_added_monitors!(nodes[1], 1);
4175 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4176 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4177 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4178 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4179 assert!(htlc_timeout_updates.update_fee.is_none());
4181 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4182 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4183 // 100_000 msat as u64, followed by the height at which we failed back above
4184 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4185 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4186 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4190 fn test_htlc_timeout() {
4191 do_test_htlc_timeout(true);
4192 do_test_htlc_timeout(false);
4195 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4196 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4197 let chanmon_cfgs = create_chanmon_cfgs(3);
4198 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4199 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4200 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4201 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4202 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4204 // Make sure all nodes are at the same starting height
4205 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4206 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4207 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4209 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4210 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4212 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4214 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4215 check_added_monitors!(nodes[1], 1);
4217 // Now attempt to route a second payment, which should be placed in the holding cell
4218 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4219 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4220 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4222 check_added_monitors!(nodes[0], 1);
4223 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4224 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4225 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4226 expect_pending_htlcs_forwardable!(nodes[1]);
4228 check_added_monitors!(nodes[1], 0);
4230 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4231 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4232 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4233 connect_blocks(&nodes[1], 1);
4236 expect_pending_htlcs_forwardable!(nodes[1]);
4237 check_added_monitors!(nodes[1], 1);
4238 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4239 assert_eq!(fail_commit.len(), 1);
4240 match fail_commit[0] {
4241 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4242 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4243 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4245 _ => unreachable!(),
4247 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4249 let events = nodes[1].node.get_and_clear_pending_events();
4250 assert_eq!(events.len(), 2);
4251 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4252 assert_eq!(*payment_hash, second_payment_hash);
4253 } else { panic!("Unexpected event"); }
4254 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4255 assert_eq!(*payment_hash, second_payment_hash);
4256 } else { panic!("Unexpected event"); }
4261 fn test_holding_cell_htlc_add_timeouts() {
4262 do_test_holding_cell_htlc_add_timeouts(false);
4263 do_test_holding_cell_htlc_add_timeouts(true);
4267 fn test_no_txn_manager_serialize_deserialize() {
4268 let chanmon_cfgs = create_chanmon_cfgs(2);
4269 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4270 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4271 let logger: test_utils::TestLogger;
4272 let fee_estimator: test_utils::TestFeeEstimator;
4273 let persister: test_utils::TestPersister;
4274 let new_chain_monitor: test_utils::TestChainMonitor;
4275 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4276 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4278 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4280 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4282 let nodes_0_serialized = nodes[0].node.encode();
4283 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4284 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4285 .write(&mut chan_0_monitor_serialized).unwrap();
4287 logger = test_utils::TestLogger::new();
4288 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4289 persister = test_utils::TestPersister::new();
4290 let keys_manager = &chanmon_cfgs[0].keys_manager;
4291 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4292 nodes[0].chain_monitor = &new_chain_monitor;
4293 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4294 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4295 &mut chan_0_monitor_read, keys_manager).unwrap();
4296 assert!(chan_0_monitor_read.is_empty());
4298 let mut nodes_0_read = &nodes_0_serialized[..];
4299 let config = UserConfig::default();
4300 let (_, nodes_0_deserialized_tmp) = {
4301 let mut channel_monitors = HashMap::new();
4302 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4303 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4304 default_config: config,
4306 fee_estimator: &fee_estimator,
4307 chain_monitor: nodes[0].chain_monitor,
4308 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4313 nodes_0_deserialized = nodes_0_deserialized_tmp;
4314 assert!(nodes_0_read.is_empty());
4316 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4317 nodes[0].node = &nodes_0_deserialized;
4318 assert_eq!(nodes[0].node.list_channels().len(), 1);
4319 check_added_monitors!(nodes[0], 1);
4321 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4322 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4323 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4324 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4326 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4327 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4328 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4329 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4331 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4332 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4333 for node in nodes.iter() {
4334 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4335 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4336 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4339 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4343 fn test_manager_serialize_deserialize_events() {
4344 // This test makes sure the events field in ChannelManager survives de/serialization
4345 let chanmon_cfgs = create_chanmon_cfgs(2);
4346 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4347 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4348 let fee_estimator: test_utils::TestFeeEstimator;
4349 let persister: test_utils::TestPersister;
4350 let logger: test_utils::TestLogger;
4351 let new_chain_monitor: test_utils::TestChainMonitor;
4352 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4353 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4355 // Start creating a channel, but stop right before broadcasting the funding transaction
4356 let channel_value = 100000;
4357 let push_msat = 10001;
4358 let a_flags = InitFeatures::known();
4359 let b_flags = InitFeatures::known();
4360 let node_a = nodes.remove(0);
4361 let node_b = nodes.remove(0);
4362 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4363 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()));
4364 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()));
4366 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4368 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4369 check_added_monitors!(node_a, 0);
4371 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()));
4373 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4374 assert_eq!(added_monitors.len(), 1);
4375 assert_eq!(added_monitors[0].0, funding_output);
4376 added_monitors.clear();
4379 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4380 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4382 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4383 assert_eq!(added_monitors.len(), 1);
4384 assert_eq!(added_monitors[0].0, funding_output);
4385 added_monitors.clear();
4387 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4392 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4393 let nodes_0_serialized = nodes[0].node.encode();
4394 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4395 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4397 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4398 logger = test_utils::TestLogger::new();
4399 persister = test_utils::TestPersister::new();
4400 let keys_manager = &chanmon_cfgs[0].keys_manager;
4401 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4402 nodes[0].chain_monitor = &new_chain_monitor;
4403 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4404 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4405 &mut chan_0_monitor_read, keys_manager).unwrap();
4406 assert!(chan_0_monitor_read.is_empty());
4408 let mut nodes_0_read = &nodes_0_serialized[..];
4409 let config = UserConfig::default();
4410 let (_, nodes_0_deserialized_tmp) = {
4411 let mut channel_monitors = HashMap::new();
4412 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4413 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4414 default_config: config,
4416 fee_estimator: &fee_estimator,
4417 chain_monitor: nodes[0].chain_monitor,
4418 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4423 nodes_0_deserialized = nodes_0_deserialized_tmp;
4424 assert!(nodes_0_read.is_empty());
4426 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4428 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4429 nodes[0].node = &nodes_0_deserialized;
4431 // After deserializing, make sure the funding_transaction is still held by the channel manager
4432 let events_4 = nodes[0].node.get_and_clear_pending_events();
4433 assert_eq!(events_4.len(), 0);
4434 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4435 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4437 // Make sure the channel is functioning as though the de/serialization never happened
4438 assert_eq!(nodes[0].node.list_channels().len(), 1);
4439 check_added_monitors!(nodes[0], 1);
4441 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4442 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4443 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4444 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4446 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4447 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4448 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4449 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4451 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4452 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4453 for node in nodes.iter() {
4454 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4455 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4456 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4459 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4463 fn test_simple_manager_serialize_deserialize() {
4464 let chanmon_cfgs = create_chanmon_cfgs(2);
4465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4467 let logger: test_utils::TestLogger;
4468 let fee_estimator: test_utils::TestFeeEstimator;
4469 let persister: test_utils::TestPersister;
4470 let new_chain_monitor: test_utils::TestChainMonitor;
4471 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4473 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4475 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4476 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4478 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4480 let nodes_0_serialized = nodes[0].node.encode();
4481 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4482 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4484 logger = test_utils::TestLogger::new();
4485 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4486 persister = test_utils::TestPersister::new();
4487 let keys_manager = &chanmon_cfgs[0].keys_manager;
4488 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4489 nodes[0].chain_monitor = &new_chain_monitor;
4490 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4491 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4492 &mut chan_0_monitor_read, keys_manager).unwrap();
4493 assert!(chan_0_monitor_read.is_empty());
4495 let mut nodes_0_read = &nodes_0_serialized[..];
4496 let (_, nodes_0_deserialized_tmp) = {
4497 let mut channel_monitors = HashMap::new();
4498 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4499 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4500 default_config: UserConfig::default(),
4502 fee_estimator: &fee_estimator,
4503 chain_monitor: nodes[0].chain_monitor,
4504 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4509 nodes_0_deserialized = nodes_0_deserialized_tmp;
4510 assert!(nodes_0_read.is_empty());
4512 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4513 nodes[0].node = &nodes_0_deserialized;
4514 check_added_monitors!(nodes[0], 1);
4516 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4518 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4519 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4523 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4524 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4525 let chanmon_cfgs = create_chanmon_cfgs(4);
4526 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4527 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4528 let logger: test_utils::TestLogger;
4529 let fee_estimator: test_utils::TestFeeEstimator;
4530 let persister: test_utils::TestPersister;
4531 let new_chain_monitor: test_utils::TestChainMonitor;
4532 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4533 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4534 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4535 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4536 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4538 let mut node_0_stale_monitors_serialized = Vec::new();
4539 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4540 let mut writer = test_utils::TestVecWriter(Vec::new());
4541 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4542 node_0_stale_monitors_serialized.push(writer.0);
4545 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4547 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4548 let nodes_0_serialized = nodes[0].node.encode();
4550 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4551 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4552 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4553 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4555 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4557 let mut node_0_monitors_serialized = Vec::new();
4558 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4559 let mut writer = test_utils::TestVecWriter(Vec::new());
4560 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4561 node_0_monitors_serialized.push(writer.0);
4564 logger = test_utils::TestLogger::new();
4565 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4566 persister = test_utils::TestPersister::new();
4567 let keys_manager = &chanmon_cfgs[0].keys_manager;
4568 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4569 nodes[0].chain_monitor = &new_chain_monitor;
4572 let mut node_0_stale_monitors = Vec::new();
4573 for serialized in node_0_stale_monitors_serialized.iter() {
4574 let mut read = &serialized[..];
4575 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4576 assert!(read.is_empty());
4577 node_0_stale_monitors.push(monitor);
4580 let mut node_0_monitors = Vec::new();
4581 for serialized in node_0_monitors_serialized.iter() {
4582 let mut read = &serialized[..];
4583 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4584 assert!(read.is_empty());
4585 node_0_monitors.push(monitor);
4588 let mut nodes_0_read = &nodes_0_serialized[..];
4589 if let Err(msgs::DecodeError::InvalidValue) =
4590 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4591 default_config: UserConfig::default(),
4593 fee_estimator: &fee_estimator,
4594 chain_monitor: nodes[0].chain_monitor,
4595 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4597 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4599 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4602 let mut nodes_0_read = &nodes_0_serialized[..];
4603 let (_, nodes_0_deserialized_tmp) =
4604 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4605 default_config: UserConfig::default(),
4607 fee_estimator: &fee_estimator,
4608 chain_monitor: nodes[0].chain_monitor,
4609 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4611 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4613 nodes_0_deserialized = nodes_0_deserialized_tmp;
4614 assert!(nodes_0_read.is_empty());
4616 { // Channel close should result in a commitment tx
4617 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4618 assert_eq!(txn.len(), 1);
4619 check_spends!(txn[0], funding_tx);
4620 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4623 for monitor in node_0_monitors.drain(..) {
4624 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4625 check_added_monitors!(nodes[0], 1);
4627 nodes[0].node = &nodes_0_deserialized;
4628 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4630 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4631 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4632 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4633 //... and we can even still claim the payment!
4634 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4636 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4637 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4638 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
4639 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4640 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4641 assert_eq!(msg_events.len(), 1);
4642 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4644 &ErrorAction::SendErrorMessage { ref msg } => {
4645 assert_eq!(msg.channel_id, channel_id);
4647 _ => panic!("Unexpected event!"),
4652 macro_rules! check_spendable_outputs {
4653 ($node: expr, $keysinterface: expr) => {
4655 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4656 let mut txn = Vec::new();
4657 let mut all_outputs = Vec::new();
4658 let secp_ctx = Secp256k1::new();
4659 for event in events.drain(..) {
4661 Event::SpendableOutputs { mut outputs } => {
4662 for outp in outputs.drain(..) {
4663 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4664 all_outputs.push(outp);
4667 _ => panic!("Unexpected event"),
4670 if all_outputs.len() > 1 {
4671 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) {
4681 fn test_claim_sizeable_push_msat() {
4682 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4683 let chanmon_cfgs = create_chanmon_cfgs(2);
4684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4686 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4688 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4689 nodes[1].node.force_close_channel(&chan.2).unwrap();
4690 check_closed_broadcast!(nodes[1], true);
4691 check_added_monitors!(nodes[1], 1);
4692 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4693 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4694 assert_eq!(node_txn.len(), 1);
4695 check_spends!(node_txn[0], chan.3);
4696 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
4698 mine_transaction(&nodes[1], &node_txn[0]);
4699 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4701 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4702 assert_eq!(spend_txn.len(), 1);
4703 assert_eq!(spend_txn[0].input.len(), 1);
4704 check_spends!(spend_txn[0], node_txn[0]);
4705 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4709 fn test_claim_on_remote_sizeable_push_msat() {
4710 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4711 // to_remote output is encumbered by a P2WPKH
4712 let chanmon_cfgs = create_chanmon_cfgs(2);
4713 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4714 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4715 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4717 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4718 nodes[0].node.force_close_channel(&chan.2).unwrap();
4719 check_closed_broadcast!(nodes[0], true);
4720 check_added_monitors!(nodes[0], 1);
4721 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4723 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4724 assert_eq!(node_txn.len(), 1);
4725 check_spends!(node_txn[0], chan.3);
4726 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
4728 mine_transaction(&nodes[1], &node_txn[0]);
4729 check_closed_broadcast!(nodes[1], true);
4730 check_added_monitors!(nodes[1], 1);
4731 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4732 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4734 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4735 assert_eq!(spend_txn.len(), 1);
4736 check_spends!(spend_txn[0], node_txn[0]);
4740 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4741 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4742 // to_remote output is encumbered by a P2WPKH
4744 let chanmon_cfgs = create_chanmon_cfgs(2);
4745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4749 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4750 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4751 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4752 assert_eq!(revoked_local_txn[0].input.len(), 1);
4753 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4755 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4756 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4757 check_closed_broadcast!(nodes[1], true);
4758 check_added_monitors!(nodes[1], 1);
4759 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4761 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4762 mine_transaction(&nodes[1], &node_txn[0]);
4763 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4765 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4766 assert_eq!(spend_txn.len(), 3);
4767 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4768 check_spends!(spend_txn[1], node_txn[0]);
4769 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4773 fn test_static_spendable_outputs_preimage_tx() {
4774 let chanmon_cfgs = create_chanmon_cfgs(2);
4775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4777 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779 // Create some initial channels
4780 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4782 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4784 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4785 assert_eq!(commitment_tx[0].input.len(), 1);
4786 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4788 // Settle A's commitment tx on B's chain
4789 assert!(nodes[1].node.claim_funds(payment_preimage));
4790 check_added_monitors!(nodes[1], 1);
4791 mine_transaction(&nodes[1], &commitment_tx[0]);
4792 check_added_monitors!(nodes[1], 1);
4793 let events = nodes[1].node.get_and_clear_pending_msg_events();
4795 MessageSendEvent::UpdateHTLCs { .. } => {},
4796 _ => panic!("Unexpected event"),
4799 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4800 _ => panic!("Unexepected event"),
4803 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4804 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4805 assert_eq!(node_txn.len(), 3);
4806 check_spends!(node_txn[0], commitment_tx[0]);
4807 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4808 check_spends!(node_txn[1], chan_1.3);
4809 check_spends!(node_txn[2], node_txn[1]);
4811 mine_transaction(&nodes[1], &node_txn[0]);
4812 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4813 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4815 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4816 assert_eq!(spend_txn.len(), 1);
4817 check_spends!(spend_txn[0], node_txn[0]);
4821 fn test_static_spendable_outputs_timeout_tx() {
4822 let chanmon_cfgs = create_chanmon_cfgs(2);
4823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4825 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4827 // Create some initial channels
4828 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4830 // Rebalance the network a bit by relaying one payment through all the channels ...
4831 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4833 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4835 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4836 assert_eq!(commitment_tx[0].input.len(), 1);
4837 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4839 // Settle A's commitment tx on B' chain
4840 mine_transaction(&nodes[1], &commitment_tx[0]);
4841 check_added_monitors!(nodes[1], 1);
4842 let events = nodes[1].node.get_and_clear_pending_msg_events();
4844 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4845 _ => panic!("Unexpected event"),
4847 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4849 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4850 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4851 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4852 check_spends!(node_txn[0], chan_1.3.clone());
4853 check_spends!(node_txn[1], commitment_tx[0].clone());
4854 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4856 mine_transaction(&nodes[1], &node_txn[1]);
4857 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4858 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4859 expect_payment_failed!(nodes[1], our_payment_hash, true);
4861 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4862 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4863 check_spends!(spend_txn[0], commitment_tx[0]);
4864 check_spends!(spend_txn[1], node_txn[1]);
4865 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4869 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4870 let chanmon_cfgs = create_chanmon_cfgs(2);
4871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4873 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4875 // Create some initial channels
4876 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4878 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4879 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4880 assert_eq!(revoked_local_txn[0].input.len(), 1);
4881 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4883 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4885 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4886 check_closed_broadcast!(nodes[1], true);
4887 check_added_monitors!(nodes[1], 1);
4888 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4890 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4891 assert_eq!(node_txn.len(), 2);
4892 assert_eq!(node_txn[0].input.len(), 2);
4893 check_spends!(node_txn[0], revoked_local_txn[0]);
4895 mine_transaction(&nodes[1], &node_txn[0]);
4896 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4898 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4899 assert_eq!(spend_txn.len(), 1);
4900 check_spends!(spend_txn[0], node_txn[0]);
4904 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4905 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4906 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4907 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4908 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4909 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4911 // Create some initial channels
4912 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4914 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4915 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4916 assert_eq!(revoked_local_txn[0].input.len(), 1);
4917 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4919 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4921 // A will generate HTLC-Timeout from revoked commitment tx
4922 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4923 check_closed_broadcast!(nodes[0], true);
4924 check_added_monitors!(nodes[0], 1);
4925 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4926 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4928 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4929 assert_eq!(revoked_htlc_txn.len(), 2);
4930 check_spends!(revoked_htlc_txn[0], chan_1.3);
4931 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4932 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4933 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4934 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4936 // B will generate justice tx from A's revoked commitment/HTLC tx
4937 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4938 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4939 check_closed_broadcast!(nodes[1], true);
4940 check_added_monitors!(nodes[1], 1);
4941 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4943 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4944 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4945 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4946 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4947 // transactions next...
4948 assert_eq!(node_txn[0].input.len(), 3);
4949 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4951 assert_eq!(node_txn[1].input.len(), 2);
4952 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4953 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4954 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4956 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4957 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4960 assert_eq!(node_txn[2].input.len(), 1);
4961 check_spends!(node_txn[2], chan_1.3);
4963 mine_transaction(&nodes[1], &node_txn[1]);
4964 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4966 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4967 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4968 assert_eq!(spend_txn.len(), 1);
4969 assert_eq!(spend_txn[0].input.len(), 1);
4970 check_spends!(spend_txn[0], node_txn[1]);
4974 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4975 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4976 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4977 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4978 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4979 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4981 // Create some initial channels
4982 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4984 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4985 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4986 assert_eq!(revoked_local_txn[0].input.len(), 1);
4987 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4989 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4990 assert_eq!(revoked_local_txn[0].output.len(), 2);
4992 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4994 // B will generate HTLC-Success from revoked commitment tx
4995 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4996 check_closed_broadcast!(nodes[1], true);
4997 check_added_monitors!(nodes[1], 1);
4998 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4999 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5001 assert_eq!(revoked_htlc_txn.len(), 2);
5002 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5003 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5004 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5006 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5007 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5008 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5010 // A will generate justice tx from B's revoked commitment/HTLC tx
5011 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5012 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5013 check_closed_broadcast!(nodes[0], true);
5014 check_added_monitors!(nodes[0], 1);
5015 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5017 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5018 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5020 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5021 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5022 // transactions next...
5023 assert_eq!(node_txn[0].input.len(), 2);
5024 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5025 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5026 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5028 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5029 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5032 assert_eq!(node_txn[1].input.len(), 1);
5033 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5035 check_spends!(node_txn[2], chan_1.3);
5037 mine_transaction(&nodes[0], &node_txn[1]);
5038 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5040 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5041 // didn't try to generate any new transactions.
5043 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5044 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5045 assert_eq!(spend_txn.len(), 3);
5046 assert_eq!(spend_txn[0].input.len(), 1);
5047 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5048 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5049 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5050 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5054 fn test_onchain_to_onchain_claim() {
5055 // Test that in case of channel closure, we detect the state of output and claim HTLC
5056 // on downstream peer's remote commitment tx.
5057 // First, have C claim an HTLC against its own latest commitment transaction.
5058 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5060 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5063 let chanmon_cfgs = create_chanmon_cfgs(3);
5064 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5065 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5066 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5068 // Create some initial channels
5069 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5070 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5072 // Ensure all nodes are at the same height
5073 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5074 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5075 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5076 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5078 // Rebalance the network a bit by relaying one payment through all the channels ...
5079 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5080 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5082 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5083 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5084 check_spends!(commitment_tx[0], chan_2.3);
5085 nodes[2].node.claim_funds(payment_preimage);
5086 check_added_monitors!(nodes[2], 1);
5087 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5088 assert!(updates.update_add_htlcs.is_empty());
5089 assert!(updates.update_fail_htlcs.is_empty());
5090 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5091 assert!(updates.update_fail_malformed_htlcs.is_empty());
5093 mine_transaction(&nodes[2], &commitment_tx[0]);
5094 check_closed_broadcast!(nodes[2], true);
5095 check_added_monitors!(nodes[2], 1);
5096 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5098 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5099 assert_eq!(c_txn.len(), 3);
5100 assert_eq!(c_txn[0], c_txn[2]);
5101 assert_eq!(commitment_tx[0], c_txn[1]);
5102 check_spends!(c_txn[1], chan_2.3);
5103 check_spends!(c_txn[2], c_txn[1]);
5104 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5105 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5106 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5107 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5109 // 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
5110 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5111 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5112 check_added_monitors!(nodes[1], 1);
5113 let events = nodes[1].node.get_and_clear_pending_events();
5114 assert_eq!(events.len(), 2);
5116 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5117 _ => panic!("Unexpected event"),
5120 Event::PaymentForwarded { fee_earned_msat, source_channel_id, claim_from_onchain_tx } => {
5121 assert_eq!(fee_earned_msat, Some(1000));
5122 assert_eq!(source_channel_id, Some(chan_1.2));
5123 assert_eq!(claim_from_onchain_tx, true);
5125 _ => panic!("Unexpected event"),
5128 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5129 // ChannelMonitor: claim tx
5130 assert_eq!(b_txn.len(), 1);
5131 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5134 check_added_monitors!(nodes[1], 1);
5135 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5136 assert_eq!(msg_events.len(), 3);
5137 match msg_events[0] {
5138 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5139 _ => panic!("Unexpected event"),
5141 match msg_events[1] {
5142 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5143 _ => panic!("Unexpected event"),
5145 match msg_events[2] {
5146 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, .. } } => {
5147 assert!(update_add_htlcs.is_empty());
5148 assert!(update_fail_htlcs.is_empty());
5149 assert_eq!(update_fulfill_htlcs.len(), 1);
5150 assert!(update_fail_malformed_htlcs.is_empty());
5151 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5153 _ => panic!("Unexpected event"),
5155 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5156 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5157 mine_transaction(&nodes[1], &commitment_tx[0]);
5158 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5159 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5160 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5161 assert_eq!(b_txn.len(), 3);
5162 check_spends!(b_txn[1], chan_1.3);
5163 check_spends!(b_txn[2], b_txn[1]);
5164 check_spends!(b_txn[0], commitment_tx[0]);
5165 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5166 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5167 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5169 check_closed_broadcast!(nodes[1], true);
5170 check_added_monitors!(nodes[1], 1);
5174 fn test_duplicate_payment_hash_one_failure_one_success() {
5175 // Topology : A --> B --> C --> D
5176 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5177 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5178 // we forward one of the payments onwards to D.
5179 let chanmon_cfgs = create_chanmon_cfgs(4);
5180 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5181 // When this test was written, the default base fee floated based on the HTLC count.
5182 // It is now fixed, so we simply set the fee to the expected value here.
5183 let mut config = test_default_channel_config();
5184 config.channel_options.forwarding_fee_base_msat = 196;
5185 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5186 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5187 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5189 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5190 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5191 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5193 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5194 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5195 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5196 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5197 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5199 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5201 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5202 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5203 // script push size limit so that the below script length checks match
5204 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5205 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5206 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5208 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5209 assert_eq!(commitment_txn[0].input.len(), 1);
5210 check_spends!(commitment_txn[0], chan_2.3);
5212 mine_transaction(&nodes[1], &commitment_txn[0]);
5213 check_closed_broadcast!(nodes[1], true);
5214 check_added_monitors!(nodes[1], 1);
5215 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5216 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5218 let htlc_timeout_tx;
5219 { // Extract one of the two HTLC-Timeout transaction
5220 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5221 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5222 assert_eq!(node_txn.len(), 4);
5223 check_spends!(node_txn[0], chan_2.3);
5225 check_spends!(node_txn[1], commitment_txn[0]);
5226 assert_eq!(node_txn[1].input.len(), 1);
5227 check_spends!(node_txn[2], commitment_txn[0]);
5228 assert_eq!(node_txn[2].input.len(), 1);
5229 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5230 check_spends!(node_txn[3], commitment_txn[0]);
5231 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5233 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5234 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5235 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5236 htlc_timeout_tx = node_txn[1].clone();
5239 nodes[2].node.claim_funds(our_payment_preimage);
5240 mine_transaction(&nodes[2], &commitment_txn[0]);
5241 check_added_monitors!(nodes[2], 2);
5242 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5243 let events = nodes[2].node.get_and_clear_pending_msg_events();
5245 MessageSendEvent::UpdateHTLCs { .. } => {},
5246 _ => panic!("Unexpected event"),
5249 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5250 _ => panic!("Unexepected event"),
5252 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5253 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)
5254 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5255 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5256 assert_eq!(htlc_success_txn[0].input.len(), 1);
5257 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5258 assert_eq!(htlc_success_txn[1].input.len(), 1);
5259 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5260 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5261 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5262 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5263 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5264 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5266 mine_transaction(&nodes[1], &htlc_timeout_tx);
5267 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5268 expect_pending_htlcs_forwardable!(nodes[1]);
5269 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5270 assert!(htlc_updates.update_add_htlcs.is_empty());
5271 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5272 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5273 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5274 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5275 check_added_monitors!(nodes[1], 1);
5277 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5278 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5280 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5282 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5284 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5285 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5286 // and nodes[2] fee) is rounded down and then claimed in full.
5287 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5288 expect_payment_forwarded!(nodes[1], nodes[0], Some(196*2), true);
5289 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5290 assert!(updates.update_add_htlcs.is_empty());
5291 assert!(updates.update_fail_htlcs.is_empty());
5292 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5293 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5294 assert!(updates.update_fail_malformed_htlcs.is_empty());
5295 check_added_monitors!(nodes[1], 1);
5297 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5298 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5300 let events = nodes[0].node.get_and_clear_pending_events();
5302 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5303 assert_eq!(*payment_preimage, our_payment_preimage);
5304 assert_eq!(*payment_hash, duplicate_payment_hash);
5306 _ => panic!("Unexpected event"),
5311 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5312 let chanmon_cfgs = create_chanmon_cfgs(2);
5313 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5314 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5315 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5317 // Create some initial channels
5318 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5320 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5321 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5322 assert_eq!(local_txn.len(), 1);
5323 assert_eq!(local_txn[0].input.len(), 1);
5324 check_spends!(local_txn[0], chan_1.3);
5326 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5327 nodes[1].node.claim_funds(payment_preimage);
5328 check_added_monitors!(nodes[1], 1);
5329 mine_transaction(&nodes[1], &local_txn[0]);
5330 check_added_monitors!(nodes[1], 1);
5331 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5332 let events = nodes[1].node.get_and_clear_pending_msg_events();
5334 MessageSendEvent::UpdateHTLCs { .. } => {},
5335 _ => panic!("Unexpected event"),
5338 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5339 _ => panic!("Unexepected event"),
5342 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5343 assert_eq!(node_txn.len(), 3);
5344 assert_eq!(node_txn[0], node_txn[2]);
5345 assert_eq!(node_txn[1], local_txn[0]);
5346 assert_eq!(node_txn[0].input.len(), 1);
5347 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5348 check_spends!(node_txn[0], local_txn[0]);
5352 mine_transaction(&nodes[1], &node_tx);
5353 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5355 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5356 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5357 assert_eq!(spend_txn.len(), 1);
5358 assert_eq!(spend_txn[0].input.len(), 1);
5359 check_spends!(spend_txn[0], node_tx);
5360 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5363 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5364 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5365 // unrevoked commitment transaction.
5366 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5367 // a remote RAA before they could be failed backwards (and combinations thereof).
5368 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5369 // use the same payment hashes.
5370 // Thus, we use a six-node network:
5375 // And test where C fails back to A/B when D announces its latest commitment transaction
5376 let chanmon_cfgs = create_chanmon_cfgs(6);
5377 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5378 // When this test was written, the default base fee floated based on the HTLC count.
5379 // It is now fixed, so we simply set the fee to the expected value here.
5380 let mut config = test_default_channel_config();
5381 config.channel_options.forwarding_fee_base_msat = 196;
5382 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5383 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5384 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5386 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5387 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5388 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5389 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5390 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5392 // Rebalance and check output sanity...
5393 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5394 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5395 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5397 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5399 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
5401 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
5402 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5404 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
5406 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
5408 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5410 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5411 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5413 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());
5415 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());
5418 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5420 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5421 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
5424 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
5426 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5427 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());
5429 // Double-check that six of the new HTLC were added
5430 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5431 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5432 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5433 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5435 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5436 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5437 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5438 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5439 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5440 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5441 check_added_monitors!(nodes[4], 0);
5442 expect_pending_htlcs_forwardable!(nodes[4]);
5443 check_added_monitors!(nodes[4], 1);
5445 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5446 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5447 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5448 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5449 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5450 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5452 // Fail 3rd below-dust and 7th above-dust HTLCs
5453 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5454 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5455 check_added_monitors!(nodes[5], 0);
5456 expect_pending_htlcs_forwardable!(nodes[5]);
5457 check_added_monitors!(nodes[5], 1);
5459 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5460 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5461 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5462 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5464 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5466 expect_pending_htlcs_forwardable!(nodes[3]);
5467 check_added_monitors!(nodes[3], 1);
5468 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5469 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5470 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5471 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5472 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5473 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5474 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5475 if deliver_last_raa {
5476 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5478 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5481 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5482 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5483 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5484 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5486 // We now broadcast the latest commitment transaction, which *should* result in failures for
5487 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5488 // the non-broadcast above-dust HTLCs.
5490 // Alternatively, we may broadcast the previous commitment transaction, which should only
5491 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5492 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5494 if announce_latest {
5495 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5497 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5499 let events = nodes[2].node.get_and_clear_pending_events();
5500 let close_event = if deliver_last_raa {
5501 assert_eq!(events.len(), 2);
5504 assert_eq!(events.len(), 1);
5508 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5509 _ => panic!("Unexpected event"),
5512 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5513 check_closed_broadcast!(nodes[2], true);
5514 if deliver_last_raa {
5515 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5517 expect_pending_htlcs_forwardable!(nodes[2]);
5519 check_added_monitors!(nodes[2], 3);
5521 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5522 assert_eq!(cs_msgs.len(), 2);
5523 let mut a_done = false;
5524 for msg in cs_msgs {
5526 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5527 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5528 // should be failed-backwards here.
5529 let target = if *node_id == nodes[0].node.get_our_node_id() {
5530 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5531 for htlc in &updates.update_fail_htlcs {
5532 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 });
5534 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5539 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5540 for htlc in &updates.update_fail_htlcs {
5541 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5543 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5544 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5547 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5548 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5549 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5550 if announce_latest {
5551 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5552 if *node_id == nodes[0].node.get_our_node_id() {
5553 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5556 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5558 _ => panic!("Unexpected event"),
5562 let as_events = nodes[0].node.get_and_clear_pending_events();
5563 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5564 let mut as_failds = HashSet::new();
5565 let mut as_updates = 0;
5566 for event in as_events.iter() {
5567 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5568 assert!(as_failds.insert(*payment_hash));
5569 if *payment_hash != payment_hash_2 {
5570 assert_eq!(*rejected_by_dest, deliver_last_raa);
5572 assert!(!rejected_by_dest);
5574 if network_update.is_some() {
5577 } else { panic!("Unexpected event"); }
5579 assert!(as_failds.contains(&payment_hash_1));
5580 assert!(as_failds.contains(&payment_hash_2));
5581 if announce_latest {
5582 assert!(as_failds.contains(&payment_hash_3));
5583 assert!(as_failds.contains(&payment_hash_5));
5585 assert!(as_failds.contains(&payment_hash_6));
5587 let bs_events = nodes[1].node.get_and_clear_pending_events();
5588 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5589 let mut bs_failds = HashSet::new();
5590 let mut bs_updates = 0;
5591 for event in bs_events.iter() {
5592 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5593 assert!(bs_failds.insert(*payment_hash));
5594 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5595 assert_eq!(*rejected_by_dest, deliver_last_raa);
5597 assert!(!rejected_by_dest);
5599 if network_update.is_some() {
5602 } else { panic!("Unexpected event"); }
5604 assert!(bs_failds.contains(&payment_hash_1));
5605 assert!(bs_failds.contains(&payment_hash_2));
5606 if announce_latest {
5607 assert!(bs_failds.contains(&payment_hash_4));
5609 assert!(bs_failds.contains(&payment_hash_5));
5611 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5612 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5613 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5614 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5615 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5616 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5620 fn test_fail_backwards_latest_remote_announce_a() {
5621 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5625 fn test_fail_backwards_latest_remote_announce_b() {
5626 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5630 fn test_fail_backwards_previous_remote_announce() {
5631 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5632 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5633 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5637 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5638 let chanmon_cfgs = create_chanmon_cfgs(2);
5639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5643 // Create some initial channels
5644 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5646 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5647 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5648 assert_eq!(local_txn[0].input.len(), 1);
5649 check_spends!(local_txn[0], chan_1.3);
5651 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5652 mine_transaction(&nodes[0], &local_txn[0]);
5653 check_closed_broadcast!(nodes[0], true);
5654 check_added_monitors!(nodes[0], 1);
5655 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5656 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5658 let htlc_timeout = {
5659 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5660 assert_eq!(node_txn.len(), 2);
5661 check_spends!(node_txn[0], chan_1.3);
5662 assert_eq!(node_txn[1].input.len(), 1);
5663 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5664 check_spends!(node_txn[1], local_txn[0]);
5668 mine_transaction(&nodes[0], &htlc_timeout);
5669 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5670 expect_payment_failed!(nodes[0], our_payment_hash, true);
5672 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5673 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5674 assert_eq!(spend_txn.len(), 3);
5675 check_spends!(spend_txn[0], local_txn[0]);
5676 assert_eq!(spend_txn[1].input.len(), 1);
5677 check_spends!(spend_txn[1], htlc_timeout);
5678 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5679 assert_eq!(spend_txn[2].input.len(), 2);
5680 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5681 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5682 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5686 fn test_key_derivation_params() {
5687 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5688 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5689 // let us re-derive the channel key set to then derive a delayed_payment_key.
5691 let chanmon_cfgs = create_chanmon_cfgs(3);
5693 // We manually create the node configuration to backup the seed.
5694 let seed = [42; 32];
5695 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5696 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);
5697 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() };
5698 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5699 node_cfgs.remove(0);
5700 node_cfgs.insert(0, node);
5702 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5703 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5705 // Create some initial channels
5706 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5708 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5709 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5710 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5712 // Ensure all nodes are at the same height
5713 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5714 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5715 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5716 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5718 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5719 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5720 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5721 assert_eq!(local_txn_1[0].input.len(), 1);
5722 check_spends!(local_txn_1[0], chan_1.3);
5724 // We check funding pubkey are unique
5725 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]));
5726 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]));
5727 if from_0_funding_key_0 == from_1_funding_key_0
5728 || from_0_funding_key_0 == from_1_funding_key_1
5729 || from_0_funding_key_1 == from_1_funding_key_0
5730 || from_0_funding_key_1 == from_1_funding_key_1 {
5731 panic!("Funding pubkeys aren't unique");
5734 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5735 mine_transaction(&nodes[0], &local_txn_1[0]);
5736 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5737 check_closed_broadcast!(nodes[0], true);
5738 check_added_monitors!(nodes[0], 1);
5739 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5741 let htlc_timeout = {
5742 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5743 assert_eq!(node_txn[1].input.len(), 1);
5744 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5745 check_spends!(node_txn[1], local_txn_1[0]);
5749 mine_transaction(&nodes[0], &htlc_timeout);
5750 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5751 expect_payment_failed!(nodes[0], our_payment_hash, true);
5753 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5754 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5755 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5756 assert_eq!(spend_txn.len(), 3);
5757 check_spends!(spend_txn[0], local_txn_1[0]);
5758 assert_eq!(spend_txn[1].input.len(), 1);
5759 check_spends!(spend_txn[1], htlc_timeout);
5760 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5761 assert_eq!(spend_txn[2].input.len(), 2);
5762 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5763 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5764 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5768 fn test_static_output_closing_tx() {
5769 let chanmon_cfgs = create_chanmon_cfgs(2);
5770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5772 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5774 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5776 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5777 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5779 mine_transaction(&nodes[0], &closing_tx);
5780 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5781 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5783 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5784 assert_eq!(spend_txn.len(), 1);
5785 check_spends!(spend_txn[0], closing_tx);
5787 mine_transaction(&nodes[1], &closing_tx);
5788 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5789 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5791 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5792 assert_eq!(spend_txn.len(), 1);
5793 check_spends!(spend_txn[0], closing_tx);
5796 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5797 let chanmon_cfgs = create_chanmon_cfgs(2);
5798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5800 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5801 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5803 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5805 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5806 // present in B's local commitment transaction, but none of A's commitment transactions.
5807 assert!(nodes[1].node.claim_funds(payment_preimage));
5808 check_added_monitors!(nodes[1], 1);
5810 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5811 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5812 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5814 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5815 check_added_monitors!(nodes[0], 1);
5816 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5817 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5818 check_added_monitors!(nodes[1], 1);
5820 let starting_block = nodes[1].best_block_info();
5821 let mut block = Block {
5822 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5825 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5826 connect_block(&nodes[1], &block);
5827 block.header.prev_blockhash = block.block_hash();
5829 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5830 check_closed_broadcast!(nodes[1], true);
5831 check_added_monitors!(nodes[1], 1);
5832 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5835 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5836 let chanmon_cfgs = create_chanmon_cfgs(2);
5837 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5838 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5839 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5840 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5842 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5843 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5844 check_added_monitors!(nodes[0], 1);
5846 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5848 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5849 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5850 // to "time out" the HTLC.
5852 let starting_block = nodes[1].best_block_info();
5853 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5856 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5857 header.prev_blockhash = header.block_hash();
5859 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5860 check_closed_broadcast!(nodes[0], true);
5861 check_added_monitors!(nodes[0], 1);
5862 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5865 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5866 let chanmon_cfgs = create_chanmon_cfgs(3);
5867 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5868 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5869 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5870 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5872 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5873 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5874 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5875 // actually revoked.
5876 let htlc_value = if use_dust { 50000 } else { 3000000 };
5877 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5878 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5879 expect_pending_htlcs_forwardable!(nodes[1]);
5880 check_added_monitors!(nodes[1], 1);
5882 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5883 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5884 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5885 check_added_monitors!(nodes[0], 1);
5886 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5887 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5888 check_added_monitors!(nodes[1], 1);
5889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5890 check_added_monitors!(nodes[1], 1);
5891 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5893 if check_revoke_no_close {
5894 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5895 check_added_monitors!(nodes[0], 1);
5898 let starting_block = nodes[1].best_block_info();
5899 let mut block = Block {
5900 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5903 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5904 connect_block(&nodes[0], &block);
5905 block.header.prev_blockhash = block.block_hash();
5907 if !check_revoke_no_close {
5908 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5909 check_closed_broadcast!(nodes[0], true);
5910 check_added_monitors!(nodes[0], 1);
5911 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5913 let events = nodes[0].node.get_and_clear_pending_events();
5914 assert_eq!(events.len(), 2);
5915 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5916 assert_eq!(*payment_hash, our_payment_hash);
5917 } else { panic!("Unexpected event"); }
5918 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5919 assert_eq!(*payment_hash, our_payment_hash);
5920 } else { panic!("Unexpected event"); }
5924 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5925 // There are only a few cases to test here:
5926 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5927 // broadcastable commitment transactions result in channel closure,
5928 // * its included in an unrevoked-but-previous remote commitment transaction,
5929 // * its included in the latest remote or local commitment transactions.
5930 // We test each of the three possible commitment transactions individually and use both dust and
5932 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5933 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5934 // tested for at least one of the cases in other tests.
5936 fn htlc_claim_single_commitment_only_a() {
5937 do_htlc_claim_local_commitment_only(true);
5938 do_htlc_claim_local_commitment_only(false);
5940 do_htlc_claim_current_remote_commitment_only(true);
5941 do_htlc_claim_current_remote_commitment_only(false);
5945 fn htlc_claim_single_commitment_only_b() {
5946 do_htlc_claim_previous_remote_commitment_only(true, false);
5947 do_htlc_claim_previous_remote_commitment_only(false, false);
5948 do_htlc_claim_previous_remote_commitment_only(true, true);
5949 do_htlc_claim_previous_remote_commitment_only(false, true);
5954 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5955 let chanmon_cfgs = create_chanmon_cfgs(2);
5956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5958 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5959 // Force duplicate randomness for every get-random call
5960 for node in nodes.iter() {
5961 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5964 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5965 let channel_value_satoshis=10000;
5966 let push_msat=10001;
5967 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5968 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5969 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5970 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5972 // Create a second channel with the same random values. This used to panic due to a colliding
5973 // channel_id, but now panics due to a colliding outbound SCID alias.
5974 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5978 fn bolt2_open_channel_sending_node_checks_part2() {
5979 let chanmon_cfgs = create_chanmon_cfgs(2);
5980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5984 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5985 let channel_value_satoshis=2^24;
5986 let push_msat=10001;
5987 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5989 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5990 let channel_value_satoshis=10000;
5991 // Test when push_msat is equal to 1000 * funding_satoshis.
5992 let push_msat=1000*channel_value_satoshis+1;
5993 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5995 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5996 let channel_value_satoshis=10000;
5997 let push_msat=10001;
5998 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
5999 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6000 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6002 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6003 // 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
6004 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6006 // 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.
6007 assert!(BREAKDOWN_TIMEOUT>0);
6008 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6010 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6011 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6012 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6014 // 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.
6015 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6016 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6017 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6018 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6019 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6023 fn bolt2_open_channel_sane_dust_limit() {
6024 let chanmon_cfgs = create_chanmon_cfgs(2);
6025 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6026 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6027 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6029 let channel_value_satoshis=1000000;
6030 let push_msat=10001;
6031 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6032 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6033 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
6034 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6036 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6037 let events = nodes[1].node.get_and_clear_pending_msg_events();
6038 let err_msg = match events[0] {
6039 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6042 _ => panic!("Unexpected event"),
6044 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6047 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6048 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6049 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6050 // is no longer affordable once it's freed.
6052 fn test_fail_holding_cell_htlc_upon_free() {
6053 let chanmon_cfgs = create_chanmon_cfgs(2);
6054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6056 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6057 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6059 // First nodes[0] generates an update_fee, setting the channel's
6060 // pending_update_fee.
6062 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6063 *feerate_lock += 20;
6065 nodes[0].node.timer_tick_occurred();
6066 check_added_monitors!(nodes[0], 1);
6068 let events = nodes[0].node.get_and_clear_pending_msg_events();
6069 assert_eq!(events.len(), 1);
6070 let (update_msg, commitment_signed) = match events[0] {
6071 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6072 (update_fee.as_ref(), commitment_signed)
6074 _ => panic!("Unexpected event"),
6077 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6079 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6080 let channel_reserve = chan_stat.channel_reserve_msat;
6081 let feerate = get_feerate!(nodes[0], chan.2);
6082 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6084 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6085 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6086 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6088 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6089 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6090 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6091 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6093 // Flush the pending fee update.
6094 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6095 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6096 check_added_monitors!(nodes[1], 1);
6097 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6098 check_added_monitors!(nodes[0], 1);
6100 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6101 // HTLC, but now that the fee has been raised the payment will now fail, causing
6102 // us to surface its failure to the user.
6103 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6104 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6105 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);
6106 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 {}",
6107 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6108 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6110 // Check that the payment failed to be sent out.
6111 let events = nodes[0].node.get_and_clear_pending_events();
6112 assert_eq!(events.len(), 1);
6114 &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, .. } => {
6115 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6116 assert_eq!(our_payment_hash.clone(), *payment_hash);
6117 assert_eq!(*rejected_by_dest, false);
6118 assert_eq!(*all_paths_failed, true);
6119 assert_eq!(*network_update, None);
6120 assert_eq!(*short_channel_id, None);
6121 assert_eq!(*error_code, None);
6122 assert_eq!(*error_data, None);
6124 _ => panic!("Unexpected event"),
6128 // Test that if multiple HTLCs are released from the holding cell and one is
6129 // valid but the other is no longer valid upon release, the valid HTLC can be
6130 // successfully completed while the other one fails as expected.
6132 fn test_free_and_fail_holding_cell_htlcs() {
6133 let chanmon_cfgs = create_chanmon_cfgs(2);
6134 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6135 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6136 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6137 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6139 // First nodes[0] generates an update_fee, setting the channel's
6140 // pending_update_fee.
6142 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6143 *feerate_lock += 200;
6145 nodes[0].node.timer_tick_occurred();
6146 check_added_monitors!(nodes[0], 1);
6148 let events = nodes[0].node.get_and_clear_pending_msg_events();
6149 assert_eq!(events.len(), 1);
6150 let (update_msg, commitment_signed) = match events[0] {
6151 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6152 (update_fee.as_ref(), commitment_signed)
6154 _ => panic!("Unexpected event"),
6157 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6159 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6160 let channel_reserve = chan_stat.channel_reserve_msat;
6161 let feerate = get_feerate!(nodes[0], chan.2);
6162 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6164 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6166 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6167 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6168 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6170 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6171 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6172 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6173 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6174 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6175 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6176 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6178 // Flush the pending fee update.
6179 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6180 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6181 check_added_monitors!(nodes[1], 1);
6182 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6183 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6184 check_added_monitors!(nodes[0], 2);
6186 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6187 // but now that the fee has been raised the second payment will now fail, causing us
6188 // to surface its failure to the user. The first payment should succeed.
6189 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6190 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6191 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);
6192 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 {}",
6193 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6194 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6196 // Check that the second payment failed to be sent out.
6197 let events = nodes[0].node.get_and_clear_pending_events();
6198 assert_eq!(events.len(), 1);
6200 &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, .. } => {
6201 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6202 assert_eq!(payment_hash_2.clone(), *payment_hash);
6203 assert_eq!(*rejected_by_dest, false);
6204 assert_eq!(*all_paths_failed, true);
6205 assert_eq!(*network_update, None);
6206 assert_eq!(*short_channel_id, None);
6207 assert_eq!(*error_code, None);
6208 assert_eq!(*error_data, None);
6210 _ => panic!("Unexpected event"),
6213 // Complete the first payment and the RAA from the fee update.
6214 let (payment_event, send_raa_event) = {
6215 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6216 assert_eq!(msgs.len(), 2);
6217 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6219 let raa = match send_raa_event {
6220 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6221 _ => panic!("Unexpected event"),
6223 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6224 check_added_monitors!(nodes[1], 1);
6225 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6226 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6227 let events = nodes[1].node.get_and_clear_pending_events();
6228 assert_eq!(events.len(), 1);
6230 Event::PendingHTLCsForwardable { .. } => {},
6231 _ => panic!("Unexpected event"),
6233 nodes[1].node.process_pending_htlc_forwards();
6234 let events = nodes[1].node.get_and_clear_pending_events();
6235 assert_eq!(events.len(), 1);
6237 Event::PaymentReceived { .. } => {},
6238 _ => panic!("Unexpected event"),
6240 nodes[1].node.claim_funds(payment_preimage_1);
6241 check_added_monitors!(nodes[1], 1);
6242 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6243 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6244 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6245 expect_payment_sent!(nodes[0], payment_preimage_1);
6248 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6249 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6250 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6253 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6254 let chanmon_cfgs = create_chanmon_cfgs(3);
6255 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6256 // When this test was written, the default base fee floated based on the HTLC count.
6257 // It is now fixed, so we simply set the fee to the expected value here.
6258 let mut config = test_default_channel_config();
6259 config.channel_options.forwarding_fee_base_msat = 196;
6260 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6261 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6262 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6263 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6265 // First nodes[1] generates an update_fee, setting the channel's
6266 // pending_update_fee.
6268 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6269 *feerate_lock += 20;
6271 nodes[1].node.timer_tick_occurred();
6272 check_added_monitors!(nodes[1], 1);
6274 let events = nodes[1].node.get_and_clear_pending_msg_events();
6275 assert_eq!(events.len(), 1);
6276 let (update_msg, commitment_signed) = match events[0] {
6277 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6278 (update_fee.as_ref(), commitment_signed)
6280 _ => panic!("Unexpected event"),
6283 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6285 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6286 let channel_reserve = chan_stat.channel_reserve_msat;
6287 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6288 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6290 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6292 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6293 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6294 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6295 let payment_event = {
6296 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6297 check_added_monitors!(nodes[0], 1);
6299 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6300 assert_eq!(events.len(), 1);
6302 SendEvent::from_event(events.remove(0))
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6305 check_added_monitors!(nodes[1], 0);
6306 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6307 expect_pending_htlcs_forwardable!(nodes[1]);
6309 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6310 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6312 // Flush the pending fee update.
6313 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6314 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6315 check_added_monitors!(nodes[2], 1);
6316 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6317 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6318 check_added_monitors!(nodes[1], 2);
6320 // A final RAA message is generated to finalize the fee update.
6321 let events = nodes[1].node.get_and_clear_pending_msg_events();
6322 assert_eq!(events.len(), 1);
6324 let raa_msg = match &events[0] {
6325 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6328 _ => panic!("Unexpected event"),
6331 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6332 check_added_monitors!(nodes[2], 1);
6333 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6335 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6336 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6337 assert_eq!(process_htlc_forwards_event.len(), 1);
6338 match &process_htlc_forwards_event[0] {
6339 &Event::PendingHTLCsForwardable { .. } => {},
6340 _ => panic!("Unexpected event"),
6343 // In response, we call ChannelManager's process_pending_htlc_forwards
6344 nodes[1].node.process_pending_htlc_forwards();
6345 check_added_monitors!(nodes[1], 1);
6347 // This causes the HTLC to be failed backwards.
6348 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6349 assert_eq!(fail_event.len(), 1);
6350 let (fail_msg, commitment_signed) = match &fail_event[0] {
6351 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6352 assert_eq!(updates.update_add_htlcs.len(), 0);
6353 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6354 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6355 assert_eq!(updates.update_fail_htlcs.len(), 1);
6356 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6358 _ => panic!("Unexpected event"),
6361 // Pass the failure messages back to nodes[0].
6362 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6363 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6365 // Complete the HTLC failure+removal process.
6366 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6367 check_added_monitors!(nodes[0], 1);
6368 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6369 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6370 check_added_monitors!(nodes[1], 2);
6371 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6372 assert_eq!(final_raa_event.len(), 1);
6373 let raa = match &final_raa_event[0] {
6374 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6375 _ => panic!("Unexpected event"),
6377 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6378 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6379 check_added_monitors!(nodes[0], 1);
6382 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6383 // 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.
6384 //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.
6387 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6388 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
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 = 100;
6398 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6399 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
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 less than their minimum HTLC value".to_string(), 1);
6405 fn test_update_add_htlc_bolt2_sender_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 (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6414 route.paths[0][0].fee_msat = 0;
6415 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6416 assert_eq!(err, "Cannot send 0-msat HTLC"));
6418 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6419 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6423 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6424 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6425 let chanmon_cfgs = create_chanmon_cfgs(2);
6426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6428 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6429 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6431 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6432 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6433 check_added_monitors!(nodes[0], 1);
6434 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6435 updates.update_add_htlcs[0].amount_msat = 0;
6437 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6438 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6439 check_closed_broadcast!(nodes[1], true).unwrap();
6440 check_added_monitors!(nodes[1], 1);
6441 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6445 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6446 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6447 //It is enforced when constructing a route.
6448 let chanmon_cfgs = create_chanmon_cfgs(2);
6449 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6450 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6451 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6452 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6454 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 0);
6455 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6456 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6457 assert_eq!(err, &"Channel CLTV overflowed?"));
6461 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6462 //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.
6463 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6464 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6465 let chanmon_cfgs = create_chanmon_cfgs(2);
6466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6468 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6469 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6470 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6472 for i in 0..max_accepted_htlcs {
6473 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6474 let payment_event = {
6475 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6476 check_added_monitors!(nodes[0], 1);
6478 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6479 assert_eq!(events.len(), 1);
6480 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6481 assert_eq!(htlcs[0].htlc_id, i);
6485 SendEvent::from_event(events.remove(0))
6487 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6488 check_added_monitors!(nodes[1], 0);
6489 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6491 expect_pending_htlcs_forwardable!(nodes[1]);
6492 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6494 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6495 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6496 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6498 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6499 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6503 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6504 //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.
6505 let chanmon_cfgs = create_chanmon_cfgs(2);
6506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6508 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6509 let channel_value = 100000;
6510 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6511 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6513 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6515 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6516 // Manually create a route over our max in flight (which our router normally automatically
6518 route.paths[0][0].fee_msat = max_in_flight + 1;
6519 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6520 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)));
6522 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6523 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);
6525 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6528 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6530 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6531 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6532 let chanmon_cfgs = create_chanmon_cfgs(2);
6533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6535 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6536 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6537 let htlc_minimum_msat: u64;
6539 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6540 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6541 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6544 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6545 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6546 check_added_monitors!(nodes[0], 1);
6547 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6548 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6549 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6550 assert!(nodes[1].node.list_channels().is_empty());
6551 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6552 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()));
6553 check_added_monitors!(nodes[1], 1);
6554 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6558 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6559 //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
6560 let chanmon_cfgs = create_chanmon_cfgs(2);
6561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6563 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6564 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6566 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6567 let channel_reserve = chan_stat.channel_reserve_msat;
6568 let feerate = get_feerate!(nodes[0], chan.2);
6569 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6570 // The 2* and +1 are for the fee spike reserve.
6571 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6573 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6574 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6575 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6576 check_added_monitors!(nodes[0], 1);
6577 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6579 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6580 // at this time channel-initiatee receivers are not required to enforce that senders
6581 // respect the fee_spike_reserve.
6582 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6583 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6585 assert!(nodes[1].node.list_channels().is_empty());
6586 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6587 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6588 check_added_monitors!(nodes[1], 1);
6589 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6593 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6594 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6595 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6596 let chanmon_cfgs = create_chanmon_cfgs(2);
6597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6599 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6600 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6602 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6603 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6604 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6605 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6606 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6607 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6609 let mut msg = msgs::UpdateAddHTLC {
6613 payment_hash: our_payment_hash,
6614 cltv_expiry: htlc_cltv,
6615 onion_routing_packet: onion_packet.clone(),
6618 for i in 0..super::channel::OUR_MAX_HTLCS {
6619 msg.htlc_id = i as u64;
6620 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6622 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6625 assert!(nodes[1].node.list_channels().is_empty());
6626 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6627 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6628 check_added_monitors!(nodes[1], 1);
6629 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6633 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6634 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6635 let chanmon_cfgs = create_chanmon_cfgs(2);
6636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6638 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6639 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6641 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6642 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6643 check_added_monitors!(nodes[0], 1);
6644 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6645 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6646 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6648 assert!(nodes[1].node.list_channels().is_empty());
6649 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6650 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6651 check_added_monitors!(nodes[1], 1);
6652 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6656 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6657 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6658 let chanmon_cfgs = create_chanmon_cfgs(2);
6659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6661 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6663 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6664 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6665 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6666 check_added_monitors!(nodes[0], 1);
6667 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6668 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6669 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6671 assert!(nodes[1].node.list_channels().is_empty());
6672 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6673 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6674 check_added_monitors!(nodes[1], 1);
6675 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6679 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6680 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6681 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6682 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6683 let chanmon_cfgs = create_chanmon_cfgs(2);
6684 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6685 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6686 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6689 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6690 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6691 check_added_monitors!(nodes[0], 1);
6692 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6693 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6695 //Disconnect and Reconnect
6696 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6697 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6698 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6699 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6700 assert_eq!(reestablish_1.len(), 1);
6701 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
6702 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6703 assert_eq!(reestablish_2.len(), 1);
6704 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6705 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6706 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6707 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6711 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6712 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6713 check_added_monitors!(nodes[1], 1);
6714 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6716 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6718 assert!(nodes[1].node.list_channels().is_empty());
6719 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6720 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6721 check_added_monitors!(nodes[1], 1);
6722 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6726 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6727 //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.
6729 let chanmon_cfgs = create_chanmon_cfgs(2);
6730 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6731 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6732 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6733 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6734 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6735 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6737 check_added_monitors!(nodes[0], 1);
6738 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6739 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6741 let update_msg = msgs::UpdateFulfillHTLC{
6744 payment_preimage: our_payment_preimage,
6747 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6749 assert!(nodes[0].node.list_channels().is_empty());
6750 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6751 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()));
6752 check_added_monitors!(nodes[0], 1);
6753 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6757 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6758 //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.
6760 let chanmon_cfgs = create_chanmon_cfgs(2);
6761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6764 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6766 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6767 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6768 check_added_monitors!(nodes[0], 1);
6769 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6770 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6772 let update_msg = msgs::UpdateFailHTLC{
6775 reason: msgs::OnionErrorPacket { data: Vec::new()},
6778 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6780 assert!(nodes[0].node.list_channels().is_empty());
6781 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6782 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()));
6783 check_added_monitors!(nodes[0], 1);
6784 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6788 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6789 //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.
6791 let chanmon_cfgs = create_chanmon_cfgs(2);
6792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6795 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6797 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6798 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6799 check_added_monitors!(nodes[0], 1);
6800 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6801 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6802 let update_msg = msgs::UpdateFailMalformedHTLC{
6805 sha256_of_onion: [1; 32],
6806 failure_code: 0x8000,
6809 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6811 assert!(nodes[0].node.list_channels().is_empty());
6812 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6813 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()));
6814 check_added_monitors!(nodes[0], 1);
6815 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6819 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6820 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6822 let chanmon_cfgs = create_chanmon_cfgs(2);
6823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6825 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6826 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6828 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6830 nodes[1].node.claim_funds(our_payment_preimage);
6831 check_added_monitors!(nodes[1], 1);
6833 let events = nodes[1].node.get_and_clear_pending_msg_events();
6834 assert_eq!(events.len(), 1);
6835 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6837 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, .. } } => {
6838 assert!(update_add_htlcs.is_empty());
6839 assert_eq!(update_fulfill_htlcs.len(), 1);
6840 assert!(update_fail_htlcs.is_empty());
6841 assert!(update_fail_malformed_htlcs.is_empty());
6842 assert!(update_fee.is_none());
6843 update_fulfill_htlcs[0].clone()
6845 _ => panic!("Unexpected event"),
6849 update_fulfill_msg.htlc_id = 1;
6851 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6853 assert!(nodes[0].node.list_channels().is_empty());
6854 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6855 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6856 check_added_monitors!(nodes[0], 1);
6857 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6861 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6862 //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.
6864 let chanmon_cfgs = create_chanmon_cfgs(2);
6865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6868 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6870 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6872 nodes[1].node.claim_funds(our_payment_preimage);
6873 check_added_monitors!(nodes[1], 1);
6875 let events = nodes[1].node.get_and_clear_pending_msg_events();
6876 assert_eq!(events.len(), 1);
6877 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6879 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, .. } } => {
6880 assert!(update_add_htlcs.is_empty());
6881 assert_eq!(update_fulfill_htlcs.len(), 1);
6882 assert!(update_fail_htlcs.is_empty());
6883 assert!(update_fail_malformed_htlcs.is_empty());
6884 assert!(update_fee.is_none());
6885 update_fulfill_htlcs[0].clone()
6887 _ => panic!("Unexpected event"),
6891 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6893 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6895 assert!(nodes[0].node.list_channels().is_empty());
6896 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6897 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6898 check_added_monitors!(nodes[0], 1);
6899 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6903 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6904 //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.
6906 let chanmon_cfgs = create_chanmon_cfgs(2);
6907 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6908 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6909 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6910 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6912 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6913 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6914 check_added_monitors!(nodes[0], 1);
6916 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6917 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6920 check_added_monitors!(nodes[1], 0);
6921 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6923 let events = nodes[1].node.get_and_clear_pending_msg_events();
6925 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6927 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, .. } } => {
6928 assert!(update_add_htlcs.is_empty());
6929 assert!(update_fulfill_htlcs.is_empty());
6930 assert!(update_fail_htlcs.is_empty());
6931 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6932 assert!(update_fee.is_none());
6933 update_fail_malformed_htlcs[0].clone()
6935 _ => panic!("Unexpected event"),
6938 update_msg.failure_code &= !0x8000;
6939 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6941 assert!(nodes[0].node.list_channels().is_empty());
6942 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6943 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6944 check_added_monitors!(nodes[0], 1);
6945 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6949 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6950 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6951 // * 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.
6953 let chanmon_cfgs = create_chanmon_cfgs(3);
6954 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6955 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6956 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6957 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6958 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6960 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6963 let mut payment_event = {
6964 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6965 check_added_monitors!(nodes[0], 1);
6966 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6967 assert_eq!(events.len(), 1);
6968 SendEvent::from_event(events.remove(0))
6970 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6971 check_added_monitors!(nodes[1], 0);
6972 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6973 expect_pending_htlcs_forwardable!(nodes[1]);
6974 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6975 assert_eq!(events_2.len(), 1);
6976 check_added_monitors!(nodes[1], 1);
6977 payment_event = SendEvent::from_event(events_2.remove(0));
6978 assert_eq!(payment_event.msgs.len(), 1);
6981 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6982 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6983 check_added_monitors!(nodes[2], 0);
6984 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6986 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6987 assert_eq!(events_3.len(), 1);
6988 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6990 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6991 assert!(update_add_htlcs.is_empty());
6992 assert!(update_fulfill_htlcs.is_empty());
6993 assert!(update_fail_htlcs.is_empty());
6994 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6995 assert!(update_fee.is_none());
6996 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6998 _ => panic!("Unexpected event"),
7002 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7004 check_added_monitors!(nodes[1], 0);
7005 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7006 expect_pending_htlcs_forwardable!(nodes[1]);
7007 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7008 assert_eq!(events_4.len(), 1);
7010 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7012 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, .. } } => {
7013 assert!(update_add_htlcs.is_empty());
7014 assert!(update_fulfill_htlcs.is_empty());
7015 assert_eq!(update_fail_htlcs.len(), 1);
7016 assert!(update_fail_malformed_htlcs.is_empty());
7017 assert!(update_fee.is_none());
7019 _ => panic!("Unexpected event"),
7022 check_added_monitors!(nodes[1], 1);
7025 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7026 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7027 // 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
7028 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7030 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7031 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7032 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7033 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7034 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7035 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7037 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7039 // We route 2 dust-HTLCs between A and B
7040 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7041 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7042 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7044 // Cache one local commitment tx as previous
7045 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7047 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7048 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7049 check_added_monitors!(nodes[1], 0);
7050 expect_pending_htlcs_forwardable!(nodes[1]);
7051 check_added_monitors!(nodes[1], 1);
7053 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7054 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7055 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7056 check_added_monitors!(nodes[0], 1);
7058 // Cache one local commitment tx as lastest
7059 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7061 let events = nodes[0].node.get_and_clear_pending_msg_events();
7063 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7064 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7066 _ => panic!("Unexpected event"),
7069 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7070 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7072 _ => panic!("Unexpected event"),
7075 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7076 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7077 if announce_latest {
7078 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7080 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7083 check_closed_broadcast!(nodes[0], true);
7084 check_added_monitors!(nodes[0], 1);
7085 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7087 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7088 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7089 let events = nodes[0].node.get_and_clear_pending_events();
7090 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7091 assert_eq!(events.len(), 2);
7092 let mut first_failed = false;
7093 for event in events {
7095 Event::PaymentPathFailed { payment_hash, .. } => {
7096 if payment_hash == payment_hash_1 {
7097 assert!(!first_failed);
7098 first_failed = true;
7100 assert_eq!(payment_hash, payment_hash_2);
7103 _ => panic!("Unexpected event"),
7109 fn test_failure_delay_dust_htlc_local_commitment() {
7110 do_test_failure_delay_dust_htlc_local_commitment(true);
7111 do_test_failure_delay_dust_htlc_local_commitment(false);
7114 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7115 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7116 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7117 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7118 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7119 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7120 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7122 let chanmon_cfgs = create_chanmon_cfgs(3);
7123 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7124 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7125 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7126 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7128 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7130 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7131 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7133 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7134 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7136 // We revoked bs_commitment_tx
7138 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7139 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7142 let mut timeout_tx = Vec::new();
7144 // We fail dust-HTLC 1 by broadcast of local commitment tx
7145 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7146 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7147 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7148 expect_payment_failed!(nodes[0], dust_hash, true);
7150 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7151 check_closed_broadcast!(nodes[0], true);
7152 check_added_monitors!(nodes[0], 1);
7153 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7154 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7155 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7156 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7157 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7158 mine_transaction(&nodes[0], &timeout_tx[0]);
7159 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7160 expect_payment_failed!(nodes[0], non_dust_hash, true);
7162 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7163 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7164 check_closed_broadcast!(nodes[0], true);
7165 check_added_monitors!(nodes[0], 1);
7166 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7167 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7168 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7169 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7171 expect_payment_failed!(nodes[0], dust_hash, true);
7172 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7173 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7174 mine_transaction(&nodes[0], &timeout_tx[0]);
7175 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7176 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7177 expect_payment_failed!(nodes[0], non_dust_hash, true);
7179 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7181 let events = nodes[0].node.get_and_clear_pending_events();
7182 assert_eq!(events.len(), 2);
7185 Event::PaymentPathFailed { payment_hash, .. } => {
7186 if payment_hash == dust_hash { first = true; }
7187 else { first = false; }
7189 _ => panic!("Unexpected event"),
7192 Event::PaymentPathFailed { payment_hash, .. } => {
7193 if first { assert_eq!(payment_hash, non_dust_hash); }
7194 else { assert_eq!(payment_hash, dust_hash); }
7196 _ => panic!("Unexpected event"),
7203 fn test_sweep_outbound_htlc_failure_update() {
7204 do_test_sweep_outbound_htlc_failure_update(false, true);
7205 do_test_sweep_outbound_htlc_failure_update(false, false);
7206 do_test_sweep_outbound_htlc_failure_update(true, false);
7210 fn test_user_configurable_csv_delay() {
7211 // We test our channel constructors yield errors when we pass them absurd csv delay
7213 let mut low_our_to_self_config = UserConfig::default();
7214 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7215 let mut high_their_to_self_config = UserConfig::default();
7216 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7217 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7218 let chanmon_cfgs = create_chanmon_cfgs(2);
7219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7221 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7223 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7224 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7225 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7226 &low_our_to_self_config, 0, 42)
7229 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())); },
7230 _ => panic!("Unexpected event"),
7232 } else { assert!(false) }
7234 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7235 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7236 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7237 open_channel.to_self_delay = 200;
7238 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7239 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7240 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7243 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())); },
7244 _ => panic!("Unexpected event"),
7246 } else { assert!(false); }
7248 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7249 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7250 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()));
7251 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7252 accept_channel.to_self_delay = 200;
7253 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7255 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7257 &ErrorAction::SendErrorMessage { ref msg } => {
7258 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()));
7259 reason_msg = msg.data.clone();
7263 } else { panic!(); }
7264 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7266 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7267 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7268 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7269 open_channel.to_self_delay = 200;
7270 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7271 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7272 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7275 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())); },
7276 _ => panic!("Unexpected event"),
7278 } else { assert!(false); }
7282 fn test_data_loss_protect() {
7283 // We want to be sure that :
7284 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7285 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7286 // * we close channel in case of detecting other being fallen behind
7287 // * we are able to claim our own outputs thanks to to_remote being static
7288 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7294 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7295 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7296 // during signing due to revoked tx
7297 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7298 let keys_manager = &chanmon_cfgs[0].keys_manager;
7301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7303 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7305 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7307 // Cache node A state before any channel update
7308 let previous_node_state = nodes[0].node.encode();
7309 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7310 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7312 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7313 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7315 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7316 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7318 // Restore node A from previous state
7319 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7320 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7321 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7322 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7323 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7324 persister = test_utils::TestPersister::new();
7325 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7327 let mut channel_monitors = HashMap::new();
7328 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7329 <(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 {
7330 keys_manager: keys_manager,
7331 fee_estimator: &fee_estimator,
7332 chain_monitor: &monitor,
7334 tx_broadcaster: &tx_broadcaster,
7335 default_config: UserConfig::default(),
7339 nodes[0].node = &node_state_0;
7340 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7341 nodes[0].chain_monitor = &monitor;
7342 nodes[0].chain_source = &chain_source;
7344 check_added_monitors!(nodes[0], 1);
7346 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7347 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7349 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7351 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7352 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7353 check_added_monitors!(nodes[0], 1);
7356 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7357 assert_eq!(node_txn.len(), 0);
7360 let mut reestablish_1 = Vec::with_capacity(1);
7361 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7362 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7363 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7364 reestablish_1.push(msg.clone());
7365 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7366 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7368 &ErrorAction::SendErrorMessage { ref msg } => {
7369 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");
7371 _ => panic!("Unexpected event!"),
7374 panic!("Unexpected event")
7378 // Check we close channel detecting A is fallen-behind
7379 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7380 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7381 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7382 check_added_monitors!(nodes[1], 1);
7384 // Check A is able to claim to_remote output
7385 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7386 assert_eq!(node_txn.len(), 1);
7387 check_spends!(node_txn[0], chan.3);
7388 assert_eq!(node_txn[0].output.len(), 2);
7389 mine_transaction(&nodes[0], &node_txn[0]);
7390 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7391 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() });
7392 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7393 assert_eq!(spend_txn.len(), 1);
7394 check_spends!(spend_txn[0], node_txn[0]);
7398 fn test_check_htlc_underpaying() {
7399 // Send payment through A -> B but A is maliciously
7400 // sending a probe payment (i.e less than expected value0
7401 // to B, B should refuse payment.
7403 let chanmon_cfgs = create_chanmon_cfgs(2);
7404 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7405 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7406 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7408 // Create some initial channels
7409 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7411 let scorer = test_utils::TestScorer::with_penalty(0);
7412 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7413 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7414 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7415 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7416 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7417 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7418 check_added_monitors!(nodes[0], 1);
7420 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7421 assert_eq!(events.len(), 1);
7422 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7423 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7424 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7426 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7427 // and then will wait a second random delay before failing the HTLC back:
7428 expect_pending_htlcs_forwardable!(nodes[1]);
7429 expect_pending_htlcs_forwardable!(nodes[1]);
7431 // Node 3 is expecting payment of 100_000 but received 10_000,
7432 // it should fail htlc like we didn't know the preimage.
7433 nodes[1].node.process_pending_htlc_forwards();
7435 let events = nodes[1].node.get_and_clear_pending_msg_events();
7436 assert_eq!(events.len(), 1);
7437 let (update_fail_htlc, commitment_signed) = match events[0] {
7438 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 } } => {
7439 assert!(update_add_htlcs.is_empty());
7440 assert!(update_fulfill_htlcs.is_empty());
7441 assert_eq!(update_fail_htlcs.len(), 1);
7442 assert!(update_fail_malformed_htlcs.is_empty());
7443 assert!(update_fee.is_none());
7444 (update_fail_htlcs[0].clone(), commitment_signed)
7446 _ => panic!("Unexpected event"),
7448 check_added_monitors!(nodes[1], 1);
7450 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7451 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7453 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7454 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7455 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7456 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7460 fn test_announce_disable_channels() {
7461 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7462 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7464 let chanmon_cfgs = create_chanmon_cfgs(2);
7465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7467 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7469 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7470 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7471 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7474 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7475 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7477 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7478 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7479 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7480 assert_eq!(msg_events.len(), 3);
7481 let mut chans_disabled = HashMap::new();
7482 for e in msg_events {
7484 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7485 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7486 // Check that each channel gets updated exactly once
7487 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7488 panic!("Generated ChannelUpdate for wrong chan!");
7491 _ => panic!("Unexpected event"),
7495 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7496 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7497 assert_eq!(reestablish_1.len(), 3);
7498 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty(), remote_network_address: None });
7499 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7500 assert_eq!(reestablish_2.len(), 3);
7502 // Reestablish chan_1
7503 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7504 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7505 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7506 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7507 // Reestablish chan_2
7508 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7509 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7510 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7511 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7512 // Reestablish chan_3
7513 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7514 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7515 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7516 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7518 nodes[0].node.timer_tick_occurred();
7519 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7520 nodes[0].node.timer_tick_occurred();
7521 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7522 assert_eq!(msg_events.len(), 3);
7523 for e in msg_events {
7525 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7526 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7527 match chans_disabled.remove(&msg.contents.short_channel_id) {
7528 // Each update should have a higher timestamp than the previous one, replacing
7530 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7531 None => panic!("Generated ChannelUpdate for wrong chan!"),
7534 _ => panic!("Unexpected event"),
7537 // Check that each channel gets updated exactly once
7538 assert!(chans_disabled.is_empty());
7542 fn test_bump_penalty_txn_on_revoked_commitment() {
7543 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7544 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7546 let chanmon_cfgs = create_chanmon_cfgs(2);
7547 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7548 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7549 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7551 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7553 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7554 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7555 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7557 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7558 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7559 assert_eq!(revoked_txn[0].output.len(), 4);
7560 assert_eq!(revoked_txn[0].input.len(), 1);
7561 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7562 let revoked_txid = revoked_txn[0].txid();
7564 let mut penalty_sum = 0;
7565 for outp in revoked_txn[0].output.iter() {
7566 if outp.script_pubkey.is_v0_p2wsh() {
7567 penalty_sum += outp.value;
7571 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7572 let header_114 = connect_blocks(&nodes[1], 14);
7574 // Actually revoke tx by claiming a HTLC
7575 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7576 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7577 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7578 check_added_monitors!(nodes[1], 1);
7580 // One or more justice tx should have been broadcast, check it
7584 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7585 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7586 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7587 assert_eq!(node_txn[0].output.len(), 1);
7588 check_spends!(node_txn[0], revoked_txn[0]);
7589 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7590 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7591 penalty_1 = node_txn[0].txid();
7595 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7596 connect_blocks(&nodes[1], 15);
7597 let mut penalty_2 = penalty_1;
7598 let mut feerate_2 = 0;
7600 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7601 assert_eq!(node_txn.len(), 1);
7602 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7603 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7604 assert_eq!(node_txn[0].output.len(), 1);
7605 check_spends!(node_txn[0], revoked_txn[0]);
7606 penalty_2 = node_txn[0].txid();
7607 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7608 assert_ne!(penalty_2, penalty_1);
7609 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7610 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7611 // Verify 25% bump heuristic
7612 assert!(feerate_2 * 100 >= feerate_1 * 125);
7616 assert_ne!(feerate_2, 0);
7618 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7619 connect_blocks(&nodes[1], 1);
7621 let mut feerate_3 = 0;
7623 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7624 assert_eq!(node_txn.len(), 1);
7625 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7626 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7627 assert_eq!(node_txn[0].output.len(), 1);
7628 check_spends!(node_txn[0], revoked_txn[0]);
7629 penalty_3 = node_txn[0].txid();
7630 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7631 assert_ne!(penalty_3, penalty_2);
7632 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7633 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7634 // Verify 25% bump heuristic
7635 assert!(feerate_3 * 100 >= feerate_2 * 125);
7639 assert_ne!(feerate_3, 0);
7641 nodes[1].node.get_and_clear_pending_events();
7642 nodes[1].node.get_and_clear_pending_msg_events();
7646 fn test_bump_penalty_txn_on_revoked_htlcs() {
7647 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7648 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7650 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7651 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7654 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7656 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7657 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7658 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7659 let scorer = test_utils::TestScorer::with_penalty(0);
7660 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7661 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7662 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7663 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7664 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7665 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7666 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7667 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7669 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7670 assert_eq!(revoked_local_txn[0].input.len(), 1);
7671 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7673 // Revoke local commitment tx
7674 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7676 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7677 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7678 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7679 check_closed_broadcast!(nodes[1], true);
7680 check_added_monitors!(nodes[1], 1);
7681 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7682 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7684 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7685 assert_eq!(revoked_htlc_txn.len(), 3);
7686 check_spends!(revoked_htlc_txn[1], chan.3);
7688 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7689 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7690 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7692 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7693 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7694 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7695 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7697 // Broadcast set of revoked txn on A
7698 let hash_128 = connect_blocks(&nodes[0], 40);
7699 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7700 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7701 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7702 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7703 let events = nodes[0].node.get_and_clear_pending_events();
7704 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7706 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7707 _ => panic!("Unexpected event"),
7713 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7714 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7715 // Verify claim tx are spending revoked HTLC txn
7717 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7718 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7719 // which are included in the same block (they are broadcasted because we scan the
7720 // transactions linearly and generate claims as we go, they likely should be removed in the
7722 assert_eq!(node_txn[0].input.len(), 1);
7723 check_spends!(node_txn[0], revoked_local_txn[0]);
7724 assert_eq!(node_txn[1].input.len(), 1);
7725 check_spends!(node_txn[1], revoked_local_txn[0]);
7726 assert_eq!(node_txn[2].input.len(), 1);
7727 check_spends!(node_txn[2], revoked_local_txn[0]);
7729 // Each of the three justice transactions claim a separate (single) output of the three
7730 // available, which we check here:
7731 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7732 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7733 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7735 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7736 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7738 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7739 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7740 // a remote commitment tx has already been confirmed).
7741 check_spends!(node_txn[3], chan.3);
7743 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7744 // output, checked above).
7745 assert_eq!(node_txn[4].input.len(), 2);
7746 assert_eq!(node_txn[4].output.len(), 1);
7747 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7749 first = node_txn[4].txid();
7750 // Store both feerates for later comparison
7751 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7752 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7753 penalty_txn = vec![node_txn[2].clone()];
7757 // Connect one more block to see if bumped penalty are issued for HTLC txn
7758 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7759 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7760 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7761 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7763 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7764 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7766 check_spends!(node_txn[0], revoked_local_txn[0]);
7767 check_spends!(node_txn[1], revoked_local_txn[0]);
7768 // Note that these are both bogus - they spend outputs already claimed in block 129:
7769 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7770 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7772 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7773 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7779 // Few more blocks to confirm penalty txn
7780 connect_blocks(&nodes[0], 4);
7781 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7782 let header_144 = connect_blocks(&nodes[0], 9);
7784 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7785 assert_eq!(node_txn.len(), 1);
7787 assert_eq!(node_txn[0].input.len(), 2);
7788 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7789 // Verify bumped tx is different and 25% bump heuristic
7790 assert_ne!(first, node_txn[0].txid());
7791 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7792 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7793 assert!(feerate_2 * 100 > feerate_1 * 125);
7794 let txn = vec![node_txn[0].clone()];
7798 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7799 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7800 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7801 connect_blocks(&nodes[0], 20);
7803 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7804 // We verify than no new transaction has been broadcast because previously
7805 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7806 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7807 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7808 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7809 // up bumped justice generation.
7810 assert_eq!(node_txn.len(), 0);
7813 check_closed_broadcast!(nodes[0], true);
7814 check_added_monitors!(nodes[0], 1);
7818 fn test_bump_penalty_txn_on_remote_commitment() {
7819 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7820 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7823 // Provide preimage for one
7824 // Check aggregation
7826 let chanmon_cfgs = create_chanmon_cfgs(2);
7827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7829 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7831 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7832 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7833 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7835 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7836 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7837 assert_eq!(remote_txn[0].output.len(), 4);
7838 assert_eq!(remote_txn[0].input.len(), 1);
7839 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7841 // Claim a HTLC without revocation (provide B monitor with preimage)
7842 nodes[1].node.claim_funds(payment_preimage);
7843 mine_transaction(&nodes[1], &remote_txn[0]);
7844 check_added_monitors!(nodes[1], 2);
7845 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7847 // One or more claim tx should have been broadcast, check it
7851 let feerate_timeout;
7852 let feerate_preimage;
7854 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855 // 9 transactions including:
7856 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7857 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7858 // 2 * HTLC-Success (one RBF bump we'll check later)
7860 assert_eq!(node_txn.len(), 8);
7861 assert_eq!(node_txn[0].input.len(), 1);
7862 assert_eq!(node_txn[6].input.len(), 1);
7863 check_spends!(node_txn[0], remote_txn[0]);
7864 check_spends!(node_txn[6], remote_txn[0]);
7865 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7866 preimage_bump = node_txn[3].clone();
7868 check_spends!(node_txn[1], chan.3);
7869 check_spends!(node_txn[2], node_txn[1]);
7870 assert_eq!(node_txn[1], node_txn[4]);
7871 assert_eq!(node_txn[2], node_txn[5]);
7873 timeout = node_txn[6].txid();
7874 let index = node_txn[6].input[0].previous_output.vout;
7875 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7876 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7878 preimage = node_txn[0].txid();
7879 let index = node_txn[0].input[0].previous_output.vout;
7880 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7881 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7885 assert_ne!(feerate_timeout, 0);
7886 assert_ne!(feerate_preimage, 0);
7888 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7889 connect_blocks(&nodes[1], 15);
7891 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7892 assert_eq!(node_txn.len(), 1);
7893 assert_eq!(node_txn[0].input.len(), 1);
7894 assert_eq!(preimage_bump.input.len(), 1);
7895 check_spends!(node_txn[0], remote_txn[0]);
7896 check_spends!(preimage_bump, remote_txn[0]);
7898 let index = preimage_bump.input[0].previous_output.vout;
7899 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7900 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7901 assert!(new_feerate * 100 > feerate_timeout * 125);
7902 assert_ne!(timeout, preimage_bump.txid());
7904 let index = node_txn[0].input[0].previous_output.vout;
7905 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7906 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7907 assert!(new_feerate * 100 > feerate_preimage * 125);
7908 assert_ne!(preimage, node_txn[0].txid());
7913 nodes[1].node.get_and_clear_pending_events();
7914 nodes[1].node.get_and_clear_pending_msg_events();
7918 fn test_counterparty_raa_skip_no_crash() {
7919 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7920 // commitment transaction, we would have happily carried on and provided them the next
7921 // commitment transaction based on one RAA forward. This would probably eventually have led to
7922 // channel closure, but it would not have resulted in funds loss. Still, our
7923 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7924 // check simply that the channel is closed in response to such an RAA, but don't check whether
7925 // we decide to punish our counterparty for revoking their funds (as we don't currently
7927 let chanmon_cfgs = create_chanmon_cfgs(2);
7928 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7929 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7930 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7931 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7933 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7934 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7936 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7938 // Make signer believe we got a counterparty signature, so that it allows the revocation
7939 keys.get_enforcement_state().last_holder_commitment -= 1;
7940 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7942 // Must revoke without gaps
7943 keys.get_enforcement_state().last_holder_commitment -= 1;
7944 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7946 keys.get_enforcement_state().last_holder_commitment -= 1;
7947 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7948 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7950 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7951 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7952 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7953 check_added_monitors!(nodes[1], 1);
7954 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7958 fn test_bump_txn_sanitize_tracking_maps() {
7959 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7960 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7962 let chanmon_cfgs = create_chanmon_cfgs(2);
7963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7965 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7967 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7968 // Lock HTLC in both directions
7969 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7970 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7972 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7973 assert_eq!(revoked_local_txn[0].input.len(), 1);
7974 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7976 // Revoke local commitment tx
7977 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7979 // Broadcast set of revoked txn on A
7980 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7981 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7982 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7984 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7985 check_closed_broadcast!(nodes[0], true);
7986 check_added_monitors!(nodes[0], 1);
7987 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7989 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7990 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7991 check_spends!(node_txn[0], revoked_local_txn[0]);
7992 check_spends!(node_txn[1], revoked_local_txn[0]);
7993 check_spends!(node_txn[2], revoked_local_txn[0]);
7994 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7998 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7999 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8000 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8002 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8003 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8004 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8009 fn test_pending_claimed_htlc_no_balance_underflow() {
8010 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
8011 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
8012 let chanmon_cfgs = create_chanmon_cfgs(2);
8013 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8014 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8015 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8016 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
8018 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
8019 nodes[1].node.claim_funds(payment_preimage);
8020 check_added_monitors!(nodes[1], 1);
8021 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8023 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
8024 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
8025 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
8026 check_added_monitors!(nodes[0], 1);
8027 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
8029 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
8030 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
8031 // can get our balance.
8033 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
8034 // the public key of the only hop. This works around ChannelDetails not showing the
8035 // almost-claimed HTLC as available balance.
8036 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
8037 route.payment_params = None; // This is all wrong, but unnecessary
8038 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
8039 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8040 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8042 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8046 fn test_channel_conf_timeout() {
8047 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8048 // confirm within 2016 blocks, as recommended by BOLT 2.
8049 let chanmon_cfgs = create_chanmon_cfgs(2);
8050 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8051 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8052 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8054 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8056 // The outbound node should wait forever for confirmation:
8057 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8058 // copied here instead of directly referencing the constant.
8059 connect_blocks(&nodes[0], 2016);
8060 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8062 // The inbound node should fail the channel after exactly 2016 blocks
8063 connect_blocks(&nodes[1], 2015);
8064 check_added_monitors!(nodes[1], 0);
8065 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8067 connect_blocks(&nodes[1], 1);
8068 check_added_monitors!(nodes[1], 1);
8069 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8070 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8071 assert_eq!(close_ev.len(), 1);
8073 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8074 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8075 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8077 _ => panic!("Unexpected event"),
8082 fn test_override_channel_config() {
8083 let chanmon_cfgs = create_chanmon_cfgs(2);
8084 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8085 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8086 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8088 // Node0 initiates a channel to node1 using the override config.
8089 let mut override_config = UserConfig::default();
8090 override_config.own_channel_config.our_to_self_delay = 200;
8092 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8094 // Assert the channel created by node0 is using the override config.
8095 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8096 assert_eq!(res.channel_flags, 0);
8097 assert_eq!(res.to_self_delay, 200);
8101 fn test_override_0msat_htlc_minimum() {
8102 let mut zero_config = UserConfig::default();
8103 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8104 let chanmon_cfgs = create_chanmon_cfgs(2);
8105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8107 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8109 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8110 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8111 assert_eq!(res.htlc_minimum_msat, 1);
8113 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8114 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8115 assert_eq!(res.htlc_minimum_msat, 1);
8119 fn test_manually_accept_inbound_channel_request() {
8120 let mut manually_accept_conf = UserConfig::default();
8121 manually_accept_conf.manually_accept_inbound_channels = true;
8122 let chanmon_cfgs = create_chanmon_cfgs(2);
8123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8127 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8128 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8130 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8132 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8133 // accepting the inbound channel request.
8134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8136 let events = nodes[1].node.get_and_clear_pending_events();
8138 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8139 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 23).unwrap();
8141 _ => panic!("Unexpected event"),
8144 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8145 assert_eq!(accept_msg_ev.len(), 1);
8147 match accept_msg_ev[0] {
8148 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8149 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8151 _ => panic!("Unexpected event"),
8154 nodes[1].node.force_close_channel(&temp_channel_id).unwrap();
8156 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8157 assert_eq!(close_msg_ev.len(), 1);
8159 let events = nodes[1].node.get_and_clear_pending_events();
8161 Event::ChannelClosed { user_channel_id, .. } => {
8162 assert_eq!(user_channel_id, 23);
8164 _ => panic!("Unexpected event"),
8169 fn test_manually_reject_inbound_channel_request() {
8170 let mut manually_accept_conf = UserConfig::default();
8171 manually_accept_conf.manually_accept_inbound_channels = true;
8172 let chanmon_cfgs = create_chanmon_cfgs(2);
8173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8177 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8178 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8180 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8182 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8183 // rejecting the inbound channel request.
8184 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8186 let events = nodes[1].node.get_and_clear_pending_events();
8188 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8189 nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8191 _ => panic!("Unexpected event"),
8194 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8195 assert_eq!(close_msg_ev.len(), 1);
8197 match close_msg_ev[0] {
8198 MessageSendEvent::HandleError { ref node_id, .. } => {
8199 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8201 _ => panic!("Unexpected event"),
8203 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8207 fn test_reject_funding_before_inbound_channel_accepted() {
8208 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8209 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8210 // the node operator before the counterparty sends a `FundingCreated` message. If a
8211 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8212 // and the channel should be closed.
8213 let mut manually_accept_conf = UserConfig::default();
8214 manually_accept_conf.manually_accept_inbound_channels = true;
8215 let chanmon_cfgs = create_chanmon_cfgs(2);
8216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8218 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8220 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8221 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8222 let temp_channel_id = res.temporary_channel_id;
8224 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8226 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8227 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8229 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8230 nodes[1].node.get_and_clear_pending_events();
8232 // Get the `AcceptChannel` message of `nodes[1]` without calling
8233 // `ChannelManager::accept_inbound_channel`, which generates a
8234 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8235 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8236 // succeed when `nodes[0]` is passed to it.
8239 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8240 let accept_chan_msg = channel.get_accept_channel_message();
8241 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8244 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8246 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8247 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8249 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8250 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8252 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8253 assert_eq!(close_msg_ev.len(), 1);
8255 let expected_err = "FundingCreated message received before the channel was accepted";
8256 match close_msg_ev[0] {
8257 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8258 assert_eq!(msg.channel_id, temp_channel_id);
8259 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8260 assert_eq!(msg.data, expected_err);
8262 _ => panic!("Unexpected event"),
8265 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8269 fn test_can_not_accept_inbound_channel_twice() {
8270 let mut manually_accept_conf = UserConfig::default();
8271 manually_accept_conf.manually_accept_inbound_channels = true;
8272 let chanmon_cfgs = create_chanmon_cfgs(2);
8273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8275 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8277 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8278 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8280 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8282 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8283 // accepting the inbound channel request.
8284 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8286 let events = nodes[1].node.get_and_clear_pending_events();
8288 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8289 nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0).unwrap();
8290 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, 0);
8292 Err(APIError::APIMisuseError { err }) => {
8293 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8295 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8296 Err(_) => panic!("Unexpected Error"),
8299 _ => panic!("Unexpected event"),
8302 // Ensure that the channel wasn't closed after attempting to accept it twice.
8303 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8304 assert_eq!(accept_msg_ev.len(), 1);
8306 match accept_msg_ev[0] {
8307 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8308 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8310 _ => panic!("Unexpected event"),
8315 fn test_can_not_accept_unknown_inbound_channel() {
8316 let chanmon_cfg = create_chanmon_cfgs(1);
8317 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8318 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8319 let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8321 let unknown_channel_id = [0; 32];
8322 let api_res = node.accept_inbound_channel(&unknown_channel_id, 0);
8324 Err(APIError::ChannelUnavailable { err }) => {
8325 assert_eq!(err, "Can't accept a channel that doesn't exist");
8327 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8328 Err(_) => panic!("Unexpected Error"),
8333 fn test_simple_mpp() {
8334 // Simple test of sending a multi-path payment.
8335 let chanmon_cfgs = create_chanmon_cfgs(4);
8336 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8337 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8338 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8340 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8341 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8342 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8343 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8345 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8346 let path = route.paths[0].clone();
8347 route.paths.push(path);
8348 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8349 route.paths[0][0].short_channel_id = chan_1_id;
8350 route.paths[0][1].short_channel_id = chan_3_id;
8351 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8352 route.paths[1][0].short_channel_id = chan_2_id;
8353 route.paths[1][1].short_channel_id = chan_4_id;
8354 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8355 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8359 fn test_preimage_storage() {
8360 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8361 let chanmon_cfgs = create_chanmon_cfgs(2);
8362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8364 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8366 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8369 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8370 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8371 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8372 check_added_monitors!(nodes[0], 1);
8373 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8374 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8375 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8376 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8378 // Note that after leaving the above scope we have no knowledge of any arguments or return
8379 // values from previous calls.
8380 expect_pending_htlcs_forwardable!(nodes[1]);
8381 let events = nodes[1].node.get_and_clear_pending_events();
8382 assert_eq!(events.len(), 1);
8384 Event::PaymentReceived { ref purpose, .. } => {
8386 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8387 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8389 _ => panic!("expected PaymentPurpose::InvoicePayment")
8392 _ => panic!("Unexpected event"),
8397 #[allow(deprecated)]
8398 fn test_secret_timeout() {
8399 // Simple test of payment secret storage time outs. After
8400 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8401 let chanmon_cfgs = create_chanmon_cfgs(2);
8402 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8403 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8404 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8406 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8408 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8410 // We should fail to register the same payment hash twice, at least until we've connected a
8411 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8412 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8413 assert_eq!(err, "Duplicate payment hash");
8414 } else { panic!(); }
8416 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8418 header: BlockHeader {
8420 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8421 merkle_root: Default::default(),
8422 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8426 connect_block(&nodes[1], &block);
8427 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8428 assert_eq!(err, "Duplicate payment hash");
8429 } else { panic!(); }
8431 // If we then connect the second block, we should be able to register the same payment hash
8432 // again (this time getting a new payment secret).
8433 block.header.prev_blockhash = block.header.block_hash();
8434 block.header.time += 1;
8435 connect_block(&nodes[1], &block);
8436 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8437 assert_ne!(payment_secret_1, our_payment_secret);
8440 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8441 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8442 check_added_monitors!(nodes[0], 1);
8443 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8444 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8445 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8446 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8448 // Note that after leaving the above scope we have no knowledge of any arguments or return
8449 // values from previous calls.
8450 expect_pending_htlcs_forwardable!(nodes[1]);
8451 let events = nodes[1].node.get_and_clear_pending_events();
8452 assert_eq!(events.len(), 1);
8454 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8455 assert!(payment_preimage.is_none());
8456 assert_eq!(payment_secret, our_payment_secret);
8457 // We don't actually have the payment preimage with which to claim this payment!
8459 _ => panic!("Unexpected event"),
8464 fn test_bad_secret_hash() {
8465 // Simple test of unregistered payment hash/invalid payment secret handling
8466 let chanmon_cfgs = create_chanmon_cfgs(2);
8467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8471 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8473 let random_payment_hash = PaymentHash([42; 32]);
8474 let random_payment_secret = PaymentSecret([43; 32]);
8475 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8476 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8478 // All the below cases should end up being handled exactly identically, so we macro the
8479 // resulting events.
8480 macro_rules! handle_unknown_invalid_payment_data {
8482 check_added_monitors!(nodes[0], 1);
8483 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8484 let payment_event = SendEvent::from_event(events.pop().unwrap());
8485 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8486 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8488 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8489 // again to process the pending backwards-failure of the HTLC
8490 expect_pending_htlcs_forwardable!(nodes[1]);
8491 expect_pending_htlcs_forwardable!(nodes[1]);
8492 check_added_monitors!(nodes[1], 1);
8494 // We should fail the payment back
8495 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8496 match events.pop().unwrap() {
8497 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8498 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8499 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8501 _ => panic!("Unexpected event"),
8506 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8507 // Error data is the HTLC value (100,000) and current block height
8508 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8510 // Send a payment with the right payment hash but the wrong payment secret
8511 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8512 handle_unknown_invalid_payment_data!();
8513 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8515 // Send a payment with a random payment hash, but the right payment secret
8516 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8517 handle_unknown_invalid_payment_data!();
8518 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8520 // Send a payment with a random payment hash and random payment secret
8521 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8522 handle_unknown_invalid_payment_data!();
8523 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8527 fn test_update_err_monitor_lockdown() {
8528 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8529 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8530 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8532 // This scenario may happen in a watchtower setup, where watchtower process a block height
8533 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8534 // commitment at same time.
8536 let chanmon_cfgs = create_chanmon_cfgs(2);
8537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8539 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8541 // Create some initial channel
8542 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8543 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8545 // Rebalance the network to generate htlc in the two directions
8546 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8548 // Route a HTLC from node 0 to node 1 (but don't settle)
8549 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8551 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8552 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8553 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8554 let persister = test_utils::TestPersister::new();
8556 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8557 let mut w = test_utils::TestVecWriter(Vec::new());
8558 monitor.write(&mut w).unwrap();
8559 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8560 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8561 assert!(new_monitor == *monitor);
8562 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);
8563 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8566 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8567 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8568 // transaction lock time requirements here.
8569 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8570 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8572 // Try to update ChannelMonitor
8573 assert!(nodes[1].node.claim_funds(preimage));
8574 check_added_monitors!(nodes[1], 1);
8575 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8576 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8577 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8578 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8579 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8580 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8581 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8582 } else { assert!(false); }
8583 } else { assert!(false); };
8584 // Our local monitor is in-sync and hasn't processed yet timeout
8585 check_added_monitors!(nodes[0], 1);
8586 let events = nodes[0].node.get_and_clear_pending_events();
8587 assert_eq!(events.len(), 1);
8591 fn test_concurrent_monitor_claim() {
8592 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8593 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8594 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8595 // state N+1 confirms. Alice claims output from state N+1.
8597 let chanmon_cfgs = create_chanmon_cfgs(2);
8598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8600 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8602 // Create some initial channel
8603 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8604 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8606 // Rebalance the network to generate htlc in the two directions
8607 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8609 // Route a HTLC from node 0 to node 1 (but don't settle)
8610 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8612 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8613 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8614 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8615 let persister = test_utils::TestPersister::new();
8616 let watchtower_alice = {
8617 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8618 let mut w = test_utils::TestVecWriter(Vec::new());
8619 monitor.write(&mut w).unwrap();
8620 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8621 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8622 assert!(new_monitor == *monitor);
8623 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);
8624 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8627 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8628 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8629 // transaction lock time requirements here.
8630 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8631 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8633 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8635 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8636 assert_eq!(txn.len(), 2);
8640 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8641 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8642 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8643 let persister = test_utils::TestPersister::new();
8644 let watchtower_bob = {
8645 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8646 let mut w = test_utils::TestVecWriter(Vec::new());
8647 monitor.write(&mut w).unwrap();
8648 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8649 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8650 assert!(new_monitor == *monitor);
8651 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);
8652 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8655 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8656 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8658 // Route another payment to generate another update with still previous HTLC pending
8659 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8661 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8663 check_added_monitors!(nodes[1], 1);
8665 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8666 assert_eq!(updates.update_add_htlcs.len(), 1);
8667 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8668 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8669 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8670 // Watchtower Alice should already have seen the block and reject the update
8671 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8672 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8673 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8674 } else { assert!(false); }
8675 } else { assert!(false); };
8676 // Our local monitor is in-sync and hasn't processed yet timeout
8677 check_added_monitors!(nodes[0], 1);
8679 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8680 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8681 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8683 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8686 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8687 assert_eq!(txn.len(), 2);
8688 bob_state_y = txn[0].clone();
8692 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8693 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8694 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);
8696 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8697 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8698 // the onchain detection of the HTLC output
8699 assert_eq!(htlc_txn.len(), 2);
8700 check_spends!(htlc_txn[0], bob_state_y);
8701 check_spends!(htlc_txn[1], bob_state_y);
8706 fn test_pre_lockin_no_chan_closed_update() {
8707 // Test that if a peer closes a channel in response to a funding_created message we don't
8708 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8711 // Doing so would imply a channel monitor update before the initial channel monitor
8712 // registration, violating our API guarantees.
8714 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8715 // then opening a second channel with the same funding output as the first (which is not
8716 // rejected because the first channel does not exist in the ChannelManager) and closing it
8717 // before receiving funding_signed.
8718 let chanmon_cfgs = create_chanmon_cfgs(2);
8719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8721 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8723 // Create an initial channel
8724 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8725 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8726 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8727 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8728 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8730 // Move the first channel through the funding flow...
8731 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8733 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8734 check_added_monitors!(nodes[0], 0);
8736 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8737 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8738 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8739 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8740 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8744 fn test_htlc_no_detection() {
8745 // This test is a mutation to underscore the detection logic bug we had
8746 // before #653. HTLC value routed is above the remaining balance, thus
8747 // inverting HTLC and `to_remote` output. HTLC will come second and
8748 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8749 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8750 // outputs order detection for correct spending children filtring.
8752 let chanmon_cfgs = create_chanmon_cfgs(2);
8753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8755 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8757 // Create some initial channels
8758 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8760 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8761 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8762 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8763 assert_eq!(local_txn[0].input.len(), 1);
8764 assert_eq!(local_txn[0].output.len(), 3);
8765 check_spends!(local_txn[0], chan_1.3);
8767 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8768 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8769 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8770 // We deliberately connect the local tx twice as this should provoke a failure calling
8771 // this test before #653 fix.
8772 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);
8773 check_closed_broadcast!(nodes[0], true);
8774 check_added_monitors!(nodes[0], 1);
8775 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8776 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8778 let htlc_timeout = {
8779 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8780 assert_eq!(node_txn[1].input.len(), 1);
8781 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8782 check_spends!(node_txn[1], local_txn[0]);
8786 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8787 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8788 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8789 expect_payment_failed!(nodes[0], our_payment_hash, true);
8792 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8793 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8794 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8795 // Carol, Alice would be the upstream node, and Carol the downstream.)
8797 // Steps of the test:
8798 // 1) Alice sends a HTLC to Carol through Bob.
8799 // 2) Carol doesn't settle the HTLC.
8800 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8801 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8802 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8803 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8804 // 5) Carol release the preimage to Bob off-chain.
8805 // 6) Bob claims the offered output on the broadcasted commitment.
8806 let chanmon_cfgs = create_chanmon_cfgs(3);
8807 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8808 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8809 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8811 // Create some initial channels
8812 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8813 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8815 // Steps (1) and (2):
8816 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8817 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8819 // Check that Alice's commitment transaction now contains an output for this HTLC.
8820 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8821 check_spends!(alice_txn[0], chan_ab.3);
8822 assert_eq!(alice_txn[0].output.len(), 2);
8823 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8824 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8825 assert_eq!(alice_txn.len(), 2);
8827 // Steps (3) and (4):
8828 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8829 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8830 let mut force_closing_node = 0; // Alice force-closes
8831 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8832 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8833 check_closed_broadcast!(nodes[force_closing_node], true);
8834 check_added_monitors!(nodes[force_closing_node], 1);
8835 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8836 if go_onchain_before_fulfill {
8837 let txn_to_broadcast = match broadcast_alice {
8838 true => alice_txn.clone(),
8839 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8841 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8842 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8843 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8844 if broadcast_alice {
8845 check_closed_broadcast!(nodes[1], true);
8846 check_added_monitors!(nodes[1], 1);
8847 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8849 assert_eq!(bob_txn.len(), 1);
8850 check_spends!(bob_txn[0], chan_ab.3);
8854 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8855 // process of removing the HTLC from their commitment transactions.
8856 assert!(nodes[2].node.claim_funds(payment_preimage));
8857 check_added_monitors!(nodes[2], 1);
8858 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8859 assert!(carol_updates.update_add_htlcs.is_empty());
8860 assert!(carol_updates.update_fail_htlcs.is_empty());
8861 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8862 assert!(carol_updates.update_fee.is_none());
8863 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8865 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8866 expect_payment_forwarded!(nodes[1], nodes[0], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8867 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8868 if !go_onchain_before_fulfill && broadcast_alice {
8869 let events = nodes[1].node.get_and_clear_pending_msg_events();
8870 assert_eq!(events.len(), 1);
8872 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8873 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8875 _ => panic!("Unexpected event"),
8878 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8879 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8880 // Carol<->Bob's updated commitment transaction info.
8881 check_added_monitors!(nodes[1], 2);
8883 let events = nodes[1].node.get_and_clear_pending_msg_events();
8884 assert_eq!(events.len(), 2);
8885 let bob_revocation = match events[0] {
8886 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8887 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8890 _ => panic!("Unexpected event"),
8892 let bob_updates = match events[1] {
8893 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8894 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8897 _ => panic!("Unexpected event"),
8900 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8901 check_added_monitors!(nodes[2], 1);
8902 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8903 check_added_monitors!(nodes[2], 1);
8905 let events = nodes[2].node.get_and_clear_pending_msg_events();
8906 assert_eq!(events.len(), 1);
8907 let carol_revocation = match events[0] {
8908 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8909 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8912 _ => panic!("Unexpected event"),
8914 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8915 check_added_monitors!(nodes[1], 1);
8917 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8918 // here's where we put said channel's commitment tx on-chain.
8919 let mut txn_to_broadcast = alice_txn.clone();
8920 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8921 if !go_onchain_before_fulfill {
8922 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8923 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8924 // If Bob was the one to force-close, he will have already passed these checks earlier.
8925 if broadcast_alice {
8926 check_closed_broadcast!(nodes[1], true);
8927 check_added_monitors!(nodes[1], 1);
8928 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8930 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8931 if broadcast_alice {
8932 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8933 // new block being connected. The ChannelManager being notified triggers a monitor update,
8934 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8935 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8937 assert_eq!(bob_txn.len(), 3);
8938 check_spends!(bob_txn[1], chan_ab.3);
8940 assert_eq!(bob_txn.len(), 2);
8941 check_spends!(bob_txn[0], chan_ab.3);
8946 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8947 // broadcasted commitment transaction.
8949 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8950 if go_onchain_before_fulfill {
8951 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8952 assert_eq!(bob_txn.len(), 2);
8954 let script_weight = match broadcast_alice {
8955 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8956 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8958 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8959 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8960 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8961 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8962 if broadcast_alice && !go_onchain_before_fulfill {
8963 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8964 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8966 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8967 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8973 fn test_onchain_htlc_settlement_after_close() {
8974 do_test_onchain_htlc_settlement_after_close(true, true);
8975 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8976 do_test_onchain_htlc_settlement_after_close(true, false);
8977 do_test_onchain_htlc_settlement_after_close(false, false);
8981 fn test_duplicate_chan_id() {
8982 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8983 // already open we reject it and keep the old channel.
8985 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8986 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8987 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8988 // updating logic for the existing channel.
8989 let chanmon_cfgs = create_chanmon_cfgs(2);
8990 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8991 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8992 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8994 // Create an initial channel
8995 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8996 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8997 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8998 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()));
9000 // Try to create a second channel with the same temporary_channel_id as the first and check
9001 // that it is rejected.
9002 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9004 let events = nodes[1].node.get_and_clear_pending_msg_events();
9005 assert_eq!(events.len(), 1);
9007 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9008 // Technically, at this point, nodes[1] would be justified in thinking both the
9009 // first (valid) and second (invalid) channels are closed, given they both have
9010 // the same non-temporary channel_id. However, currently we do not, so we just
9011 // move forward with it.
9012 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9013 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9015 _ => panic!("Unexpected event"),
9019 // Move the first channel through the funding flow...
9020 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9022 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9023 check_added_monitors!(nodes[0], 0);
9025 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9026 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9028 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9029 assert_eq!(added_monitors.len(), 1);
9030 assert_eq!(added_monitors[0].0, funding_output);
9031 added_monitors.clear();
9033 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9035 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9036 let channel_id = funding_outpoint.to_channel_id();
9038 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9041 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9042 // Technically this is allowed by the spec, but we don't support it and there's little reason
9043 // to. Still, it shouldn't cause any other issues.
9044 open_chan_msg.temporary_channel_id = channel_id;
9045 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9047 let events = nodes[1].node.get_and_clear_pending_msg_events();
9048 assert_eq!(events.len(), 1);
9050 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9051 // Technically, at this point, nodes[1] would be justified in thinking both
9052 // channels are closed, but currently we do not, so we just move forward with it.
9053 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9054 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9056 _ => panic!("Unexpected event"),
9060 // Now try to create a second channel which has a duplicate funding output.
9061 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9062 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9063 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9064 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()));
9065 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9067 let funding_created = {
9068 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9069 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9070 let logger = test_utils::TestLogger::new();
9071 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9073 check_added_monitors!(nodes[0], 0);
9074 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9075 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9076 // still needs to be cleared here.
9077 check_added_monitors!(nodes[1], 1);
9079 // ...still, nodes[1] will reject the duplicate channel.
9081 let events = nodes[1].node.get_and_clear_pending_msg_events();
9082 assert_eq!(events.len(), 1);
9084 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9085 // Technically, at this point, nodes[1] would be justified in thinking both
9086 // channels are closed, but currently we do not, so we just move forward with it.
9087 assert_eq!(msg.channel_id, channel_id);
9088 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9090 _ => panic!("Unexpected event"),
9094 // finally, finish creating the original channel and send a payment over it to make sure
9095 // everything is functional.
9096 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9098 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9099 assert_eq!(added_monitors.len(), 1);
9100 assert_eq!(added_monitors[0].0, funding_output);
9101 added_monitors.clear();
9104 let events_4 = nodes[0].node.get_and_clear_pending_events();
9105 assert_eq!(events_4.len(), 0);
9106 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9107 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9109 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9110 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9111 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9112 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9116 fn test_error_chans_closed() {
9117 // Test that we properly handle error messages, closing appropriate channels.
9119 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9120 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9121 // we can test various edge cases around it to ensure we don't regress.
9122 let chanmon_cfgs = create_chanmon_cfgs(3);
9123 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9124 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9125 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9127 // Create some initial channels
9128 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9129 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9130 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9132 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9133 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9134 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9136 // Closing a channel from a different peer has no effect
9137 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9138 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9140 // Closing one channel doesn't impact others
9141 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9142 check_added_monitors!(nodes[0], 1);
9143 check_closed_broadcast!(nodes[0], false);
9144 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9145 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9146 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9147 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);
9148 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);
9150 // A null channel ID should close all channels
9151 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9152 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9153 check_added_monitors!(nodes[0], 2);
9154 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9155 let events = nodes[0].node.get_and_clear_pending_msg_events();
9156 assert_eq!(events.len(), 2);
9158 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9159 assert_eq!(msg.contents.flags & 2, 2);
9161 _ => panic!("Unexpected event"),
9164 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9165 assert_eq!(msg.contents.flags & 2, 2);
9167 _ => panic!("Unexpected event"),
9169 // Note that at this point users of a standard PeerHandler will end up calling
9170 // peer_disconnected with no_connection_possible set to false, duplicating the
9171 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9172 // users with their own peer handling logic. We duplicate the call here, however.
9173 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9174 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9176 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9177 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9178 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9182 fn test_invalid_funding_tx() {
9183 // Test that we properly handle invalid funding transactions sent to us from a peer.
9185 // Previously, all other major lightning implementations had failed to properly sanitize
9186 // funding transactions from their counterparties, leading to a multi-implementation critical
9187 // security vulnerability (though we always sanitized properly, we've previously had
9188 // un-released crashes in the sanitization process).
9189 let chanmon_cfgs = create_chanmon_cfgs(2);
9190 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9191 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9192 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9194 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9195 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()));
9196 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()));
9198 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9199 for output in tx.output.iter_mut() {
9200 // Make the confirmed funding transaction have a bogus script_pubkey
9201 output.script_pubkey = bitcoin::Script::new();
9204 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9205 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()));
9206 check_added_monitors!(nodes[1], 1);
9208 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()));
9209 check_added_monitors!(nodes[0], 1);
9211 let events_1 = nodes[0].node.get_and_clear_pending_events();
9212 assert_eq!(events_1.len(), 0);
9214 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9215 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9216 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9218 let expected_err = "funding tx had wrong script/value or output index";
9219 confirm_transaction_at(&nodes[1], &tx, 1);
9220 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9221 check_added_monitors!(nodes[1], 1);
9222 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9223 assert_eq!(events_2.len(), 1);
9224 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9225 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9226 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9227 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9228 } else { panic!(); }
9229 } else { panic!(); }
9230 assert_eq!(nodes[1].node.list_channels().len(), 0);
9233 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9234 // In the first version of the chain::Confirm interface, after a refactor was made to not
9235 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9236 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9237 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9238 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9239 // spending transaction until height N+1 (or greater). This was due to the way
9240 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9241 // spending transaction at the height the input transaction was confirmed at, not whether we
9242 // should broadcast a spending transaction at the current height.
9243 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9244 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9245 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9246 // until we learned about an additional block.
9248 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9249 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9250 let chanmon_cfgs = create_chanmon_cfgs(3);
9251 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9252 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9253 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9254 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9256 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9257 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9258 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9259 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9260 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9262 nodes[1].node.force_close_channel(&channel_id).unwrap();
9263 check_closed_broadcast!(nodes[1], true);
9264 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9265 check_added_monitors!(nodes[1], 1);
9266 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9267 assert_eq!(node_txn.len(), 1);
9269 let conf_height = nodes[1].best_block_info().1;
9270 if !test_height_before_timelock {
9271 connect_blocks(&nodes[1], 24 * 6);
9273 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9274 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9275 if test_height_before_timelock {
9276 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9277 // generate any events or broadcast any transactions
9278 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9279 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9281 // We should broadcast an HTLC transaction spending our funding transaction first
9282 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9283 assert_eq!(spending_txn.len(), 2);
9284 assert_eq!(spending_txn[0], node_txn[0]);
9285 check_spends!(spending_txn[1], node_txn[0]);
9286 // We should also generate a SpendableOutputs event with the to_self output (as its
9288 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9289 assert_eq!(descriptor_spend_txn.len(), 1);
9291 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9292 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9293 // additional block built on top of the current chain.
9294 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9295 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9296 expect_pending_htlcs_forwardable!(nodes[1]);
9297 check_added_monitors!(nodes[1], 1);
9299 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9300 assert!(updates.update_add_htlcs.is_empty());
9301 assert!(updates.update_fulfill_htlcs.is_empty());
9302 assert_eq!(updates.update_fail_htlcs.len(), 1);
9303 assert!(updates.update_fail_malformed_htlcs.is_empty());
9304 assert!(updates.update_fee.is_none());
9305 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9306 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9307 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9312 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9313 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9314 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9318 fn test_forwardable_regen() {
9319 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9320 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9322 // We test it for both payment receipt and payment forwarding.
9324 let chanmon_cfgs = create_chanmon_cfgs(3);
9325 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9326 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9327 let persister: test_utils::TestPersister;
9328 let new_chain_monitor: test_utils::TestChainMonitor;
9329 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9330 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9331 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9332 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9334 // First send a payment to nodes[1]
9335 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9336 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9337 check_added_monitors!(nodes[0], 1);
9339 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9340 assert_eq!(events.len(), 1);
9341 let payment_event = SendEvent::from_event(events.pop().unwrap());
9342 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9343 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9345 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9347 // Next send a payment which is forwarded by nodes[1]
9348 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9349 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9350 check_added_monitors!(nodes[0], 1);
9352 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9353 assert_eq!(events.len(), 1);
9354 let payment_event = SendEvent::from_event(events.pop().unwrap());
9355 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9356 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9358 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9360 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9362 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9363 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9364 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9366 let nodes_1_serialized = nodes[1].node.encode();
9367 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9368 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9369 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9370 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9372 persister = test_utils::TestPersister::new();
9373 let keys_manager = &chanmon_cfgs[1].keys_manager;
9374 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);
9375 nodes[1].chain_monitor = &new_chain_monitor;
9377 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9378 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9379 &mut chan_0_monitor_read, keys_manager).unwrap();
9380 assert!(chan_0_monitor_read.is_empty());
9381 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9382 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9383 &mut chan_1_monitor_read, keys_manager).unwrap();
9384 assert!(chan_1_monitor_read.is_empty());
9386 let mut nodes_1_read = &nodes_1_serialized[..];
9387 let (_, nodes_1_deserialized_tmp) = {
9388 let mut channel_monitors = HashMap::new();
9389 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9390 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9391 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9392 default_config: UserConfig::default(),
9394 fee_estimator: node_cfgs[1].fee_estimator,
9395 chain_monitor: nodes[1].chain_monitor,
9396 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9397 logger: nodes[1].logger,
9401 nodes_1_deserialized = nodes_1_deserialized_tmp;
9402 assert!(nodes_1_read.is_empty());
9404 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9405 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9406 nodes[1].node = &nodes_1_deserialized;
9407 check_added_monitors!(nodes[1], 2);
9409 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9410 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9411 // the commitment state.
9412 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9414 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9416 expect_pending_htlcs_forwardable!(nodes[1]);
9417 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9418 check_added_monitors!(nodes[1], 1);
9420 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9421 assert_eq!(events.len(), 1);
9422 let payment_event = SendEvent::from_event(events.pop().unwrap());
9423 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9424 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9425 expect_pending_htlcs_forwardable!(nodes[2]);
9426 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9428 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9429 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9433 fn test_dup_htlc_second_fail_panic() {
9434 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9435 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9436 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9437 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9438 let chanmon_cfgs = create_chanmon_cfgs(2);
9439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9441 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9443 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9445 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9446 .with_features(InvoiceFeatures::known());
9447 let scorer = test_utils::TestScorer::with_penalty(0);
9448 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9449 let route = get_route(
9450 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
9451 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
9452 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9454 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9457 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9458 check_added_monitors!(nodes[0], 1);
9459 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9460 assert_eq!(events.len(), 1);
9461 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9463 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9465 expect_pending_htlcs_forwardable!(nodes[1]);
9466 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9469 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9470 check_added_monitors!(nodes[0], 1);
9471 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9472 assert_eq!(events.len(), 1);
9473 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9474 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9475 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9476 // At this point, nodes[1] would notice it has too much value for the payment. It will
9477 // assume the second is a privacy attack (no longer particularly relevant
9478 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9479 // the first HTLC delivered above.
9482 // Now we go fail back the first HTLC from the user end.
9483 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9484 nodes[1].node.process_pending_htlc_forwards();
9485 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9487 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9488 nodes[1].node.process_pending_htlc_forwards();
9490 check_added_monitors!(nodes[1], 1);
9491 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9492 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9494 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9495 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9496 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9498 let failure_events = nodes[0].node.get_and_clear_pending_events();
9499 assert_eq!(failure_events.len(), 2);
9500 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9501 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9505 fn test_keysend_payments_to_public_node() {
9506 let chanmon_cfgs = create_chanmon_cfgs(2);
9507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9511 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9512 let network_graph = nodes[0].network_graph;
9513 let payer_pubkey = nodes[0].node.get_our_node_id();
9514 let payee_pubkey = nodes[1].node.get_our_node_id();
9515 let route_params = RouteParameters {
9516 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9517 final_value_msat: 10000,
9518 final_cltv_expiry_delta: 40,
9520 let scorer = test_utils::TestScorer::with_penalty(0);
9521 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9522 let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9524 let test_preimage = PaymentPreimage([42; 32]);
9525 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9526 check_added_monitors!(nodes[0], 1);
9527 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9528 assert_eq!(events.len(), 1);
9529 let event = events.pop().unwrap();
9530 let path = vec![&nodes[1]];
9531 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9532 claim_payment(&nodes[0], &path, test_preimage);
9536 fn test_keysend_payments_to_private_node() {
9537 let chanmon_cfgs = create_chanmon_cfgs(2);
9538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9540 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9542 let payer_pubkey = nodes[0].node.get_our_node_id();
9543 let payee_pubkey = nodes[1].node.get_our_node_id();
9544 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9545 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known(), remote_network_address: None });
9547 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9548 let route_params = RouteParameters {
9549 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9550 final_value_msat: 10000,
9551 final_cltv_expiry_delta: 40,
9553 let network_graph = nodes[0].network_graph;
9554 let first_hops = nodes[0].node.list_usable_channels();
9555 let scorer = test_utils::TestScorer::with_penalty(0);
9556 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9557 let route = find_route(
9558 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9559 nodes[0].logger, &scorer, &random_seed_bytes
9562 let test_preimage = PaymentPreimage([42; 32]);
9563 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9564 check_added_monitors!(nodes[0], 1);
9565 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9566 assert_eq!(events.len(), 1);
9567 let event = events.pop().unwrap();
9568 let path = vec![&nodes[1]];
9569 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9570 claim_payment(&nodes[0], &path, test_preimage);
9573 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9574 #[derive(Clone, Copy, PartialEq)]
9575 enum ExposureEvent {
9576 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9578 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9580 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9581 AtUpdateFeeOutbound,
9584 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9585 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9588 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9589 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9590 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9591 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9592 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9593 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9594 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9595 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9597 let chanmon_cfgs = create_chanmon_cfgs(2);
9598 let mut config = test_default_channel_config();
9599 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9600 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9602 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9604 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9605 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9606 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9607 open_channel.max_accepted_htlcs = 60;
9609 open_channel.dust_limit_satoshis = 546;
9611 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9612 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9613 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9615 let opt_anchors = false;
9617 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9620 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9621 chan.holder_dust_limit_satoshis = 546;
9625 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9626 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()));
9627 check_added_monitors!(nodes[1], 1);
9629 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()));
9630 check_added_monitors!(nodes[0], 1);
9632 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9633 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9634 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9636 let dust_buffer_feerate = {
9637 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9638 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9639 chan.get_dust_buffer_feerate(None) as u64
9641 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9642 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9644 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(opt_anchors) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9645 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9647 let dust_htlc_on_counterparty_tx: u64 = 25;
9648 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9651 if dust_outbound_balance {
9652 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9653 // Outbound dust balance: 4372 sats
9654 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9655 for i in 0..dust_outbound_htlc_on_holder_tx {
9656 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9657 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9660 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9661 // Inbound dust balance: 4372 sats
9662 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9663 for _ in 0..dust_inbound_htlc_on_holder_tx {
9664 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9668 if dust_outbound_balance {
9669 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9670 // Outbound dust balance: 5000 sats
9671 for i in 0..dust_htlc_on_counterparty_tx {
9672 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9673 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9676 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9677 // Inbound dust balance: 5000 sats
9678 for _ in 0..dust_htlc_on_counterparty_tx {
9679 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9684 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9685 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9686 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 });
9687 let mut config = UserConfig::default();
9688 // With default dust exposure: 5000 sats
9690 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9691 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9692 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)));
9694 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)));
9696 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9697 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 });
9698 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9699 check_added_monitors!(nodes[1], 1);
9700 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9701 assert_eq!(events.len(), 1);
9702 let payment_event = SendEvent::from_event(events.remove(0));
9703 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9704 // With default dust exposure: 5000 sats
9706 // Outbound dust balance: 6399 sats
9707 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9708 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9709 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);
9711 // Outbound dust balance: 5200 sats
9712 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);
9714 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9715 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9716 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9718 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9719 *feerate_lock = *feerate_lock * 10;
9721 nodes[0].node.timer_tick_occurred();
9722 check_added_monitors!(nodes[0], 1);
9723 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);
9726 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9727 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9728 added_monitors.clear();
9732 fn test_max_dust_htlc_exposure() {
9733 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9734 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9735 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9736 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9737 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9738 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9739 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9740 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9741 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9742 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9743 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9744 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);