1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{BaseSign, KeysInterface};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, PAYMENT_EXPIRY_BLOCKS };
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
26 use routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
37 use bitcoin::hash_types::BlockHash;
38 use bitcoin::blockdata::block::{Block, BlockHeader};
39 use bitcoin::blockdata::script::Builder;
40 use bitcoin::blockdata::opcodes;
41 use bitcoin::blockdata::constants::genesis_block;
42 use bitcoin::network::constants::Network;
44 use bitcoin::secp256k1::Secp256k1;
45 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51 use alloc::collections::BTreeSet;
52 use core::default::Default;
53 use sync::{Arc, Mutex};
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
59 fn test_insane_channel_opens() {
60 // Stand up a network of 2 nodes
61 let chanmon_cfgs = create_chanmon_cfgs(2);
62 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
63 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
64 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
66 // Instantiate channel parameters where we push the maximum msats given our
68 let channel_value_sat = 31337; // same as funding satoshis
69 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
70 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
72 // Have node0 initiate a channel to node1 with aforementioned parameters
73 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
75 // Extract the channel open message from node0 to node1
76 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
78 // Test helper that asserts we get the correct error string given a mutator
79 // that supposedly makes the channel open message insane
80 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
81 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
82 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
83 assert_eq!(msg_events.len(), 1);
84 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
85 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
87 &ErrorAction::SendErrorMessage { .. } => {
88 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
90 _ => panic!("unexpected event!"),
92 } else { assert!(false); }
95 use ln::channel::MAX_FUNDING_SATOSHIS;
96 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
98 // Test all mutations that would make the channel open message insane
99 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
101 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
103 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
105 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
107 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
109 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
111 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
113 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
116 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
117 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
118 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
119 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
120 // in normal testing, we test it explicitly here.
121 let chanmon_cfgs = create_chanmon_cfgs(2);
122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126 // Have node0 initiate a channel to node1 with aforementioned parameters
127 let mut push_amt = 100_000_000;
128 let feerate_per_kw = 253;
129 let opt_anchors = false;
130 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
131 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
133 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
134 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
135 if !send_from_initiator {
136 open_channel_message.channel_reserve_satoshis = 0;
137 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
139 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_message);
141 // Extract the channel accept message from node1 to node0
142 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
143 if send_from_initiator {
144 accept_channel_message.channel_reserve_satoshis = 0;
145 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
147 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel_message);
150 let mut chan = get_channel_ref!(if send_from_initiator { &nodes[1] } else { &nodes[0] }, lock, temp_channel_id);
151 chan.holder_selected_channel_reserve_satoshis = 0;
152 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
155 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
156 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
157 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
159 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
160 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
161 if send_from_initiator {
162 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
163 // Note that for outbound channels we have to consider the commitment tx fee and the
164 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
165 // well as an additional HTLC.
166 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
168 send_payment(&nodes[1], &[&nodes[0]], push_amt);
173 fn test_counterparty_no_reserve() {
174 do_test_counterparty_no_reserve(true);
175 do_test_counterparty_no_reserve(false);
179 fn test_async_inbound_update_fee() {
180 let chanmon_cfgs = create_chanmon_cfgs(2);
181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
184 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
187 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
191 // send (1) commitment_signed -.
192 // <- update_add_htlc/commitment_signed
193 // send (2) RAA (awaiting remote revoke) -.
194 // (1) commitment_signed is delivered ->
195 // .- send (3) RAA (awaiting remote revoke)
196 // (2) RAA is delivered ->
197 // .- send (4) commitment_signed
198 // <- (3) RAA is delivered
199 // send (5) commitment_signed -.
200 // <- (4) commitment_signed is delivered
202 // (5) commitment_signed is delivered ->
204 // (6) RAA is delivered ->
206 // First nodes[0] generates an update_fee
208 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
211 nodes[0].node.timer_tick_occurred();
212 check_added_monitors!(nodes[0], 1);
214 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
215 assert_eq!(events_0.len(), 1);
216 let (update_msg, commitment_signed) = match events_0[0] { // (1)
217 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
218 (update_fee.as_ref(), commitment_signed)
220 _ => panic!("Unexpected event"),
223 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
225 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
226 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
227 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
228 check_added_monitors!(nodes[1], 1);
230 let payment_event = {
231 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
232 assert_eq!(events_1.len(), 1);
233 SendEvent::from_event(events_1.remove(0))
235 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
236 assert_eq!(payment_event.msgs.len(), 1);
238 // ...now when the messages get delivered everyone should be happy
239 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
240 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
241 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
242 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
243 check_added_monitors!(nodes[0], 1);
245 // deliver(1), generate (3):
246 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
247 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
248 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
249 check_added_monitors!(nodes[1], 1);
251 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
252 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
253 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
254 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
255 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
256 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
257 assert!(bs_update.update_fee.is_none()); // (4)
258 check_added_monitors!(nodes[1], 1);
260 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
261 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
262 assert!(as_update.update_add_htlcs.is_empty()); // (5)
263 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
264 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
265 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
266 assert!(as_update.update_fee.is_none()); // (5)
267 check_added_monitors!(nodes[0], 1);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
270 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // only (6) so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
275 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
276 check_added_monitors!(nodes[1], 1);
278 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
279 check_added_monitors!(nodes[0], 1);
281 let events_2 = nodes[0].node.get_and_clear_pending_events();
282 assert_eq!(events_2.len(), 1);
284 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
285 _ => panic!("Unexpected event"),
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
289 check_added_monitors!(nodes[1], 1);
293 fn test_update_fee_unordered_raa() {
294 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
295 // crash in an earlier version of the update_fee patch)
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
303 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
305 // First nodes[0] generates an update_fee
307 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
310 nodes[0].node.timer_tick_occurred();
311 check_added_monitors!(nodes[0], 1);
313 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
314 assert_eq!(events_0.len(), 1);
315 let update_msg = match events_0[0] { // (1)
316 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
319 _ => panic!("Unexpected event"),
322 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
324 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
325 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
326 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
327 check_added_monitors!(nodes[1], 1);
329 let payment_event = {
330 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
331 assert_eq!(events_1.len(), 1);
332 SendEvent::from_event(events_1.remove(0))
334 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
335 assert_eq!(payment_event.msgs.len(), 1);
337 // ...now when the messages get delivered everyone should be happy
338 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
339 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
340 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
341 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
342 check_added_monitors!(nodes[0], 1);
344 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
345 check_added_monitors!(nodes[1], 1);
347 // We can't continue, sadly, because our (1) now has a bogus signature
351 fn test_multi_flight_update_fee() {
352 let chanmon_cfgs = create_chanmon_cfgs(2);
353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
356 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
359 // update_fee/commitment_signed ->
360 // .- send (1) RAA and (2) commitment_signed
361 // update_fee (never committed) ->
363 // We have to manually generate the above update_fee, it is allowed by the protocol but we
364 // don't track which updates correspond to which revoke_and_ack responses so we're in
365 // AwaitingRAA mode and will not generate the update_fee yet.
366 // <- (1) RAA delivered
367 // (3) is generated and send (4) CS -.
368 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
369 // know the per_commitment_point to use for it.
370 // <- (2) commitment_signed delivered
372 // B should send no response here
373 // (4) commitment_signed delivered ->
374 // <- RAA/commitment_signed delivered
377 // First nodes[0] generates an update_fee
380 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
381 initial_feerate = *feerate_lock;
382 *feerate_lock = initial_feerate + 20;
384 nodes[0].node.timer_tick_occurred();
385 check_added_monitors!(nodes[0], 1);
387 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
388 assert_eq!(events_0.len(), 1);
389 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
390 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
391 (update_fee.as_ref().unwrap(), commitment_signed)
393 _ => panic!("Unexpected event"),
396 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
397 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
398 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
399 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
400 check_added_monitors!(nodes[1], 1);
402 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
405 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
406 *feerate_lock = initial_feerate + 40;
408 nodes[0].node.timer_tick_occurred();
409 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
410 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
412 // Create the (3) update_fee message that nodes[0] will generate before it does...
413 let mut update_msg_2 = msgs::UpdateFee {
414 channel_id: update_msg_1.channel_id.clone(),
415 feerate_per_kw: (initial_feerate + 30) as u32,
418 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
420 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
422 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
424 // Deliver (1), generating (3) and (4)
425 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
426 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
427 check_added_monitors!(nodes[0], 1);
428 assert!(as_second_update.update_add_htlcs.is_empty());
429 assert!(as_second_update.update_fulfill_htlcs.is_empty());
430 assert!(as_second_update.update_fail_htlcs.is_empty());
431 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
432 // Check that the update_fee newly generated matches what we delivered:
433 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
434 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
436 // Deliver (2) commitment_signed
437 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
438 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
439 check_added_monitors!(nodes[0], 1);
440 // No commitment_signed so get_event_msg's assert(len == 1) passes
442 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
443 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
444 check_added_monitors!(nodes[1], 1);
447 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
448 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
449 check_added_monitors!(nodes[1], 1);
451 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
452 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
453 check_added_monitors!(nodes[0], 1);
455 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
456 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
457 // No commitment_signed so get_event_msg's assert(len == 1) passes
458 check_added_monitors!(nodes[0], 1);
460 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
461 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
462 check_added_monitors!(nodes[1], 1);
465 fn do_test_sanity_on_in_flight_opens(steps: u8) {
466 // Previously, we had issues deserializing channels when we hadn't connected the first block
467 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
468 // serialization round-trips and simply do steps towards opening a channel and then drop the
471 let chanmon_cfgs = create_chanmon_cfgs(2);
472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
476 if steps & 0b1000_0000 != 0{
478 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
481 connect_block(&nodes[0], &block);
482 connect_block(&nodes[1], &block);
485 if steps & 0x0f == 0 { return; }
486 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
487 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
489 if steps & 0x0f == 1 { return; }
490 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
491 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
493 if steps & 0x0f == 2 { return; }
494 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
496 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
498 if steps & 0x0f == 3 { return; }
499 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
500 check_added_monitors!(nodes[0], 0);
501 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
503 if steps & 0x0f == 4 { return; }
504 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
506 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
507 assert_eq!(added_monitors.len(), 1);
508 assert_eq!(added_monitors[0].0, funding_output);
509 added_monitors.clear();
511 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
513 if steps & 0x0f == 5 { return; }
514 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
516 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
517 assert_eq!(added_monitors.len(), 1);
518 assert_eq!(added_monitors[0].0, funding_output);
519 added_monitors.clear();
522 let events_4 = nodes[0].node.get_and_clear_pending_events();
523 assert_eq!(events_4.len(), 0);
525 if steps & 0x0f == 6 { return; }
526 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
528 if steps & 0x0f == 7 { return; }
529 confirm_transaction_at(&nodes[0], &tx, 2);
530 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
531 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
535 fn test_sanity_on_in_flight_opens() {
536 do_test_sanity_on_in_flight_opens(0);
537 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
538 do_test_sanity_on_in_flight_opens(1);
539 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
540 do_test_sanity_on_in_flight_opens(2);
541 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
542 do_test_sanity_on_in_flight_opens(3);
543 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
544 do_test_sanity_on_in_flight_opens(4);
545 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
546 do_test_sanity_on_in_flight_opens(5);
547 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
548 do_test_sanity_on_in_flight_opens(6);
549 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
550 do_test_sanity_on_in_flight_opens(7);
551 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
552 do_test_sanity_on_in_flight_opens(8);
553 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
557 fn test_update_fee_vanilla() {
558 let chanmon_cfgs = create_chanmon_cfgs(2);
559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
562 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
565 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
568 nodes[0].node.timer_tick_occurred();
569 check_added_monitors!(nodes[0], 1);
571 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
572 assert_eq!(events_0.len(), 1);
573 let (update_msg, commitment_signed) = match events_0[0] {
574 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
575 (update_fee.as_ref(), commitment_signed)
577 _ => panic!("Unexpected event"),
579 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
581 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
582 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
583 check_added_monitors!(nodes[1], 1);
585 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
586 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
587 check_added_monitors!(nodes[0], 1);
589 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
590 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
591 // No commitment_signed so get_event_msg's assert(len == 1) passes
592 check_added_monitors!(nodes[0], 1);
594 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
595 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
596 check_added_monitors!(nodes[1], 1);
600 fn test_update_fee_that_funder_cannot_afford() {
601 let chanmon_cfgs = create_chanmon_cfgs(2);
602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
604 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
605 let channel_value = 5000;
607 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
608 let channel_id = chan.2;
609 let secp_ctx = Secp256k1::new();
610 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
612 let opt_anchors = false;
614 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
615 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
616 // calculate two different feerates here - the expected local limit as well as the expected
618 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
619 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
621 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
622 *feerate_lock = feerate;
624 nodes[0].node.timer_tick_occurred();
625 check_added_monitors!(nodes[0], 1);
626 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
628 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
630 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
632 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
634 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
636 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
637 assert_eq!(commitment_tx.output.len(), 2);
638 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
639 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
640 actual_fee = channel_value - actual_fee;
641 assert_eq!(total_fee, actual_fee);
645 // Increment the feerate by a small constant, accounting for rounding errors
646 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
649 nodes[0].node.timer_tick_occurred();
650 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
651 check_added_monitors!(nodes[0], 0);
653 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
655 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
656 // needed to sign the new commitment tx and (2) sign the new commitment tx.
657 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
658 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
659 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
660 let chan_signer = local_chan.get_signer();
661 let pubkeys = chan_signer.pubkeys();
662 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
663 pubkeys.funding_pubkey)
665 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
666 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
667 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
668 let chan_signer = remote_chan.get_signer();
669 let pubkeys = chan_signer.pubkeys();
670 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
671 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
672 pubkeys.funding_pubkey)
675 // Assemble the set of keys we can use for signatures for our commitment_signed message.
676 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
677 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
680 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
681 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
682 let local_chan_signer = local_chan.get_signer();
683 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
684 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
685 INITIAL_COMMITMENT_NUMBER - 1,
687 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
688 opt_anchors, local_funding, remote_funding,
689 commit_tx_keys.clone(),
690 non_buffer_feerate + 4,
692 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
694 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
697 let commit_signed_msg = msgs::CommitmentSigned {
700 htlc_signatures: res.1
703 let update_fee = msgs::UpdateFee {
705 feerate_per_kw: non_buffer_feerate + 4,
708 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
710 //While producing the commitment_signed response after handling a received update_fee request the
711 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
712 //Should produce and error.
713 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
714 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
715 check_added_monitors!(nodes[1], 1);
716 check_closed_broadcast!(nodes[1], true);
717 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
721 fn test_update_fee_with_fundee_update_add_htlc() {
722 let chanmon_cfgs = create_chanmon_cfgs(2);
723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
725 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
726 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
729 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
732 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
735 nodes[0].node.timer_tick_occurred();
736 check_added_monitors!(nodes[0], 1);
738 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
739 assert_eq!(events_0.len(), 1);
740 let (update_msg, commitment_signed) = match events_0[0] {
741 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
742 (update_fee.as_ref(), commitment_signed)
744 _ => panic!("Unexpected event"),
746 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
748 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
749 check_added_monitors!(nodes[1], 1);
751 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
753 // nothing happens since node[1] is in AwaitingRemoteRevoke
754 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
756 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
757 assert_eq!(added_monitors.len(), 0);
758 added_monitors.clear();
760 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
761 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762 // node[1] has nothing to do
764 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
765 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
766 check_added_monitors!(nodes[0], 1);
768 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
769 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
770 // No commitment_signed so get_event_msg's assert(len == 1) passes
771 check_added_monitors!(nodes[0], 1);
772 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
773 check_added_monitors!(nodes[1], 1);
774 // AwaitingRemoteRevoke ends here
776 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
777 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
778 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
779 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
780 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
781 assert_eq!(commitment_update.update_fee.is_none(), true);
783 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
784 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
785 check_added_monitors!(nodes[0], 1);
786 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
788 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
789 check_added_monitors!(nodes[1], 1);
790 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
792 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
793 check_added_monitors!(nodes[1], 1);
794 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
795 // No commitment_signed so get_event_msg's assert(len == 1) passes
797 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
798 check_added_monitors!(nodes[0], 1);
799 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
801 expect_pending_htlcs_forwardable!(nodes[0]);
803 let events = nodes[0].node.get_and_clear_pending_events();
804 assert_eq!(events.len(), 1);
806 Event::PaymentReceived { .. } => { },
807 _ => panic!("Unexpected event"),
810 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
812 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
813 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
814 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
815 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
816 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
820 fn test_update_fee() {
821 let chanmon_cfgs = create_chanmon_cfgs(2);
822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
825 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
826 let channel_id = chan.2;
829 // (1) update_fee/commitment_signed ->
830 // <- (2) revoke_and_ack
831 // .- send (3) commitment_signed
832 // (4) update_fee/commitment_signed ->
833 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
834 // <- (3) commitment_signed delivered
835 // send (6) revoke_and_ack -.
836 // <- (5) deliver revoke_and_ack
837 // (6) deliver revoke_and_ack ->
838 // .- send (7) commitment_signed in response to (4)
839 // <- (7) deliver commitment_signed
842 // Create and deliver (1)...
845 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
846 feerate = *feerate_lock;
847 *feerate_lock = feerate + 20;
849 nodes[0].node.timer_tick_occurred();
850 check_added_monitors!(nodes[0], 1);
852 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
853 assert_eq!(events_0.len(), 1);
854 let (update_msg, commitment_signed) = match events_0[0] {
855 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
856 (update_fee.as_ref(), commitment_signed)
858 _ => panic!("Unexpected event"),
860 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
862 // Generate (2) and (3):
863 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
864 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
865 check_added_monitors!(nodes[1], 1);
868 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 check_added_monitors!(nodes[0], 1);
872 // Create and deliver (4)...
874 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
875 *feerate_lock = feerate + 30;
877 nodes[0].node.timer_tick_occurred();
878 check_added_monitors!(nodes[0], 1);
879 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
880 assert_eq!(events_0.len(), 1);
881 let (update_msg, commitment_signed) = match events_0[0] {
882 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
883 (update_fee.as_ref(), commitment_signed)
885 _ => panic!("Unexpected event"),
888 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
890 check_added_monitors!(nodes[1], 1);
892 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
893 // No commitment_signed so get_event_msg's assert(len == 1) passes
895 // Handle (3), creating (6):
896 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
897 check_added_monitors!(nodes[0], 1);
898 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
899 // No commitment_signed so get_event_msg's assert(len == 1) passes
902 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
903 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
904 check_added_monitors!(nodes[0], 1);
906 // Deliver (6), creating (7):
907 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
908 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
909 assert!(commitment_update.update_add_htlcs.is_empty());
910 assert!(commitment_update.update_fulfill_htlcs.is_empty());
911 assert!(commitment_update.update_fail_htlcs.is_empty());
912 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
913 assert!(commitment_update.update_fee.is_none());
914 check_added_monitors!(nodes[1], 1);
917 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
918 check_added_monitors!(nodes[0], 1);
919 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
920 // No commitment_signed so get_event_msg's assert(len == 1) passes
922 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
923 check_added_monitors!(nodes[1], 1);
924 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
926 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
927 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
928 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
929 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
930 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
934 fn fake_network_test() {
935 // Simple test which builds a network of ChannelManagers, connects them to each other, and
936 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
937 let chanmon_cfgs = create_chanmon_cfgs(4);
938 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
939 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
940 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
942 // Create some initial channels
943 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
944 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
945 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
947 // Rebalance the network a bit by relaying one payment through all the channels...
948 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
949 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
950 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
951 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
953 // Send some more payments
954 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
955 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
956 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
958 // Test failure packets
959 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
960 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
962 // Add a new channel that skips 3
963 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
965 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
966 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
967 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
968 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
969 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
970 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
971 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
973 // Do some rebalance loop payments, simultaneously
974 let mut hops = Vec::with_capacity(3);
976 pubkey: nodes[2].node.get_our_node_id(),
977 node_features: NodeFeatures::empty(),
978 short_channel_id: chan_2.0.contents.short_channel_id,
979 channel_features: ChannelFeatures::empty(),
981 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
984 pubkey: nodes[3].node.get_our_node_id(),
985 node_features: NodeFeatures::empty(),
986 short_channel_id: chan_3.0.contents.short_channel_id,
987 channel_features: ChannelFeatures::empty(),
989 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
992 pubkey: nodes[1].node.get_our_node_id(),
993 node_features: NodeFeatures::known(),
994 short_channel_id: chan_4.0.contents.short_channel_id,
995 channel_features: ChannelFeatures::known(),
997 cltv_expiry_delta: TEST_FINAL_CLTV,
999 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1000 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1001 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1003 let mut hops = Vec::with_capacity(3);
1004 hops.push(RouteHop {
1005 pubkey: nodes[3].node.get_our_node_id(),
1006 node_features: NodeFeatures::empty(),
1007 short_channel_id: chan_4.0.contents.short_channel_id,
1008 channel_features: ChannelFeatures::empty(),
1010 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1012 hops.push(RouteHop {
1013 pubkey: nodes[2].node.get_our_node_id(),
1014 node_features: NodeFeatures::empty(),
1015 short_channel_id: chan_3.0.contents.short_channel_id,
1016 channel_features: ChannelFeatures::empty(),
1018 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1020 hops.push(RouteHop {
1021 pubkey: nodes[1].node.get_our_node_id(),
1022 node_features: NodeFeatures::known(),
1023 short_channel_id: chan_2.0.contents.short_channel_id,
1024 channel_features: ChannelFeatures::known(),
1026 cltv_expiry_delta: TEST_FINAL_CLTV,
1028 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1029 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1030 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1032 // Claim the rebalances...
1033 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1034 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1036 // Add a duplicate new channel from 2 to 4
1037 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1039 // Send some payments across both channels
1040 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1041 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1042 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1045 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1046 let events = nodes[0].node.get_and_clear_pending_msg_events();
1047 assert_eq!(events.len(), 0);
1048 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1050 //TODO: Test that routes work again here as we've been notified that the channel is full
1052 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1053 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1054 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1056 // Close down the channels...
1057 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1058 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1059 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1060 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1061 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1062 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1063 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1064 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1065 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1066 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1067 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1068 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1069 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1070 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1071 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1075 fn holding_cell_htlc_counting() {
1076 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1077 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1078 // commitment dance rounds.
1079 let chanmon_cfgs = create_chanmon_cfgs(3);
1080 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1081 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1082 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1083 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1084 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1086 let mut payments = Vec::new();
1087 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1088 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1089 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1090 payments.push((payment_preimage, payment_hash));
1092 check_added_monitors!(nodes[1], 1);
1094 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1095 assert_eq!(events.len(), 1);
1096 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1097 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1099 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1100 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1102 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1104 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1105 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1106 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1110 // This should also be true if we try to forward a payment.
1111 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1113 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1114 check_added_monitors!(nodes[0], 1);
1117 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1122 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1123 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1124 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1125 // fails), the second will process the resulting failure and fail the HTLC backward.
1126 expect_pending_htlcs_forwardable!(nodes[1]);
1127 expect_pending_htlcs_forwardable!(nodes[1]);
1128 check_added_monitors!(nodes[1], 1);
1130 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1131 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1132 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1134 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1136 // Now forward all the pending HTLCs and claim them back
1137 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1138 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1139 check_added_monitors!(nodes[2], 1);
1141 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1142 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1143 check_added_monitors!(nodes[1], 1);
1144 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1146 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1147 check_added_monitors!(nodes[1], 1);
1148 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1150 for ref update in as_updates.update_add_htlcs.iter() {
1151 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1153 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1154 check_added_monitors!(nodes[2], 1);
1155 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1156 check_added_monitors!(nodes[2], 1);
1157 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1159 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1160 check_added_monitors!(nodes[1], 1);
1161 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162 check_added_monitors!(nodes[1], 1);
1163 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1165 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1166 check_added_monitors!(nodes[2], 1);
1168 expect_pending_htlcs_forwardable!(nodes[2]);
1170 let events = nodes[2].node.get_and_clear_pending_events();
1171 assert_eq!(events.len(), payments.len());
1172 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1174 &Event::PaymentReceived { ref payment_hash, .. } => {
1175 assert_eq!(*payment_hash, *hash);
1177 _ => panic!("Unexpected event"),
1181 for (preimage, _) in payments.drain(..) {
1182 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1185 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1189 fn duplicate_htlc_test() {
1190 // Test that we accept duplicate payment_hash HTLCs across the network and that
1191 // claiming/failing them are all separate and don't affect each other
1192 let chanmon_cfgs = create_chanmon_cfgs(6);
1193 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1194 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1195 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1197 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1198 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1199 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1200 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1201 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1202 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1204 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1206 *nodes[0].network_payment_count.borrow_mut() -= 1;
1207 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1209 *nodes[0].network_payment_count.borrow_mut() -= 1;
1210 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1212 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1213 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1214 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1218 fn test_duplicate_htlc_different_direction_onchain() {
1219 // Test that ChannelMonitor doesn't generate 2 preimage txn
1220 // when we have 2 HTLCs with same preimage that go across a node
1221 // in opposite directions, even with the same payment secret.
1222 let chanmon_cfgs = create_chanmon_cfgs(2);
1223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1225 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1227 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1230 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1232 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1234 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1235 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1236 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1238 // Provide preimage to node 0 by claiming payment
1239 nodes[0].node.claim_funds(payment_preimage);
1240 check_added_monitors!(nodes[0], 1);
1242 // Broadcast node 1 commitment txn
1243 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1245 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1246 let mut has_both_htlcs = 0; // check htlcs match ones committed
1247 for outp in remote_txn[0].output.iter() {
1248 if outp.value == 800_000 / 1000 {
1249 has_both_htlcs += 1;
1250 } else if outp.value == 900_000 / 1000 {
1251 has_both_htlcs += 1;
1254 assert_eq!(has_both_htlcs, 2);
1256 mine_transaction(&nodes[0], &remote_txn[0]);
1257 check_added_monitors!(nodes[0], 1);
1258 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1259 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1261 // Check we only broadcast 1 timeout tx
1262 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1263 assert_eq!(claim_txn.len(), 8);
1264 assert_eq!(claim_txn[1], claim_txn[4]);
1265 assert_eq!(claim_txn[2], claim_txn[5]);
1266 check_spends!(claim_txn[1], chan_1.3);
1267 check_spends!(claim_txn[2], claim_txn[1]);
1268 check_spends!(claim_txn[7], claim_txn[1]);
1270 assert_eq!(claim_txn[0].input.len(), 1);
1271 assert_eq!(claim_txn[3].input.len(), 1);
1272 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1274 assert_eq!(claim_txn[0].input.len(), 1);
1275 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1276 check_spends!(claim_txn[0], remote_txn[0]);
1277 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1278 assert_eq!(claim_txn[6].input.len(), 1);
1279 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1280 check_spends!(claim_txn[6], remote_txn[0]);
1281 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1283 let events = nodes[0].node.get_and_clear_pending_msg_events();
1284 assert_eq!(events.len(), 3);
1287 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1288 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1289 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1290 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1292 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1293 assert!(update_add_htlcs.is_empty());
1294 assert!(update_fail_htlcs.is_empty());
1295 assert_eq!(update_fulfill_htlcs.len(), 1);
1296 assert!(update_fail_malformed_htlcs.is_empty());
1297 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1299 _ => panic!("Unexpected event"),
1305 fn test_basic_channel_reserve() {
1306 let chanmon_cfgs = create_chanmon_cfgs(2);
1307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1309 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1310 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1312 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1313 let channel_reserve = chan_stat.channel_reserve_msat;
1315 // The 2* and +1 are for the fee spike reserve.
1316 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1, get_opt_anchors!(nodes[0], chan.2));
1317 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1318 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1319 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1321 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1323 &APIError::ChannelUnavailable{ref err} =>
1324 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1325 _ => panic!("Unexpected error variant"),
1328 _ => panic!("Unexpected error variant"),
1330 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1331 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1333 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1337 fn test_fee_spike_violation_fails_htlc() {
1338 let chanmon_cfgs = create_chanmon_cfgs(2);
1339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1342 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1344 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1345 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1346 let secp_ctx = Secp256k1::new();
1347 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1349 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1351 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1352 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1353 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1354 let msg = msgs::UpdateAddHTLC {
1357 amount_msat: htlc_msat,
1358 payment_hash: payment_hash,
1359 cltv_expiry: htlc_cltv,
1360 onion_routing_packet: onion_packet,
1363 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1365 // Now manually create the commitment_signed message corresponding to the update_add
1366 // nodes[0] just sent. In the code for construction of this message, "local" refers
1367 // to the sender of the message, and "remote" refers to the receiver.
1369 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1371 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1373 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1374 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1375 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1376 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1377 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1378 let chan_signer = local_chan.get_signer();
1379 // Make the signer believe we validated another commitment, so we can release the secret
1380 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1382 let pubkeys = chan_signer.pubkeys();
1383 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1384 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1385 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1386 chan_signer.pubkeys().funding_pubkey)
1388 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1389 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1390 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1391 let chan_signer = remote_chan.get_signer();
1392 let pubkeys = chan_signer.pubkeys();
1393 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1394 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1395 chan_signer.pubkeys().funding_pubkey)
1398 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1399 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1400 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1402 // Build the remote commitment transaction so we can sign it, and then later use the
1403 // signature for the commitment_signed message.
1404 let local_chan_balance = 1313;
1406 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1408 amount_msat: 3460001,
1409 cltv_expiry: htlc_cltv,
1411 transaction_output_index: Some(1),
1414 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1417 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1418 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1419 let local_chan_signer = local_chan.get_signer();
1420 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1424 local_chan.opt_anchors(), local_funding, remote_funding,
1425 commit_tx_keys.clone(),
1427 &mut vec![(accepted_htlc_info, ())],
1428 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1430 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1433 let commit_signed_msg = msgs::CommitmentSigned {
1436 htlc_signatures: res.1
1439 // Send the commitment_signed message to the nodes[1].
1440 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1441 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1443 // Send the RAA to nodes[1].
1444 let raa_msg = msgs::RevokeAndACK {
1446 per_commitment_secret: local_secret,
1447 next_per_commitment_point: next_local_point
1449 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1451 let events = nodes[1].node.get_and_clear_pending_msg_events();
1452 assert_eq!(events.len(), 1);
1453 // Make sure the HTLC failed in the way we expect.
1455 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1456 assert_eq!(update_fail_htlcs.len(), 1);
1457 update_fail_htlcs[0].clone()
1459 _ => panic!("Unexpected event"),
1461 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1462 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1464 check_added_monitors!(nodes[1], 2);
1468 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1469 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1470 // Set the fee rate for the channel very high, to the point where the fundee
1471 // sending any above-dust amount would result in a channel reserve violation.
1472 // In this test we check that we would be prevented from sending an HTLC in
1474 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1479 let opt_anchors = false;
1481 let mut push_amt = 100_000_000;
1482 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1483 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1485 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1487 // Sending exactly enough to hit the reserve amount should be accepted
1488 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1489 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1492 // However one more HTLC should be significantly over the reserve amount and fail.
1493 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1494 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1495 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1496 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1497 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1501 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1502 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1503 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1506 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1508 let opt_anchors = false;
1510 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1511 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1512 // transaction fee with 0 HTLCs (183 sats)).
1513 let mut push_amt = 100_000_000;
1514 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1515 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1516 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1518 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1519 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1520 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1523 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1524 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1525 let secp_ctx = Secp256k1::new();
1526 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1527 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1528 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1529 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1530 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1531 let msg = msgs::UpdateAddHTLC {
1533 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1534 amount_msat: htlc_msat,
1535 payment_hash: payment_hash,
1536 cltv_expiry: htlc_cltv,
1537 onion_routing_packet: onion_packet,
1540 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1541 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1542 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1543 assert_eq!(nodes[0].node.list_channels().len(), 0);
1544 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1545 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1546 check_added_monitors!(nodes[0], 1);
1547 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1551 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1552 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1553 // calculating our commitment transaction fee (this was previously broken).
1554 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1555 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1561 let opt_anchors = false;
1563 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1564 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1565 // transaction fee with 0 HTLCs (183 sats)).
1566 let mut push_amt = 100_000_000;
1567 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1568 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1569 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1571 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1572 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1573 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1574 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1575 // commitment transaction fee.
1576 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1578 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1579 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1580 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1583 // One more than the dust amt should fail, however.
1584 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1585 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1586 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1590 fn test_chan_init_feerate_unaffordability() {
1591 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1592 // channel reserve and feerate requirements.
1593 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1594 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1599 let opt_anchors = false;
1601 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1603 let mut push_amt = 100_000_000;
1604 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1605 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1606 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1608 // During open, we don't have a "counterparty channel reserve" to check against, so that
1609 // requirement only comes into play on the open_channel handling side.
1610 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1611 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1612 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1613 open_channel_msg.push_msat += 1;
1614 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1616 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1617 assert_eq!(msg_events.len(), 1);
1618 match msg_events[0] {
1619 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1620 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1622 _ => panic!("Unexpected event"),
1627 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1628 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1629 // calculating our counterparty's commitment transaction fee (this was previously broken).
1630 let chanmon_cfgs = create_chanmon_cfgs(2);
1631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1633 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1634 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1636 let payment_amt = 46000; // Dust amount
1637 // In the previous code, these first four payments would succeed.
1638 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1639 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1640 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1641 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1643 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1644 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1645 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1646 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1647 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1648 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1650 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1651 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1652 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1653 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1657 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1658 let chanmon_cfgs = create_chanmon_cfgs(3);
1659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1661 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1662 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1663 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1666 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1667 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1668 let feerate = get_feerate!(nodes[0], chan.2);
1669 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
1671 // Add a 2* and +1 for the fee spike reserve.
1672 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1673 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1674 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1676 // Add a pending HTLC.
1677 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1678 let payment_event_1 = {
1679 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1680 check_added_monitors!(nodes[0], 1);
1682 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1683 assert_eq!(events.len(), 1);
1684 SendEvent::from_event(events.remove(0))
1686 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1688 // Attempt to trigger a channel reserve violation --> payment failure.
1689 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1690 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1691 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1692 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1694 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1695 let secp_ctx = Secp256k1::new();
1696 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1697 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1698 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1699 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1700 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1701 let msg = msgs::UpdateAddHTLC {
1704 amount_msat: htlc_msat + 1,
1705 payment_hash: our_payment_hash_1,
1706 cltv_expiry: htlc_cltv,
1707 onion_routing_packet: onion_packet,
1710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1711 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1712 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1713 assert_eq!(nodes[1].node.list_channels().len(), 1);
1714 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1715 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1716 check_added_monitors!(nodes[1], 1);
1717 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1721 fn test_inbound_outbound_capacity_is_not_zero() {
1722 let chanmon_cfgs = create_chanmon_cfgs(2);
1723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1726 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1727 let channels0 = node_chanmgrs[0].list_channels();
1728 let channels1 = node_chanmgrs[1].list_channels();
1729 assert_eq!(channels0.len(), 1);
1730 assert_eq!(channels1.len(), 1);
1732 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1733 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1734 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1736 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1737 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1740 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1741 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1745 fn test_channel_reserve_holding_cell_htlcs() {
1746 let chanmon_cfgs = create_chanmon_cfgs(3);
1747 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1748 // When this test was written, the default base fee floated based on the HTLC count.
1749 // It is now fixed, so we simply set the fee to the expected value here.
1750 let mut config = test_default_channel_config();
1751 config.channel_options.forwarding_fee_base_msat = 239;
1752 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1753 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1754 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1755 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1757 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1758 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1760 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1761 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1763 macro_rules! expect_forward {
1765 let mut events = $node.node.get_and_clear_pending_msg_events();
1766 assert_eq!(events.len(), 1);
1767 check_added_monitors!($node, 1);
1768 let payment_event = SendEvent::from_event(events.remove(0));
1773 let feemsat = 239; // set above
1774 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1775 let feerate = get_feerate!(nodes[0], chan_1.2);
1776 let opt_anchors = get_opt_anchors!(nodes[0], chan_1.2);
1778 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1780 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1782 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1783 route.paths[0].last_mut().unwrap().fee_msat += 1;
1784 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1785 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1786 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1787 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1788 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1791 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1792 // nodes[0]'s wealth
1794 let amt_msat = recv_value_0 + total_fee_msat;
1795 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1796 // Also, ensure that each payment has enough to be over the dust limit to
1797 // ensure it'll be included in each commit tx fee calculation.
1798 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1799 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1800 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1803 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1805 let (stat01_, stat11_, stat12_, stat22_) = (
1806 get_channel_value_stat!(nodes[0], chan_1.2),
1807 get_channel_value_stat!(nodes[1], chan_1.2),
1808 get_channel_value_stat!(nodes[1], chan_2.2),
1809 get_channel_value_stat!(nodes[2], chan_2.2),
1812 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1813 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1814 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1815 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1816 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1819 // adding pending output.
1820 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1821 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1822 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1823 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1824 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1825 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1826 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1827 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1828 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1830 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1831 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1832 let amt_msat_1 = recv_value_1 + total_fee_msat;
1834 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1835 let payment_event_1 = {
1836 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1837 check_added_monitors!(nodes[0], 1);
1839 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1840 assert_eq!(events.len(), 1);
1841 SendEvent::from_event(events.remove(0))
1843 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1845 // channel reserve test with htlc pending output > 0
1846 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1848 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1849 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1850 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1851 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1854 // split the rest to test holding cell
1855 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1856 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1857 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1858 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1860 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1861 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1864 // now see if they go through on both sides
1865 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1866 // but this will stuck in the holding cell
1867 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1868 check_added_monitors!(nodes[0], 0);
1869 let events = nodes[0].node.get_and_clear_pending_events();
1870 assert_eq!(events.len(), 0);
1872 // test with outbound holding cell amount > 0
1874 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1875 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1876 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1877 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1878 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1881 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1882 // this will also stuck in the holding cell
1883 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1884 check_added_monitors!(nodes[0], 0);
1885 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1888 // flush the pending htlc
1889 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1890 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1891 check_added_monitors!(nodes[1], 1);
1893 // the pending htlc should be promoted to committed
1894 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1895 check_added_monitors!(nodes[0], 1);
1896 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1898 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1899 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1900 // No commitment_signed so get_event_msg's assert(len == 1) passes
1901 check_added_monitors!(nodes[0], 1);
1903 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1905 check_added_monitors!(nodes[1], 1);
1907 expect_pending_htlcs_forwardable!(nodes[1]);
1909 let ref payment_event_11 = expect_forward!(nodes[1]);
1910 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1911 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1913 expect_pending_htlcs_forwardable!(nodes[2]);
1914 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1916 // flush the htlcs in the holding cell
1917 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1918 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1920 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1921 expect_pending_htlcs_forwardable!(nodes[1]);
1923 let ref payment_event_3 = expect_forward!(nodes[1]);
1924 assert_eq!(payment_event_3.msgs.len(), 2);
1925 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1926 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1928 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1929 expect_pending_htlcs_forwardable!(nodes[2]);
1931 let events = nodes[2].node.get_and_clear_pending_events();
1932 assert_eq!(events.len(), 2);
1934 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1935 assert_eq!(our_payment_hash_21, *payment_hash);
1936 assert_eq!(recv_value_21, amt);
1938 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1939 assert!(payment_preimage.is_none());
1940 assert_eq!(our_payment_secret_21, *payment_secret);
1942 _ => panic!("expected PaymentPurpose::InvoicePayment")
1945 _ => panic!("Unexpected event"),
1948 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1949 assert_eq!(our_payment_hash_22, *payment_hash);
1950 assert_eq!(recv_value_22, amt);
1952 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1953 assert!(payment_preimage.is_none());
1954 assert_eq!(our_payment_secret_22, *payment_secret);
1956 _ => panic!("expected PaymentPurpose::InvoicePayment")
1959 _ => panic!("Unexpected event"),
1962 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1963 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1964 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1966 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
1967 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1968 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1970 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
1971 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
1972 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1973 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1974 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1976 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1977 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1981 fn channel_reserve_in_flight_removes() {
1982 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1983 // can send to its counterparty, but due to update ordering, the other side may not yet have
1984 // considered those HTLCs fully removed.
1985 // This tests that we don't count HTLCs which will not be included in the next remote
1986 // commitment transaction towards the reserve value (as it implies no commitment transaction
1987 // will be generated which violates the remote reserve value).
1988 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1990 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1991 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1992 // you only consider the value of the first HTLC, it may not),
1993 // * start routing a third HTLC from A to B,
1994 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1995 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1996 // * deliver the first fulfill from B
1997 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1999 // * deliver A's response CS and RAA.
2000 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2001 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2002 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2003 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2004 let chanmon_cfgs = create_chanmon_cfgs(2);
2005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2007 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2008 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2010 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2011 // Route the first two HTLCs.
2012 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2013 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2015 // Start routing the third HTLC (this is just used to get everyone in the right state).
2016 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2018 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2019 check_added_monitors!(nodes[0], 1);
2020 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2021 assert_eq!(events.len(), 1);
2022 SendEvent::from_event(events.remove(0))
2025 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2026 // initial fulfill/CS.
2027 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2028 check_added_monitors!(nodes[1], 1);
2029 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2031 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2032 // remove the second HTLC when we send the HTLC back from B to A.
2033 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2034 check_added_monitors!(nodes[1], 1);
2035 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2037 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2039 check_added_monitors!(nodes[0], 1);
2040 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2041 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2044 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2045 check_added_monitors!(nodes[1], 1);
2046 // B is already AwaitingRAA, so cant generate a CS here
2047 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2049 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2050 check_added_monitors!(nodes[1], 1);
2051 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2053 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2054 check_added_monitors!(nodes[0], 1);
2055 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2057 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2058 check_added_monitors!(nodes[1], 1);
2059 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2061 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2062 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2063 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2064 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2065 // on-chain as necessary).
2066 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2068 check_added_monitors!(nodes[0], 1);
2069 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2070 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2072 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2073 check_added_monitors!(nodes[1], 1);
2074 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2076 expect_pending_htlcs_forwardable!(nodes[1]);
2077 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2079 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2080 // resolve the second HTLC from A's point of view.
2081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2082 check_added_monitors!(nodes[0], 1);
2083 expect_payment_path_successful!(nodes[0]);
2084 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2087 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2088 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2090 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2091 check_added_monitors!(nodes[1], 1);
2092 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2093 assert_eq!(events.len(), 1);
2094 SendEvent::from_event(events.remove(0))
2097 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2098 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2099 check_added_monitors!(nodes[0], 1);
2100 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2102 // Now just resolve all the outstanding messages/HTLCs for completeness...
2104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2105 check_added_monitors!(nodes[1], 1);
2106 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2108 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2109 check_added_monitors!(nodes[1], 1);
2111 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2112 check_added_monitors!(nodes[0], 1);
2113 expect_payment_path_successful!(nodes[0]);
2114 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2116 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2117 check_added_monitors!(nodes[1], 1);
2118 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2120 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121 check_added_monitors!(nodes[0], 1);
2123 expect_pending_htlcs_forwardable!(nodes[0]);
2124 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2126 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2127 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2131 fn channel_monitor_network_test() {
2132 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2133 // tests that ChannelMonitor is able to recover from various states.
2134 let chanmon_cfgs = create_chanmon_cfgs(5);
2135 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2136 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2137 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2139 // Create some initial channels
2140 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2141 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2142 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2143 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2145 // Make sure all nodes are at the same starting height
2146 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2147 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2148 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2149 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2150 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2152 // Rebalance the network a bit by relaying one payment through all the channels...
2153 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2154 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2155 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2156 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2158 // Simple case with no pending HTLCs:
2159 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2160 check_added_monitors!(nodes[1], 1);
2161 check_closed_broadcast!(nodes[1], false);
2163 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2164 assert_eq!(node_txn.len(), 1);
2165 mine_transaction(&nodes[0], &node_txn[0]);
2166 check_added_monitors!(nodes[0], 1);
2167 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2169 check_closed_broadcast!(nodes[0], true);
2170 assert_eq!(nodes[0].node.list_channels().len(), 0);
2171 assert_eq!(nodes[1].node.list_channels().len(), 1);
2172 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2173 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2175 // One pending HTLC is discarded by the force-close:
2176 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2178 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2179 // broadcasted until we reach the timelock time).
2180 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2181 check_closed_broadcast!(nodes[1], false);
2182 check_added_monitors!(nodes[1], 1);
2184 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2185 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2186 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2187 mine_transaction(&nodes[2], &node_txn[0]);
2188 check_added_monitors!(nodes[2], 1);
2189 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2191 check_closed_broadcast!(nodes[2], true);
2192 assert_eq!(nodes[1].node.list_channels().len(), 0);
2193 assert_eq!(nodes[2].node.list_channels().len(), 1);
2194 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2195 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2197 macro_rules! claim_funds {
2198 ($node: expr, $prev_node: expr, $preimage: expr) => {
2200 assert!($node.node.claim_funds($preimage));
2201 check_added_monitors!($node, 1);
2203 let events = $node.node.get_and_clear_pending_msg_events();
2204 assert_eq!(events.len(), 1);
2206 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2207 assert!(update_add_htlcs.is_empty());
2208 assert!(update_fail_htlcs.is_empty());
2209 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2211 _ => panic!("Unexpected event"),
2217 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2218 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2219 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2220 check_added_monitors!(nodes[2], 1);
2221 check_closed_broadcast!(nodes[2], false);
2222 let node2_commitment_txid;
2224 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2225 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2226 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2227 node2_commitment_txid = node_txn[0].txid();
2229 // Claim the payment on nodes[3], giving it knowledge of the preimage
2230 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2231 mine_transaction(&nodes[3], &node_txn[0]);
2232 check_added_monitors!(nodes[3], 1);
2233 check_preimage_claim(&nodes[3], &node_txn);
2235 check_closed_broadcast!(nodes[3], true);
2236 assert_eq!(nodes[2].node.list_channels().len(), 0);
2237 assert_eq!(nodes[3].node.list_channels().len(), 1);
2238 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2239 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2241 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2242 // confusing us in the following tests.
2243 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2245 // One pending HTLC to time out:
2246 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2247 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2250 let (close_chan_update_1, close_chan_update_2) = {
2251 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2252 let events = nodes[3].node.get_and_clear_pending_msg_events();
2253 assert_eq!(events.len(), 2);
2254 let close_chan_update_1 = match events[0] {
2255 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2258 _ => panic!("Unexpected event"),
2261 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2262 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2264 _ => panic!("Unexpected event"),
2266 check_added_monitors!(nodes[3], 1);
2268 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2270 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2271 node_txn.retain(|tx| {
2272 if tx.input[0].previous_output.txid == node2_commitment_txid {
2278 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2280 // Claim the payment on nodes[4], giving it knowledge of the preimage
2281 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2283 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2284 let events = nodes[4].node.get_and_clear_pending_msg_events();
2285 assert_eq!(events.len(), 2);
2286 let close_chan_update_2 = match events[0] {
2287 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2290 _ => panic!("Unexpected event"),
2293 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2294 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2296 _ => panic!("Unexpected event"),
2298 check_added_monitors!(nodes[4], 1);
2299 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2301 mine_transaction(&nodes[4], &node_txn[0]);
2302 check_preimage_claim(&nodes[4], &node_txn);
2303 (close_chan_update_1, close_chan_update_2)
2305 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2306 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2307 assert_eq!(nodes[3].node.list_channels().len(), 0);
2308 assert_eq!(nodes[4].node.list_channels().len(), 0);
2310 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2311 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2312 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2316 fn test_justice_tx() {
2317 // Test justice txn built on revoked HTLC-Success tx, against both sides
2318 let mut alice_config = UserConfig::default();
2319 alice_config.channel_options.announced_channel = true;
2320 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2321 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2322 let mut bob_config = UserConfig::default();
2323 bob_config.channel_options.announced_channel = true;
2324 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2325 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2326 let user_cfgs = [Some(alice_config), Some(bob_config)];
2327 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2328 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2329 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2333 // Create some new channels:
2334 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2336 // A pending HTLC which will be revoked:
2337 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338 // Get the will-be-revoked local txn from nodes[0]
2339 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2340 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2341 assert_eq!(revoked_local_txn[0].input.len(), 1);
2342 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2343 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2344 assert_eq!(revoked_local_txn[1].input.len(), 1);
2345 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2346 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2347 // Revoke the old state
2348 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2351 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2353 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2354 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2355 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2357 check_spends!(node_txn[0], revoked_local_txn[0]);
2358 node_txn.swap_remove(0);
2359 node_txn.truncate(1);
2361 check_added_monitors!(nodes[1], 1);
2362 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2363 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2365 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2366 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2367 // Verify broadcast of revoked HTLC-timeout
2368 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2369 check_added_monitors!(nodes[0], 1);
2370 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2371 // Broadcast revoked HTLC-timeout on node 1
2372 mine_transaction(&nodes[1], &node_txn[1]);
2373 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2375 get_announce_close_broadcast_events(&nodes, 0, 1);
2377 assert_eq!(nodes[0].node.list_channels().len(), 0);
2378 assert_eq!(nodes[1].node.list_channels().len(), 0);
2380 // We test justice_tx build by A on B's revoked HTLC-Success tx
2381 // Create some new channels:
2382 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2384 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2388 // A pending HTLC which will be revoked:
2389 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2390 // Get the will-be-revoked local txn from B
2391 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2392 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2393 assert_eq!(revoked_local_txn[0].input.len(), 1);
2394 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2395 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2396 // Revoke the old state
2397 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2399 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2401 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2402 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2403 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2405 check_spends!(node_txn[0], revoked_local_txn[0]);
2406 node_txn.swap_remove(0);
2408 check_added_monitors!(nodes[0], 1);
2409 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2411 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2412 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2414 check_added_monitors!(nodes[1], 1);
2415 mine_transaction(&nodes[0], &node_txn[1]);
2416 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2417 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2419 get_announce_close_broadcast_events(&nodes, 0, 1);
2420 assert_eq!(nodes[0].node.list_channels().len(), 0);
2421 assert_eq!(nodes[1].node.list_channels().len(), 0);
2425 fn revoked_output_claim() {
2426 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2427 // transaction is broadcast by its counterparty
2428 let chanmon_cfgs = create_chanmon_cfgs(2);
2429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2433 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2434 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2435 assert_eq!(revoked_local_txn.len(), 1);
2436 // Only output is the full channel value back to nodes[0]:
2437 assert_eq!(revoked_local_txn[0].output.len(), 1);
2438 // Send a payment through, updating everyone's latest commitment txn
2439 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2441 // Inform nodes[1] that nodes[0] broadcast a stale tx
2442 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2443 check_added_monitors!(nodes[1], 1);
2444 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2445 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2446 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2448 check_spends!(node_txn[0], revoked_local_txn[0]);
2449 check_spends!(node_txn[1], chan_1.3);
2451 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2452 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2453 get_announce_close_broadcast_events(&nodes, 0, 1);
2454 check_added_monitors!(nodes[0], 1);
2455 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2459 fn claim_htlc_outputs_shared_tx() {
2460 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2461 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2462 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2467 // Create some new channel:
2468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2470 // Rebalance the network to generate htlc in the two directions
2471 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2472 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2473 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2476 // Get the will-be-revoked local txn from node[0]
2477 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2478 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2479 assert_eq!(revoked_local_txn[0].input.len(), 1);
2480 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2481 assert_eq!(revoked_local_txn[1].input.len(), 1);
2482 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2483 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2484 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2486 //Revoke the old state
2487 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2490 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2491 check_added_monitors!(nodes[0], 1);
2492 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2493 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2494 check_added_monitors!(nodes[1], 1);
2495 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2496 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2497 expect_payment_failed!(nodes[1], payment_hash_2, true);
2499 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2500 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2502 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2503 check_spends!(node_txn[0], revoked_local_txn[0]);
2505 let mut witness_lens = BTreeSet::new();
2506 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2507 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2508 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2509 assert_eq!(witness_lens.len(), 3);
2510 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2511 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2512 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2514 // Next nodes[1] broadcasts its current local tx state:
2515 assert_eq!(node_txn[1].input.len(), 1);
2516 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2518 get_announce_close_broadcast_events(&nodes, 0, 1);
2519 assert_eq!(nodes[0].node.list_channels().len(), 0);
2520 assert_eq!(nodes[1].node.list_channels().len(), 0);
2524 fn claim_htlc_outputs_single_tx() {
2525 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2526 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2527 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2532 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2534 // Rebalance the network to generate htlc in the two directions
2535 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2536 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2537 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2538 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2539 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2541 // Get the will-be-revoked local txn from node[0]
2542 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2544 //Revoke the old state
2545 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2548 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2549 check_added_monitors!(nodes[0], 1);
2550 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2551 check_added_monitors!(nodes[1], 1);
2552 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2553 let mut events = nodes[0].node.get_and_clear_pending_events();
2554 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2556 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2557 _ => panic!("Unexpected event"),
2560 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2561 expect_payment_failed!(nodes[1], payment_hash_2, true);
2563 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564 assert_eq!(node_txn.len(), 9);
2565 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2566 // ChannelManager: local commmitment + local HTLC-timeout (2)
2567 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2568 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2570 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2571 assert_eq!(node_txn[0].input.len(), 1);
2572 check_spends!(node_txn[0], chan_1.3);
2573 assert_eq!(node_txn[1].input.len(), 1);
2574 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2575 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2576 check_spends!(node_txn[1], node_txn[0]);
2578 // Justice transactions are indices 1-2-4
2579 assert_eq!(node_txn[2].input.len(), 1);
2580 assert_eq!(node_txn[3].input.len(), 1);
2581 assert_eq!(node_txn[4].input.len(), 1);
2583 check_spends!(node_txn[2], revoked_local_txn[0]);
2584 check_spends!(node_txn[3], revoked_local_txn[0]);
2585 check_spends!(node_txn[4], revoked_local_txn[0]);
2587 let mut witness_lens = BTreeSet::new();
2588 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2589 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2590 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2591 assert_eq!(witness_lens.len(), 3);
2592 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2593 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2594 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2596 get_announce_close_broadcast_events(&nodes, 0, 1);
2597 assert_eq!(nodes[0].node.list_channels().len(), 0);
2598 assert_eq!(nodes[1].node.list_channels().len(), 0);
2602 fn test_htlc_on_chain_success() {
2603 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2604 // the preimage backward accordingly. So here we test that ChannelManager is
2605 // broadcasting the right event to other nodes in payment path.
2606 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2607 // A --------------------> B ----------------------> C (preimage)
2608 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2609 // commitment transaction was broadcast.
2610 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2612 // B should be able to claim via preimage if A then broadcasts its local tx.
2613 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2614 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2615 // PaymentSent event).
2617 let chanmon_cfgs = create_chanmon_cfgs(3);
2618 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2620 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2622 // Create some initial channels
2623 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2624 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2626 // Ensure all nodes are at the same height
2627 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2628 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2629 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2630 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2632 // Rebalance the network a bit by relaying one payment through all the channels...
2633 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2634 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2636 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2637 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2639 // Broadcast legit commitment tx from C on B's chain
2640 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2641 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2642 assert_eq!(commitment_tx.len(), 1);
2643 check_spends!(commitment_tx[0], chan_2.3);
2644 nodes[2].node.claim_funds(our_payment_preimage);
2645 nodes[2].node.claim_funds(our_payment_preimage_2);
2646 check_added_monitors!(nodes[2], 2);
2647 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2648 assert!(updates.update_add_htlcs.is_empty());
2649 assert!(updates.update_fail_htlcs.is_empty());
2650 assert!(updates.update_fail_malformed_htlcs.is_empty());
2651 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2653 mine_transaction(&nodes[2], &commitment_tx[0]);
2654 check_closed_broadcast!(nodes[2], true);
2655 check_added_monitors!(nodes[2], 1);
2656 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2657 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2658 assert_eq!(node_txn.len(), 5);
2659 assert_eq!(node_txn[0], node_txn[3]);
2660 assert_eq!(node_txn[1], node_txn[4]);
2661 assert_eq!(node_txn[2], commitment_tx[0]);
2662 check_spends!(node_txn[0], commitment_tx[0]);
2663 check_spends!(node_txn[1], commitment_tx[0]);
2664 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2665 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2666 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2667 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2668 assert_eq!(node_txn[0].lock_time, 0);
2669 assert_eq!(node_txn[1].lock_time, 0);
2671 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2672 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2673 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2674 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2676 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2677 assert_eq!(added_monitors.len(), 1);
2678 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2679 added_monitors.clear();
2681 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2682 assert_eq!(forwarded_events.len(), 3);
2683 match forwarded_events[0] {
2684 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2685 _ => panic!("Unexpected event"),
2687 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2688 } else { panic!(); }
2689 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2690 } else { panic!(); }
2691 let events = nodes[1].node.get_and_clear_pending_msg_events();
2693 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2694 assert_eq!(added_monitors.len(), 2);
2695 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2696 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2697 added_monitors.clear();
2699 assert_eq!(events.len(), 3);
2701 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2702 _ => panic!("Unexpected event"),
2705 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2706 _ => panic!("Unexpected event"),
2710 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2711 assert!(update_add_htlcs.is_empty());
2712 assert!(update_fail_htlcs.is_empty());
2713 assert_eq!(update_fulfill_htlcs.len(), 1);
2714 assert!(update_fail_malformed_htlcs.is_empty());
2715 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2717 _ => panic!("Unexpected event"),
2719 macro_rules! check_tx_local_broadcast {
2720 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2721 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2722 assert_eq!(node_txn.len(), 3);
2723 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2724 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2725 check_spends!(node_txn[1], $commitment_tx);
2726 check_spends!(node_txn[2], $commitment_tx);
2727 assert_ne!(node_txn[1].lock_time, 0);
2728 assert_ne!(node_txn[2].lock_time, 0);
2730 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2731 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2732 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2733 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2735 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2736 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2737 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2738 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2740 check_spends!(node_txn[0], $chan_tx);
2741 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2745 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2746 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2747 // timeout-claim of the output that nodes[2] just claimed via success.
2748 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2750 // Broadcast legit commitment tx from A on B's chain
2751 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2752 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2753 check_spends!(node_a_commitment_tx[0], chan_1.3);
2754 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2755 check_closed_broadcast!(nodes[1], true);
2756 check_added_monitors!(nodes[1], 1);
2757 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2758 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2759 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2760 let commitment_spend =
2761 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2762 check_spends!(node_txn[1], commitment_tx[0]);
2763 check_spends!(node_txn[2], commitment_tx[0]);
2764 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2767 check_spends!(node_txn[0], commitment_tx[0]);
2768 check_spends!(node_txn[1], commitment_tx[0]);
2769 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2773 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2774 assert_eq!(commitment_spend.input.len(), 2);
2775 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2776 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2777 assert_eq!(commitment_spend.lock_time, 0);
2778 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2779 check_spends!(node_txn[3], chan_1.3);
2780 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2781 check_spends!(node_txn[4], node_txn[3]);
2782 check_spends!(node_txn[5], node_txn[3]);
2783 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2784 // we already checked the same situation with A.
2786 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2787 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2788 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2789 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2790 check_closed_broadcast!(nodes[0], true);
2791 check_added_monitors!(nodes[0], 1);
2792 let events = nodes[0].node.get_and_clear_pending_events();
2793 assert_eq!(events.len(), 5);
2794 let mut first_claimed = false;
2795 for event in events {
2797 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2798 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2799 assert!(!first_claimed);
2800 first_claimed = true;
2802 assert_eq!(payment_preimage, our_payment_preimage_2);
2803 assert_eq!(payment_hash, payment_hash_2);
2806 Event::PaymentPathSuccessful { .. } => {},
2807 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2808 _ => panic!("Unexpected event"),
2811 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2814 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2815 // Test that in case of a unilateral close onchain, we detect the state of output and
2816 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2817 // broadcasting the right event to other nodes in payment path.
2818 // A ------------------> B ----------------------> C (timeout)
2819 // B's commitment tx C's commitment tx
2821 // B's HTLC timeout tx B's timeout tx
2823 let chanmon_cfgs = create_chanmon_cfgs(3);
2824 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2825 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2826 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2827 *nodes[0].connect_style.borrow_mut() = connect_style;
2828 *nodes[1].connect_style.borrow_mut() = connect_style;
2829 *nodes[2].connect_style.borrow_mut() = connect_style;
2831 // Create some intial channels
2832 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2833 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2835 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2836 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2837 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2839 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2841 // Broadcast legit commitment tx from C on B's chain
2842 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2843 check_spends!(commitment_tx[0], chan_2.3);
2844 nodes[2].node.fail_htlc_backwards(&payment_hash);
2845 check_added_monitors!(nodes[2], 0);
2846 expect_pending_htlcs_forwardable!(nodes[2]);
2847 check_added_monitors!(nodes[2], 1);
2849 let events = nodes[2].node.get_and_clear_pending_msg_events();
2850 assert_eq!(events.len(), 1);
2852 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2853 assert!(update_add_htlcs.is_empty());
2854 assert!(!update_fail_htlcs.is_empty());
2855 assert!(update_fulfill_htlcs.is_empty());
2856 assert!(update_fail_malformed_htlcs.is_empty());
2857 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2859 _ => panic!("Unexpected event"),
2861 mine_transaction(&nodes[2], &commitment_tx[0]);
2862 check_closed_broadcast!(nodes[2], true);
2863 check_added_monitors!(nodes[2], 1);
2864 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2865 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2866 assert_eq!(node_txn.len(), 1);
2867 check_spends!(node_txn[0], chan_2.3);
2868 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2870 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2871 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2872 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2873 mine_transaction(&nodes[1], &commitment_tx[0]);
2874 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2877 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2878 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2879 assert_eq!(node_txn[0], node_txn[3]);
2880 assert_eq!(node_txn[1], node_txn[4]);
2882 check_spends!(node_txn[2], commitment_tx[0]);
2883 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2885 check_spends!(node_txn[0], chan_2.3);
2886 check_spends!(node_txn[1], node_txn[0]);
2887 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2888 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2890 timeout_tx = node_txn[2].clone();
2894 mine_transaction(&nodes[1], &timeout_tx);
2895 check_added_monitors!(nodes[1], 1);
2896 check_closed_broadcast!(nodes[1], true);
2898 // B will rebroadcast a fee-bumped timeout transaction here.
2899 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2900 assert_eq!(node_txn.len(), 1);
2901 check_spends!(node_txn[0], commitment_tx[0]);
2904 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2906 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2907 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2908 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2909 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2910 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2911 if node_txn.len() == 1 {
2912 check_spends!(node_txn[0], chan_2.3);
2914 assert_eq!(node_txn.len(), 0);
2918 expect_pending_htlcs_forwardable!(nodes[1]);
2919 check_added_monitors!(nodes[1], 1);
2920 let events = nodes[1].node.get_and_clear_pending_msg_events();
2921 assert_eq!(events.len(), 1);
2923 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2924 assert!(update_add_htlcs.is_empty());
2925 assert!(!update_fail_htlcs.is_empty());
2926 assert!(update_fulfill_htlcs.is_empty());
2927 assert!(update_fail_malformed_htlcs.is_empty());
2928 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2930 _ => panic!("Unexpected event"),
2933 // Broadcast legit commitment tx from B on A's chain
2934 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2935 check_spends!(commitment_tx[0], chan_1.3);
2937 mine_transaction(&nodes[0], &commitment_tx[0]);
2938 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2940 check_closed_broadcast!(nodes[0], true);
2941 check_added_monitors!(nodes[0], 1);
2942 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2943 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2944 assert_eq!(node_txn.len(), 2);
2945 check_spends!(node_txn[0], chan_1.3);
2946 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2947 check_spends!(node_txn[1], commitment_tx[0]);
2948 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2952 fn test_htlc_on_chain_timeout() {
2953 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2954 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2955 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2959 fn test_simple_commitment_revoked_fail_backward() {
2960 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2961 // and fail backward accordingly.
2963 let chanmon_cfgs = create_chanmon_cfgs(3);
2964 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2965 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2966 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2968 // Create some initial channels
2969 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2970 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2972 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2973 // Get the will-be-revoked local txn from nodes[2]
2974 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2975 // Revoke the old state
2976 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2978 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2980 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2981 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2982 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2983 check_added_monitors!(nodes[1], 1);
2984 check_closed_broadcast!(nodes[1], true);
2986 expect_pending_htlcs_forwardable!(nodes[1]);
2987 check_added_monitors!(nodes[1], 1);
2988 let events = nodes[1].node.get_and_clear_pending_msg_events();
2989 assert_eq!(events.len(), 1);
2991 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
2992 assert!(update_add_htlcs.is_empty());
2993 assert_eq!(update_fail_htlcs.len(), 1);
2994 assert!(update_fulfill_htlcs.is_empty());
2995 assert!(update_fail_malformed_htlcs.is_empty());
2996 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2998 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2999 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3000 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3002 _ => panic!("Unexpected event"),
3006 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3007 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3008 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3009 // commitment transaction anymore.
3010 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3011 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3012 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3013 // technically disallowed and we should probably handle it reasonably.
3014 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3015 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3017 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3018 // commitment_signed (implying it will be in the latest remote commitment transaction).
3019 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3020 // and once they revoke the previous commitment transaction (allowing us to send a new
3021 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3022 let chanmon_cfgs = create_chanmon_cfgs(3);
3023 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3024 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3025 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3027 // Create some initial channels
3028 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3031 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3032 // Get the will-be-revoked local txn from nodes[2]
3033 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3034 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3035 // Revoke the old state
3036 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3038 let value = if use_dust {
3039 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3040 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3041 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3044 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3045 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3046 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3048 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3049 expect_pending_htlcs_forwardable!(nodes[2]);
3050 check_added_monitors!(nodes[2], 1);
3051 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3052 assert!(updates.update_add_htlcs.is_empty());
3053 assert!(updates.update_fulfill_htlcs.is_empty());
3054 assert!(updates.update_fail_malformed_htlcs.is_empty());
3055 assert_eq!(updates.update_fail_htlcs.len(), 1);
3056 assert!(updates.update_fee.is_none());
3057 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3058 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3059 // Drop the last RAA from 3 -> 2
3061 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3062 expect_pending_htlcs_forwardable!(nodes[2]);
3063 check_added_monitors!(nodes[2], 1);
3064 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3065 assert!(updates.update_add_htlcs.is_empty());
3066 assert!(updates.update_fulfill_htlcs.is_empty());
3067 assert!(updates.update_fail_malformed_htlcs.is_empty());
3068 assert_eq!(updates.update_fail_htlcs.len(), 1);
3069 assert!(updates.update_fee.is_none());
3070 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3071 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3072 check_added_monitors!(nodes[1], 1);
3073 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3074 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3075 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3076 check_added_monitors!(nodes[2], 1);
3078 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3079 expect_pending_htlcs_forwardable!(nodes[2]);
3080 check_added_monitors!(nodes[2], 1);
3081 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3082 assert!(updates.update_add_htlcs.is_empty());
3083 assert!(updates.update_fulfill_htlcs.is_empty());
3084 assert!(updates.update_fail_malformed_htlcs.is_empty());
3085 assert_eq!(updates.update_fail_htlcs.len(), 1);
3086 assert!(updates.update_fee.is_none());
3087 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3088 // At this point first_payment_hash has dropped out of the latest two commitment
3089 // transactions that nodes[1] is tracking...
3090 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3091 check_added_monitors!(nodes[1], 1);
3092 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3093 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3094 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3095 check_added_monitors!(nodes[2], 1);
3097 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3098 // on nodes[2]'s RAA.
3099 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3100 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3101 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3102 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3103 check_added_monitors!(nodes[1], 0);
3106 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3107 // One monitor for the new revocation preimage, no second on as we won't generate a new
3108 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3109 check_added_monitors!(nodes[1], 1);
3110 let events = nodes[1].node.get_and_clear_pending_events();
3111 assert_eq!(events.len(), 1);
3113 Event::PendingHTLCsForwardable { .. } => { },
3114 _ => panic!("Unexpected event"),
3116 // Deliberately don't process the pending fail-back so they all fail back at once after
3117 // block connection just like the !deliver_bs_raa case
3120 let mut failed_htlcs = HashSet::new();
3121 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3123 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3124 check_added_monitors!(nodes[1], 1);
3125 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3126 assert!(ANTI_REORG_DELAY > PAYMENT_EXPIRY_BLOCKS); // We assume payments will also expire
3128 let events = nodes[1].node.get_and_clear_pending_events();
3129 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 4 });
3131 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3132 _ => panic!("Unexepected event"),
3135 Event::PaymentPathFailed { ref payment_hash, .. } => {
3136 assert_eq!(*payment_hash, fourth_payment_hash);
3138 _ => panic!("Unexpected event"),
3140 if !deliver_bs_raa {
3142 Event::PaymentFailed { ref payment_hash, .. } => {
3143 assert_eq!(*payment_hash, fourth_payment_hash);
3145 _ => panic!("Unexpected event"),
3148 Event::PendingHTLCsForwardable { .. } => { },
3149 _ => panic!("Unexpected event"),
3152 nodes[1].node.process_pending_htlc_forwards();
3153 check_added_monitors!(nodes[1], 1);
3155 let events = nodes[1].node.get_and_clear_pending_msg_events();
3156 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3157 match events[if deliver_bs_raa { 1 } else { 0 }] {
3158 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3159 _ => panic!("Unexpected event"),
3161 match events[if deliver_bs_raa { 2 } else { 1 }] {
3162 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3163 assert_eq!(channel_id, chan_2.2);
3164 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3166 _ => panic!("Unexpected event"),
3170 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3171 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3172 assert_eq!(update_add_htlcs.len(), 1);
3173 assert!(update_fulfill_htlcs.is_empty());
3174 assert!(update_fail_htlcs.is_empty());
3175 assert!(update_fail_malformed_htlcs.is_empty());
3177 _ => panic!("Unexpected event"),
3180 match events[if deliver_bs_raa { 3 } else { 2 }] {
3181 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3182 assert!(update_add_htlcs.is_empty());
3183 assert_eq!(update_fail_htlcs.len(), 3);
3184 assert!(update_fulfill_htlcs.is_empty());
3185 assert!(update_fail_malformed_htlcs.is_empty());
3186 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3188 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3189 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3190 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3192 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3194 let events = nodes[0].node.get_and_clear_pending_events();
3195 assert_eq!(events.len(), 3);
3197 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3198 assert!(failed_htlcs.insert(payment_hash.0));
3199 // If we delivered B's RAA we got an unknown preimage error, not something
3200 // that we should update our routing table for.
3201 if !deliver_bs_raa {
3202 assert!(network_update.is_some());
3205 _ => panic!("Unexpected event"),
3208 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3209 assert!(failed_htlcs.insert(payment_hash.0));
3210 assert!(network_update.is_some());
3212 _ => panic!("Unexpected event"),
3215 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3216 assert!(failed_htlcs.insert(payment_hash.0));
3217 assert!(network_update.is_some());
3219 _ => panic!("Unexpected event"),
3222 _ => panic!("Unexpected event"),
3225 assert!(failed_htlcs.contains(&first_payment_hash.0));
3226 assert!(failed_htlcs.contains(&second_payment_hash.0));
3227 assert!(failed_htlcs.contains(&third_payment_hash.0));
3231 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3232 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3233 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3234 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3235 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3239 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3240 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3241 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3242 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3243 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3247 fn fail_backward_pending_htlc_upon_channel_failure() {
3248 let chanmon_cfgs = create_chanmon_cfgs(2);
3249 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3250 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3251 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3252 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3254 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3256 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3257 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3258 check_added_monitors!(nodes[0], 1);
3260 let payment_event = {
3261 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3262 assert_eq!(events.len(), 1);
3263 SendEvent::from_event(events.remove(0))
3265 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3266 assert_eq!(payment_event.msgs.len(), 1);
3269 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3270 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3272 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3273 check_added_monitors!(nodes[0], 0);
3275 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3278 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3280 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3282 let secp_ctx = Secp256k1::new();
3283 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3284 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3285 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3286 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3287 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3289 // Send a 0-msat update_add_htlc to fail the channel.
3290 let update_add_htlc = msgs::UpdateAddHTLC {
3296 onion_routing_packet,
3298 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3300 let events = nodes[0].node.get_and_clear_pending_events();
3301 assert_eq!(events.len(), 2);
3302 // Check that Alice fails backward the pending HTLC from the second payment.
3304 Event::PaymentPathFailed { payment_hash, .. } => {
3305 assert_eq!(payment_hash, failed_payment_hash);
3307 _ => panic!("Unexpected event"),
3310 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3311 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3313 _ => panic!("Unexpected event {:?}", events[1]),
3315 check_closed_broadcast!(nodes[0], true);
3316 check_added_monitors!(nodes[0], 1);
3320 fn test_htlc_ignore_latest_remote_commitment() {
3321 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3322 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3323 let chanmon_cfgs = create_chanmon_cfgs(2);
3324 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3325 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3326 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3327 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3329 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3330 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3331 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3332 check_closed_broadcast!(nodes[0], true);
3333 check_added_monitors!(nodes[0], 1);
3334 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3336 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3337 assert_eq!(node_txn.len(), 3);
3338 assert_eq!(node_txn[0], node_txn[1]);
3340 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3341 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3342 check_closed_broadcast!(nodes[1], true);
3343 check_added_monitors!(nodes[1], 1);
3344 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3346 // Duplicate the connect_block call since this may happen due to other listeners
3347 // registering new transactions
3348 header.prev_blockhash = header.block_hash();
3349 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3353 fn test_force_close_fail_back() {
3354 // Check which HTLCs are failed-backwards on channel force-closure
3355 let chanmon_cfgs = create_chanmon_cfgs(3);
3356 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3357 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3358 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3359 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3360 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3362 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3364 let mut payment_event = {
3365 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3366 check_added_monitors!(nodes[0], 1);
3368 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3369 assert_eq!(events.len(), 1);
3370 SendEvent::from_event(events.remove(0))
3373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3374 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3376 expect_pending_htlcs_forwardable!(nodes[1]);
3378 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3379 assert_eq!(events_2.len(), 1);
3380 payment_event = SendEvent::from_event(events_2.remove(0));
3381 assert_eq!(payment_event.msgs.len(), 1);
3383 check_added_monitors!(nodes[1], 1);
3384 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3385 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3386 check_added_monitors!(nodes[2], 1);
3387 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3389 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3390 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3391 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3393 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3394 check_closed_broadcast!(nodes[2], true);
3395 check_added_monitors!(nodes[2], 1);
3396 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3398 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3399 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3400 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3401 // back to nodes[1] upon timeout otherwise.
3402 assert_eq!(node_txn.len(), 1);
3406 mine_transaction(&nodes[1], &tx);
3408 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3409 check_closed_broadcast!(nodes[1], true);
3410 check_added_monitors!(nodes[1], 1);
3411 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3413 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3415 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3416 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3418 mine_transaction(&nodes[2], &tx);
3419 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3420 assert_eq!(node_txn.len(), 1);
3421 assert_eq!(node_txn[0].input.len(), 1);
3422 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3423 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3424 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3426 check_spends!(node_txn[0], tx);
3430 fn test_dup_events_on_peer_disconnect() {
3431 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3432 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3433 // as we used to generate the event immediately upon receipt of the payment preimage in the
3434 // update_fulfill_htlc message.
3436 let chanmon_cfgs = create_chanmon_cfgs(2);
3437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3439 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3440 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3442 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3444 assert!(nodes[1].node.claim_funds(payment_preimage));
3445 check_added_monitors!(nodes[1], 1);
3446 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3447 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3448 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3450 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3451 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3453 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3454 expect_payment_path_successful!(nodes[0]);
3458 fn test_simple_peer_disconnect() {
3459 // Test that we can reconnect when there are no lost messages
3460 let chanmon_cfgs = create_chanmon_cfgs(3);
3461 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3462 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3463 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3464 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3465 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3467 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3468 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3469 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3471 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3472 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3473 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3474 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3476 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3477 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3478 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3480 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3481 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3482 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3483 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3485 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3486 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3488 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3489 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3491 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3493 let events = nodes[0].node.get_and_clear_pending_events();
3494 assert_eq!(events.len(), 3);
3496 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3497 assert_eq!(payment_preimage, payment_preimage_3);
3498 assert_eq!(payment_hash, payment_hash_3);
3500 _ => panic!("Unexpected event"),
3503 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3504 assert_eq!(payment_hash, payment_hash_5);
3505 assert!(rejected_by_dest);
3507 _ => panic!("Unexpected event"),
3510 Event::PaymentPathSuccessful { .. } => {},
3511 _ => panic!("Unexpected event"),
3515 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3516 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3519 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3520 // Test that we can reconnect when in-flight HTLC updates get dropped
3521 let chanmon_cfgs = create_chanmon_cfgs(2);
3522 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526 let mut as_funding_locked = None;
3527 if messages_delivered == 0 {
3528 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3529 as_funding_locked = Some(funding_locked);
3530 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3531 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3532 // it before the channel_reestablish message.
3534 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3537 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3539 let payment_event = {
3540 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3541 check_added_monitors!(nodes[0], 1);
3543 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3544 assert_eq!(events.len(), 1);
3545 SendEvent::from_event(events.remove(0))
3547 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3549 if messages_delivered < 2 {
3550 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3552 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3553 if messages_delivered >= 3 {
3554 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3555 check_added_monitors!(nodes[1], 1);
3556 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3558 if messages_delivered >= 4 {
3559 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3561 check_added_monitors!(nodes[0], 1);
3563 if messages_delivered >= 5 {
3564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3565 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3566 // No commitment_signed so get_event_msg's assert(len == 1) passes
3567 check_added_monitors!(nodes[0], 1);
3569 if messages_delivered >= 6 {
3570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3571 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3572 check_added_monitors!(nodes[1], 1);
3579 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3580 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3581 if messages_delivered < 3 {
3582 if simulate_broken_lnd {
3583 // lnd has a long-standing bug where they send a funding_locked prior to a
3584 // channel_reestablish if you reconnect prior to funding_locked time.
3586 // Here we simulate that behavior, delivering a funding_locked immediately on
3587 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3588 // in `reconnect_nodes` but we currently don't fail based on that.
3590 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3591 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3593 // Even if the funding_locked messages get exchanged, as long as nothing further was
3594 // received on either side, both sides will need to resend them.
3595 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596 } else if messages_delivered == 3 {
3597 // nodes[0] still wants its RAA + commitment_signed
3598 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3599 } else if messages_delivered == 4 {
3600 // nodes[0] still wants its commitment_signed
3601 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3602 } else if messages_delivered == 5 {
3603 // nodes[1] still wants its final RAA
3604 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3605 } else if messages_delivered == 6 {
3606 // Everything was delivered...
3607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3610 let events_1 = nodes[1].node.get_and_clear_pending_events();
3611 assert_eq!(events_1.len(), 1);
3613 Event::PendingHTLCsForwardable { .. } => { },
3614 _ => panic!("Unexpected event"),
3617 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3618 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3619 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3621 nodes[1].node.process_pending_htlc_forwards();
3623 let events_2 = nodes[1].node.get_and_clear_pending_events();
3624 assert_eq!(events_2.len(), 1);
3626 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3627 assert_eq!(payment_hash_1, *payment_hash);
3628 assert_eq!(amt, 1000000);
3630 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3631 assert!(payment_preimage.is_none());
3632 assert_eq!(payment_secret_1, *payment_secret);
3634 _ => panic!("expected PaymentPurpose::InvoicePayment")
3637 _ => panic!("Unexpected event"),
3640 nodes[1].node.claim_funds(payment_preimage_1);
3641 check_added_monitors!(nodes[1], 1);
3643 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3644 assert_eq!(events_3.len(), 1);
3645 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3646 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3647 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3648 assert!(updates.update_add_htlcs.is_empty());
3649 assert!(updates.update_fail_htlcs.is_empty());
3650 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3651 assert!(updates.update_fail_malformed_htlcs.is_empty());
3652 assert!(updates.update_fee.is_none());
3653 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3655 _ => panic!("Unexpected event"),
3658 if messages_delivered >= 1 {
3659 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3661 let events_4 = nodes[0].node.get_and_clear_pending_events();
3662 assert_eq!(events_4.len(), 1);
3664 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3665 assert_eq!(payment_preimage_1, *payment_preimage);
3666 assert_eq!(payment_hash_1, *payment_hash);
3668 _ => panic!("Unexpected event"),
3671 if messages_delivered >= 2 {
3672 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3673 check_added_monitors!(nodes[0], 1);
3674 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3676 if messages_delivered >= 3 {
3677 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3678 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3679 check_added_monitors!(nodes[1], 1);
3681 if messages_delivered >= 4 {
3682 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3683 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3684 // No commitment_signed so get_event_msg's assert(len == 1) passes
3685 check_added_monitors!(nodes[1], 1);
3687 if messages_delivered >= 5 {
3688 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3689 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3690 check_added_monitors!(nodes[0], 1);
3697 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3698 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3699 if messages_delivered < 2 {
3700 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701 if messages_delivered < 1 {
3702 expect_payment_sent!(nodes[0], payment_preimage_1);
3704 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3706 } else if messages_delivered == 2 {
3707 // nodes[0] still wants its RAA + commitment_signed
3708 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3709 } else if messages_delivered == 3 {
3710 // nodes[0] still wants its commitment_signed
3711 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3712 } else if messages_delivered == 4 {
3713 // nodes[1] still wants its final RAA
3714 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3715 } else if messages_delivered == 5 {
3716 // Everything was delivered...
3717 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720 if messages_delivered == 1 || messages_delivered == 2 {
3721 expect_payment_path_successful!(nodes[0]);
3724 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3725 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3726 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728 if messages_delivered > 2 {
3729 expect_payment_path_successful!(nodes[0]);
3732 // Channel should still work fine...
3733 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3734 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3735 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3739 fn test_drop_messages_peer_disconnect_a() {
3740 do_test_drop_messages_peer_disconnect(0, true);
3741 do_test_drop_messages_peer_disconnect(0, false);
3742 do_test_drop_messages_peer_disconnect(1, false);
3743 do_test_drop_messages_peer_disconnect(2, false);
3747 fn test_drop_messages_peer_disconnect_b() {
3748 do_test_drop_messages_peer_disconnect(3, false);
3749 do_test_drop_messages_peer_disconnect(4, false);
3750 do_test_drop_messages_peer_disconnect(5, false);
3751 do_test_drop_messages_peer_disconnect(6, false);
3755 fn test_funding_peer_disconnect() {
3756 // Test that we can lock in our funding tx while disconnected
3757 let chanmon_cfgs = create_chanmon_cfgs(2);
3758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3760 let persister: test_utils::TestPersister;
3761 let new_chain_monitor: test_utils::TestChainMonitor;
3762 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3764 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3766 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3767 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3769 confirm_transaction(&nodes[0], &tx);
3770 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3771 assert!(events_1.is_empty());
3773 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3775 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3776 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3778 confirm_transaction(&nodes[1], &tx);
3779 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3780 assert!(events_2.is_empty());
3782 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3783 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
3784 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3785 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3787 // nodes[0] hasn't yet received a funding_locked, so it only sends that on reconnect.
3788 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
3789 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3790 assert_eq!(events_3.len(), 1);
3791 let as_funding_locked = match events_3[0] {
3792 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3793 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3796 _ => panic!("Unexpected event {:?}", events_3[0]),
3799 // nodes[1] received nodes[0]'s funding_locked on the first reconnect above, so it should send
3800 // announcement_signatures as well as channel_update.
3801 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
3802 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3803 assert_eq!(events_4.len(), 3);
3805 let bs_funding_locked = match events_4[0] {
3806 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3807 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3808 chan_id = msg.channel_id;
3811 _ => panic!("Unexpected event {:?}", events_4[0]),
3813 let bs_announcement_sigs = match events_4[1] {
3814 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3815 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3818 _ => panic!("Unexpected event {:?}", events_4[1]),
3821 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3822 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3824 _ => panic!("Unexpected event {:?}", events_4[2]),
3827 // Re-deliver nodes[0]'s funding_locked, which nodes[1] can safely ignore. It currently
3828 // generates a duplicative private channel_update
3829 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked);
3830 let events_5 = nodes[1].node.get_and_clear_pending_msg_events();
3831 assert_eq!(events_5.len(), 1);
3833 MessageSendEvent::SendChannelUpdate { ref node_id, msg: _ } => {
3834 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3836 _ => panic!("Unexpected event {:?}", events_5[0]),
3839 // When we deliver nodes[1]'s funding_locked, however, nodes[0] will generate its
3840 // announcement_signatures.
3841 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &bs_funding_locked);
3842 let events_6 = nodes[0].node.get_and_clear_pending_msg_events();
3843 assert_eq!(events_6.len(), 1);
3844 let as_announcement_sigs = match events_6[0] {
3845 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3846 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3849 _ => panic!("Unexpected event {:?}", events_6[0]),
3852 // When we deliver nodes[1]'s announcement_signatures to nodes[0], nodes[0] should immediately
3853 // broadcast the channel announcement globally, as well as re-send its (now-public)
3855 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3856 let events_7 = nodes[0].node.get_and_clear_pending_msg_events();
3857 assert_eq!(events_7.len(), 1);
3858 let (chan_announcement, as_update) = match events_7[0] {
3859 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3860 (msg.clone(), update_msg.clone())
3862 _ => panic!("Unexpected event {:?}", events_7[0]),
3865 // Finally, deliver nodes[0]'s announcement_signatures to nodes[1] and make sure it creates the
3866 // same channel_announcement.
3867 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3868 let events_8 = nodes[1].node.get_and_clear_pending_msg_events();
3869 assert_eq!(events_8.len(), 1);
3870 let bs_update = match events_8[0] {
3871 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3872 assert_eq!(*msg, chan_announcement);
3875 _ => panic!("Unexpected event {:?}", events_8[0]),
3878 // Provide the channel announcement and public updates to the network graph
3879 nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap();
3880 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3881 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3883 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3884 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3885 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3887 // Check that after deserialization and reconnection we can still generate an identical
3888 // channel_announcement from the cached signatures.
3889 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3891 let nodes_0_serialized = nodes[0].node.encode();
3892 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3893 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3895 persister = test_utils::TestPersister::new();
3896 let keys_manager = &chanmon_cfgs[0].keys_manager;
3897 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
3898 nodes[0].chain_monitor = &new_chain_monitor;
3899 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3900 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3901 &mut chan_0_monitor_read, keys_manager).unwrap();
3902 assert!(chan_0_monitor_read.is_empty());
3904 let mut nodes_0_read = &nodes_0_serialized[..];
3905 let (_, nodes_0_deserialized_tmp) = {
3906 let mut channel_monitors = HashMap::new();
3907 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3908 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3909 default_config: UserConfig::default(),
3911 fee_estimator: node_cfgs[0].fee_estimator,
3912 chain_monitor: nodes[0].chain_monitor,
3913 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3914 logger: nodes[0].logger,
3918 nodes_0_deserialized = nodes_0_deserialized_tmp;
3919 assert!(nodes_0_read.is_empty());
3921 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3922 nodes[0].node = &nodes_0_deserialized;
3923 check_added_monitors!(nodes[0], 1);
3925 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3927 // The channel announcement should be re-generated exactly by broadcast_node_announcement.
3928 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3929 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3930 let mut found_announcement = false;
3931 for event in msgs.iter() {
3933 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3934 if *msg == chan_announcement { found_announcement = true; }
3936 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3937 _ => panic!("Unexpected event"),
3940 assert!(found_announcement);
3944 fn test_drop_messages_peer_disconnect_dual_htlc() {
3945 // Test that we can handle reconnecting when both sides of a channel have pending
3946 // commitment_updates when we disconnect.
3947 let chanmon_cfgs = create_chanmon_cfgs(2);
3948 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3949 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3950 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3951 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3953 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3955 // Now try to send a second payment which will fail to send
3956 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3957 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3958 check_added_monitors!(nodes[0], 1);
3960 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3961 assert_eq!(events_1.len(), 1);
3963 MessageSendEvent::UpdateHTLCs { .. } => {},
3964 _ => panic!("Unexpected event"),
3967 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3968 check_added_monitors!(nodes[1], 1);
3970 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3971 assert_eq!(events_2.len(), 1);
3973 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 } } => {
3974 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3975 assert!(update_add_htlcs.is_empty());
3976 assert_eq!(update_fulfill_htlcs.len(), 1);
3977 assert!(update_fail_htlcs.is_empty());
3978 assert!(update_fail_malformed_htlcs.is_empty());
3979 assert!(update_fee.is_none());
3981 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3982 let events_3 = nodes[0].node.get_and_clear_pending_events();
3983 assert_eq!(events_3.len(), 1);
3985 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3986 assert_eq!(*payment_preimage, payment_preimage_1);
3987 assert_eq!(*payment_hash, payment_hash_1);
3989 _ => panic!("Unexpected event"),
3992 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3993 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3994 // No commitment_signed so get_event_msg's assert(len == 1) passes
3995 check_added_monitors!(nodes[0], 1);
3997 _ => panic!("Unexpected event"),
4000 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4001 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4003 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4004 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4005 assert_eq!(reestablish_1.len(), 1);
4006 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4007 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4008 assert_eq!(reestablish_2.len(), 1);
4010 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4011 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4012 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4013 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4015 assert!(as_resp.0.is_none());
4016 assert!(bs_resp.0.is_none());
4018 assert!(bs_resp.1.is_none());
4019 assert!(bs_resp.2.is_none());
4021 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4023 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4024 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4025 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4026 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4027 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4028 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4029 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4030 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4031 // No commitment_signed so get_event_msg's assert(len == 1) passes
4032 check_added_monitors!(nodes[1], 1);
4034 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4035 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4036 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4037 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4038 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4039 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4040 assert!(bs_second_commitment_signed.update_fee.is_none());
4041 check_added_monitors!(nodes[1], 1);
4043 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4044 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4045 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4046 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4047 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4048 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4049 assert!(as_commitment_signed.update_fee.is_none());
4050 check_added_monitors!(nodes[0], 1);
4052 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4053 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4054 // No commitment_signed so get_event_msg's assert(len == 1) passes
4055 check_added_monitors!(nodes[0], 1);
4057 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4058 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4059 // No commitment_signed so get_event_msg's assert(len == 1) passes
4060 check_added_monitors!(nodes[1], 1);
4062 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4063 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4064 check_added_monitors!(nodes[1], 1);
4066 expect_pending_htlcs_forwardable!(nodes[1]);
4068 let events_5 = nodes[1].node.get_and_clear_pending_events();
4069 assert_eq!(events_5.len(), 1);
4071 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
4072 assert_eq!(payment_hash_2, *payment_hash);
4074 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4075 assert!(payment_preimage.is_none());
4076 assert_eq!(payment_secret_2, *payment_secret);
4078 _ => panic!("expected PaymentPurpose::InvoicePayment")
4081 _ => panic!("Unexpected event"),
4084 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4085 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4086 check_added_monitors!(nodes[0], 1);
4088 expect_payment_path_successful!(nodes[0]);
4089 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4092 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4093 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4094 // to avoid our counterparty failing the channel.
4095 let chanmon_cfgs = create_chanmon_cfgs(2);
4096 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4097 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4098 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4100 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4102 let our_payment_hash = if send_partial_mpp {
4103 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4104 // Use the utility function send_payment_along_path to send the payment with MPP data which
4105 // indicates there are more HTLCs coming.
4106 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.
4107 let payment_id = PaymentId([42; 32]);
4108 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();
4109 check_added_monitors!(nodes[0], 1);
4110 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4111 assert_eq!(events.len(), 1);
4112 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4113 // hop should *not* yet generate any PaymentReceived event(s).
4114 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4117 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4120 let mut block = Block {
4121 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4124 connect_block(&nodes[0], &block);
4125 connect_block(&nodes[1], &block);
4126 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4127 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4128 block.header.prev_blockhash = block.block_hash();
4129 connect_block(&nodes[0], &block);
4130 connect_block(&nodes[1], &block);
4133 expect_pending_htlcs_forwardable!(nodes[1]);
4135 check_added_monitors!(nodes[1], 1);
4136 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4137 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4138 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4139 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4140 assert!(htlc_timeout_updates.update_fee.is_none());
4142 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4143 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4144 // 100_000 msat as u64, followed by the height at which we failed back above
4145 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4146 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4147 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4151 fn test_htlc_timeout() {
4152 do_test_htlc_timeout(true);
4153 do_test_htlc_timeout(false);
4156 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4157 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4158 let chanmon_cfgs = create_chanmon_cfgs(3);
4159 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4160 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4161 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4162 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4163 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4165 // Make sure all nodes are at the same starting height
4166 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4167 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4168 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4170 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4171 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4173 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4175 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4176 check_added_monitors!(nodes[1], 1);
4178 // Now attempt to route a second payment, which should be placed in the holding cell
4179 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4180 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4181 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4183 check_added_monitors!(nodes[0], 1);
4184 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4185 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4186 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4187 expect_pending_htlcs_forwardable!(nodes[1]);
4189 check_added_monitors!(nodes[1], 0);
4191 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4192 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4193 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4194 connect_blocks(&nodes[1], 1);
4197 expect_pending_htlcs_forwardable!(nodes[1]);
4198 check_added_monitors!(nodes[1], 1);
4199 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4200 assert_eq!(fail_commit.len(), 1);
4201 match fail_commit[0] {
4202 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4203 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4204 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4206 _ => unreachable!(),
4208 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4210 let events = nodes[1].node.get_and_clear_pending_events();
4211 assert_eq!(events.len(), 2);
4212 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
4213 assert_eq!(*payment_hash, second_payment_hash);
4214 } else { panic!("Unexpected event"); }
4215 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
4216 assert_eq!(*payment_hash, second_payment_hash);
4217 } else { panic!("Unexpected event"); }
4222 fn test_holding_cell_htlc_add_timeouts() {
4223 do_test_holding_cell_htlc_add_timeouts(false);
4224 do_test_holding_cell_htlc_add_timeouts(true);
4228 fn test_no_txn_manager_serialize_deserialize() {
4229 let chanmon_cfgs = create_chanmon_cfgs(2);
4230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4232 let logger: test_utils::TestLogger;
4233 let fee_estimator: test_utils::TestFeeEstimator;
4234 let persister: test_utils::TestPersister;
4235 let new_chain_monitor: test_utils::TestChainMonitor;
4236 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4237 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4239 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4241 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4243 let nodes_0_serialized = nodes[0].node.encode();
4244 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4245 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4246 .write(&mut chan_0_monitor_serialized).unwrap();
4248 logger = test_utils::TestLogger::new();
4249 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4250 persister = test_utils::TestPersister::new();
4251 let keys_manager = &chanmon_cfgs[0].keys_manager;
4252 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4253 nodes[0].chain_monitor = &new_chain_monitor;
4254 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4255 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4256 &mut chan_0_monitor_read, keys_manager).unwrap();
4257 assert!(chan_0_monitor_read.is_empty());
4259 let mut nodes_0_read = &nodes_0_serialized[..];
4260 let config = UserConfig::default();
4261 let (_, nodes_0_deserialized_tmp) = {
4262 let mut channel_monitors = HashMap::new();
4263 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4264 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4265 default_config: config,
4267 fee_estimator: &fee_estimator,
4268 chain_monitor: nodes[0].chain_monitor,
4269 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4274 nodes_0_deserialized = nodes_0_deserialized_tmp;
4275 assert!(nodes_0_read.is_empty());
4277 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4278 nodes[0].node = &nodes_0_deserialized;
4279 assert_eq!(nodes[0].node.list_channels().len(), 1);
4280 check_added_monitors!(nodes[0], 1);
4282 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4283 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4284 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4285 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4287 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4288 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4289 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4290 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4292 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4293 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4294 for node in nodes.iter() {
4295 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4296 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4297 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4300 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4304 fn test_manager_serialize_deserialize_events() {
4305 // This test makes sure the events field in ChannelManager survives de/serialization
4306 let chanmon_cfgs = create_chanmon_cfgs(2);
4307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4309 let fee_estimator: test_utils::TestFeeEstimator;
4310 let persister: test_utils::TestPersister;
4311 let logger: test_utils::TestLogger;
4312 let new_chain_monitor: test_utils::TestChainMonitor;
4313 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4314 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4316 // Start creating a channel, but stop right before broadcasting the funding transaction
4317 let channel_value = 100000;
4318 let push_msat = 10001;
4319 let a_flags = InitFeatures::known();
4320 let b_flags = InitFeatures::known();
4321 let node_a = nodes.remove(0);
4322 let node_b = nodes.remove(0);
4323 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4324 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()));
4325 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()));
4327 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4329 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4330 check_added_monitors!(node_a, 0);
4332 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()));
4334 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4335 assert_eq!(added_monitors.len(), 1);
4336 assert_eq!(added_monitors[0].0, funding_output);
4337 added_monitors.clear();
4340 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4341 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4343 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4344 assert_eq!(added_monitors.len(), 1);
4345 assert_eq!(added_monitors[0].0, funding_output);
4346 added_monitors.clear();
4348 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4353 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4354 let nodes_0_serialized = nodes[0].node.encode();
4355 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4356 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4358 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4359 logger = test_utils::TestLogger::new();
4360 persister = test_utils::TestPersister::new();
4361 let keys_manager = &chanmon_cfgs[0].keys_manager;
4362 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4363 nodes[0].chain_monitor = &new_chain_monitor;
4364 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4365 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4366 &mut chan_0_monitor_read, keys_manager).unwrap();
4367 assert!(chan_0_monitor_read.is_empty());
4369 let mut nodes_0_read = &nodes_0_serialized[..];
4370 let config = UserConfig::default();
4371 let (_, nodes_0_deserialized_tmp) = {
4372 let mut channel_monitors = HashMap::new();
4373 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4374 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4375 default_config: config,
4377 fee_estimator: &fee_estimator,
4378 chain_monitor: nodes[0].chain_monitor,
4379 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4384 nodes_0_deserialized = nodes_0_deserialized_tmp;
4385 assert!(nodes_0_read.is_empty());
4387 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4389 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4390 nodes[0].node = &nodes_0_deserialized;
4392 // After deserializing, make sure the funding_transaction is still held by the channel manager
4393 let events_4 = nodes[0].node.get_and_clear_pending_events();
4394 assert_eq!(events_4.len(), 0);
4395 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4396 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4398 // Make sure the channel is functioning as though the de/serialization never happened
4399 assert_eq!(nodes[0].node.list_channels().len(), 1);
4400 check_added_monitors!(nodes[0], 1);
4402 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4403 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4404 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4405 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4407 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4408 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4409 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4410 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4412 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4413 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4414 for node in nodes.iter() {
4415 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4416 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4417 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4420 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4424 fn test_simple_manager_serialize_deserialize() {
4425 let chanmon_cfgs = create_chanmon_cfgs(2);
4426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4428 let logger: test_utils::TestLogger;
4429 let fee_estimator: test_utils::TestFeeEstimator;
4430 let persister: test_utils::TestPersister;
4431 let new_chain_monitor: test_utils::TestChainMonitor;
4432 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4433 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4434 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4436 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4437 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4439 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4441 let nodes_0_serialized = nodes[0].node.encode();
4442 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4443 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4445 logger = test_utils::TestLogger::new();
4446 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4447 persister = test_utils::TestPersister::new();
4448 let keys_manager = &chanmon_cfgs[0].keys_manager;
4449 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4450 nodes[0].chain_monitor = &new_chain_monitor;
4451 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4452 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4453 &mut chan_0_monitor_read, keys_manager).unwrap();
4454 assert!(chan_0_monitor_read.is_empty());
4456 let mut nodes_0_read = &nodes_0_serialized[..];
4457 let (_, nodes_0_deserialized_tmp) = {
4458 let mut channel_monitors = HashMap::new();
4459 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4460 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4461 default_config: UserConfig::default(),
4463 fee_estimator: &fee_estimator,
4464 chain_monitor: nodes[0].chain_monitor,
4465 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4470 nodes_0_deserialized = nodes_0_deserialized_tmp;
4471 assert!(nodes_0_read.is_empty());
4473 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4474 nodes[0].node = &nodes_0_deserialized;
4475 check_added_monitors!(nodes[0], 1);
4477 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4479 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4480 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4484 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4485 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4486 let chanmon_cfgs = create_chanmon_cfgs(4);
4487 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4488 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4489 let logger: test_utils::TestLogger;
4490 let fee_estimator: test_utils::TestFeeEstimator;
4491 let persister: test_utils::TestPersister;
4492 let new_chain_monitor: test_utils::TestChainMonitor;
4493 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4494 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4495 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4496 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4497 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4499 let mut node_0_stale_monitors_serialized = Vec::new();
4500 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4501 let mut writer = test_utils::TestVecWriter(Vec::new());
4502 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4503 node_0_stale_monitors_serialized.push(writer.0);
4506 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4508 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4509 let nodes_0_serialized = nodes[0].node.encode();
4511 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4512 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4513 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4514 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4516 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4518 let mut node_0_monitors_serialized = Vec::new();
4519 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4520 let mut writer = test_utils::TestVecWriter(Vec::new());
4521 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4522 node_0_monitors_serialized.push(writer.0);
4525 logger = test_utils::TestLogger::new();
4526 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4527 persister = test_utils::TestPersister::new();
4528 let keys_manager = &chanmon_cfgs[0].keys_manager;
4529 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4530 nodes[0].chain_monitor = &new_chain_monitor;
4533 let mut node_0_stale_monitors = Vec::new();
4534 for serialized in node_0_stale_monitors_serialized.iter() {
4535 let mut read = &serialized[..];
4536 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4537 assert!(read.is_empty());
4538 node_0_stale_monitors.push(monitor);
4541 let mut node_0_monitors = Vec::new();
4542 for serialized in node_0_monitors_serialized.iter() {
4543 let mut read = &serialized[..];
4544 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4545 assert!(read.is_empty());
4546 node_0_monitors.push(monitor);
4549 let mut nodes_0_read = &nodes_0_serialized[..];
4550 if let Err(msgs::DecodeError::InvalidValue) =
4551 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4552 default_config: UserConfig::default(),
4554 fee_estimator: &fee_estimator,
4555 chain_monitor: nodes[0].chain_monitor,
4556 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4558 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4560 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4563 let mut nodes_0_read = &nodes_0_serialized[..];
4564 let (_, nodes_0_deserialized_tmp) =
4565 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4566 default_config: UserConfig::default(),
4568 fee_estimator: &fee_estimator,
4569 chain_monitor: nodes[0].chain_monitor,
4570 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4572 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4574 nodes_0_deserialized = nodes_0_deserialized_tmp;
4575 assert!(nodes_0_read.is_empty());
4577 { // Channel close should result in a commitment tx
4578 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4579 assert_eq!(txn.len(), 1);
4580 check_spends!(txn[0], funding_tx);
4581 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4584 for monitor in node_0_monitors.drain(..) {
4585 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4586 check_added_monitors!(nodes[0], 1);
4588 nodes[0].node = &nodes_0_deserialized;
4589 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4591 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4593 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4594 //... and we can even still claim the payment!
4595 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4597 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4598 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4599 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4600 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4601 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4602 assert_eq!(msg_events.len(), 1);
4603 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4605 &ErrorAction::SendErrorMessage { ref msg } => {
4606 assert_eq!(msg.channel_id, channel_id);
4608 _ => panic!("Unexpected event!"),
4613 macro_rules! check_spendable_outputs {
4614 ($node: expr, $keysinterface: expr) => {
4616 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4617 let mut txn = Vec::new();
4618 let mut all_outputs = Vec::new();
4619 let secp_ctx = Secp256k1::new();
4620 for event in events.drain(..) {
4622 Event::SpendableOutputs { mut outputs } => {
4623 for outp in outputs.drain(..) {
4624 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4625 all_outputs.push(outp);
4628 _ => panic!("Unexpected event"),
4631 if all_outputs.len() > 1 {
4632 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) {
4642 fn test_claim_sizeable_push_msat() {
4643 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4644 let chanmon_cfgs = create_chanmon_cfgs(2);
4645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4649 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4650 nodes[1].node.force_close_channel(&chan.2).unwrap();
4651 check_closed_broadcast!(nodes[1], true);
4652 check_added_monitors!(nodes[1], 1);
4653 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4654 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4655 assert_eq!(node_txn.len(), 1);
4656 check_spends!(node_txn[0], chan.3);
4657 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
4659 mine_transaction(&nodes[1], &node_txn[0]);
4660 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4662 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4663 assert_eq!(spend_txn.len(), 1);
4664 assert_eq!(spend_txn[0].input.len(), 1);
4665 check_spends!(spend_txn[0], node_txn[0]);
4666 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4670 fn test_claim_on_remote_sizeable_push_msat() {
4671 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4672 // to_remote output is encumbered by a P2WPKH
4673 let chanmon_cfgs = create_chanmon_cfgs(2);
4674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4676 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4678 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4679 nodes[0].node.force_close_channel(&chan.2).unwrap();
4680 check_closed_broadcast!(nodes[0], true);
4681 check_added_monitors!(nodes[0], 1);
4682 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4684 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4685 assert_eq!(node_txn.len(), 1);
4686 check_spends!(node_txn[0], chan.3);
4687 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
4689 mine_transaction(&nodes[1], &node_txn[0]);
4690 check_closed_broadcast!(nodes[1], true);
4691 check_added_monitors!(nodes[1], 1);
4692 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4693 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4695 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4696 assert_eq!(spend_txn.len(), 1);
4697 check_spends!(spend_txn[0], node_txn[0]);
4701 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4702 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4703 // to_remote output is encumbered by a P2WPKH
4705 let chanmon_cfgs = create_chanmon_cfgs(2);
4706 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4707 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4708 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4710 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4711 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4712 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4713 assert_eq!(revoked_local_txn[0].input.len(), 1);
4714 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4716 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4717 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4718 check_closed_broadcast!(nodes[1], true);
4719 check_added_monitors!(nodes[1], 1);
4720 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4722 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4723 mine_transaction(&nodes[1], &node_txn[0]);
4724 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4726 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4727 assert_eq!(spend_txn.len(), 3);
4728 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4729 check_spends!(spend_txn[1], node_txn[0]);
4730 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4734 fn test_static_spendable_outputs_preimage_tx() {
4735 let chanmon_cfgs = create_chanmon_cfgs(2);
4736 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4737 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4738 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4740 // Create some initial channels
4741 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4743 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4745 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4746 assert_eq!(commitment_tx[0].input.len(), 1);
4747 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4749 // Settle A's commitment tx on B's chain
4750 assert!(nodes[1].node.claim_funds(payment_preimage));
4751 check_added_monitors!(nodes[1], 1);
4752 mine_transaction(&nodes[1], &commitment_tx[0]);
4753 check_added_monitors!(nodes[1], 1);
4754 let events = nodes[1].node.get_and_clear_pending_msg_events();
4756 MessageSendEvent::UpdateHTLCs { .. } => {},
4757 _ => panic!("Unexpected event"),
4760 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4761 _ => panic!("Unexepected event"),
4764 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4765 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4766 assert_eq!(node_txn.len(), 3);
4767 check_spends!(node_txn[0], commitment_tx[0]);
4768 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4769 check_spends!(node_txn[1], chan_1.3);
4770 check_spends!(node_txn[2], node_txn[1]);
4772 mine_transaction(&nodes[1], &node_txn[0]);
4773 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4774 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4776 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4777 assert_eq!(spend_txn.len(), 1);
4778 check_spends!(spend_txn[0], node_txn[0]);
4782 fn test_static_spendable_outputs_timeout_tx() {
4783 let chanmon_cfgs = create_chanmon_cfgs(2);
4784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4788 // Create some initial channels
4789 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4791 // Rebalance the network a bit by relaying one payment through all the channels ...
4792 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4794 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4796 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4797 assert_eq!(commitment_tx[0].input.len(), 1);
4798 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4800 // Settle A's commitment tx on B' chain
4801 mine_transaction(&nodes[1], &commitment_tx[0]);
4802 check_added_monitors!(nodes[1], 1);
4803 let events = nodes[1].node.get_and_clear_pending_msg_events();
4805 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4806 _ => panic!("Unexpected event"),
4808 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4810 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4811 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4812 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4813 check_spends!(node_txn[0], chan_1.3.clone());
4814 check_spends!(node_txn[1], commitment_tx[0].clone());
4815 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4817 mine_transaction(&nodes[1], &node_txn[1]);
4818 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4819 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4820 expect_payment_failed!(nodes[1], our_payment_hash, true);
4822 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4823 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4824 check_spends!(spend_txn[0], commitment_tx[0]);
4825 check_spends!(spend_txn[1], node_txn[1]);
4826 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4830 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4831 let chanmon_cfgs = create_chanmon_cfgs(2);
4832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4834 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4836 // Create some initial channels
4837 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4839 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4840 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4841 assert_eq!(revoked_local_txn[0].input.len(), 1);
4842 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4844 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4846 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4847 check_closed_broadcast!(nodes[1], true);
4848 check_added_monitors!(nodes[1], 1);
4849 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4851 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4852 assert_eq!(node_txn.len(), 2);
4853 assert_eq!(node_txn[0].input.len(), 2);
4854 check_spends!(node_txn[0], revoked_local_txn[0]);
4856 mine_transaction(&nodes[1], &node_txn[0]);
4857 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4859 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4860 assert_eq!(spend_txn.len(), 1);
4861 check_spends!(spend_txn[0], node_txn[0]);
4865 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4866 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4867 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4870 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4872 // Create some initial channels
4873 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4875 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4876 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4877 assert_eq!(revoked_local_txn[0].input.len(), 1);
4878 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4880 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4882 // A will generate HTLC-Timeout from revoked commitment tx
4883 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4884 check_closed_broadcast!(nodes[0], true);
4885 check_added_monitors!(nodes[0], 1);
4886 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4887 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4889 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4890 assert_eq!(revoked_htlc_txn.len(), 2);
4891 check_spends!(revoked_htlc_txn[0], chan_1.3);
4892 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4893 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4894 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4895 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4897 // B will generate justice tx from A's revoked commitment/HTLC tx
4898 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4899 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4900 check_closed_broadcast!(nodes[1], true);
4901 check_added_monitors!(nodes[1], 1);
4902 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4904 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4905 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4906 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4907 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4908 // transactions next...
4909 assert_eq!(node_txn[0].input.len(), 3);
4910 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4912 assert_eq!(node_txn[1].input.len(), 2);
4913 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4914 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4915 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4917 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4918 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4921 assert_eq!(node_txn[2].input.len(), 1);
4922 check_spends!(node_txn[2], chan_1.3);
4924 mine_transaction(&nodes[1], &node_txn[1]);
4925 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4927 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4928 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4929 assert_eq!(spend_txn.len(), 1);
4930 assert_eq!(spend_txn[0].input.len(), 1);
4931 check_spends!(spend_txn[0], node_txn[1]);
4935 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4936 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4937 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4938 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4939 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4940 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4942 // Create some initial channels
4943 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4945 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4946 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4947 assert_eq!(revoked_local_txn[0].input.len(), 1);
4948 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4950 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4951 assert_eq!(revoked_local_txn[0].output.len(), 2);
4953 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4955 // B will generate HTLC-Success from revoked commitment tx
4956 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4957 check_closed_broadcast!(nodes[1], true);
4958 check_added_monitors!(nodes[1], 1);
4959 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4960 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4962 assert_eq!(revoked_htlc_txn.len(), 2);
4963 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4964 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4965 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4967 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4968 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4969 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4971 // A will generate justice tx from B's revoked commitment/HTLC tx
4972 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4973 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4974 check_closed_broadcast!(nodes[0], true);
4975 check_added_monitors!(nodes[0], 1);
4976 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4978 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4979 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4981 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4982 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4983 // transactions next...
4984 assert_eq!(node_txn[0].input.len(), 2);
4985 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4986 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4987 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4989 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4990 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4993 assert_eq!(node_txn[1].input.len(), 1);
4994 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4996 check_spends!(node_txn[2], chan_1.3);
4998 mine_transaction(&nodes[0], &node_txn[1]);
4999 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5001 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5002 // didn't try to generate any new transactions.
5004 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5005 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5006 assert_eq!(spend_txn.len(), 3);
5007 assert_eq!(spend_txn[0].input.len(), 1);
5008 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5009 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5010 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5011 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5015 fn test_onchain_to_onchain_claim() {
5016 // Test that in case of channel closure, we detect the state of output and claim HTLC
5017 // on downstream peer's remote commitment tx.
5018 // First, have C claim an HTLC against its own latest commitment transaction.
5019 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5021 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5024 let chanmon_cfgs = create_chanmon_cfgs(3);
5025 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5026 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5027 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5029 // Create some initial channels
5030 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5031 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5033 // Ensure all nodes are at the same height
5034 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5035 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5036 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5037 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5039 // Rebalance the network a bit by relaying one payment through all the channels ...
5040 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5041 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5043 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5044 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5045 check_spends!(commitment_tx[0], chan_2.3);
5046 nodes[2].node.claim_funds(payment_preimage);
5047 check_added_monitors!(nodes[2], 1);
5048 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5049 assert!(updates.update_add_htlcs.is_empty());
5050 assert!(updates.update_fail_htlcs.is_empty());
5051 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5052 assert!(updates.update_fail_malformed_htlcs.is_empty());
5054 mine_transaction(&nodes[2], &commitment_tx[0]);
5055 check_closed_broadcast!(nodes[2], true);
5056 check_added_monitors!(nodes[2], 1);
5057 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5059 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5060 assert_eq!(c_txn.len(), 3);
5061 assert_eq!(c_txn[0], c_txn[2]);
5062 assert_eq!(commitment_tx[0], c_txn[1]);
5063 check_spends!(c_txn[1], chan_2.3);
5064 check_spends!(c_txn[2], c_txn[1]);
5065 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5066 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5067 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5068 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5070 // 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
5071 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5072 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5073 check_added_monitors!(nodes[1], 1);
5074 let events = nodes[1].node.get_and_clear_pending_events();
5075 assert_eq!(events.len(), 2);
5077 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5078 _ => panic!("Unexpected event"),
5081 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5082 assert_eq!(fee_earned_msat, Some(1000));
5083 assert_eq!(claim_from_onchain_tx, true);
5085 _ => panic!("Unexpected event"),
5088 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5089 // ChannelMonitor: claim tx
5090 assert_eq!(b_txn.len(), 1);
5091 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5094 check_added_monitors!(nodes[1], 1);
5095 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5096 assert_eq!(msg_events.len(), 3);
5097 match msg_events[0] {
5098 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5099 _ => panic!("Unexpected event"),
5101 match msg_events[1] {
5102 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5103 _ => panic!("Unexpected event"),
5105 match msg_events[2] {
5106 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, .. } } => {
5107 assert!(update_add_htlcs.is_empty());
5108 assert!(update_fail_htlcs.is_empty());
5109 assert_eq!(update_fulfill_htlcs.len(), 1);
5110 assert!(update_fail_malformed_htlcs.is_empty());
5111 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5113 _ => panic!("Unexpected event"),
5115 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5116 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5117 mine_transaction(&nodes[1], &commitment_tx[0]);
5118 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5119 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5120 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5121 assert_eq!(b_txn.len(), 3);
5122 check_spends!(b_txn[1], chan_1.3);
5123 check_spends!(b_txn[2], b_txn[1]);
5124 check_spends!(b_txn[0], commitment_tx[0]);
5125 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5126 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5127 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5129 check_closed_broadcast!(nodes[1], true);
5130 check_added_monitors!(nodes[1], 1);
5134 fn test_duplicate_payment_hash_one_failure_one_success() {
5135 // Topology : A --> B --> C --> D
5136 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5137 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5138 // we forward one of the payments onwards to D.
5139 let chanmon_cfgs = create_chanmon_cfgs(4);
5140 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5141 // When this test was written, the default base fee floated based on the HTLC count.
5142 // It is now fixed, so we simply set the fee to the expected value here.
5143 let mut config = test_default_channel_config();
5144 config.channel_options.forwarding_fee_base_msat = 196;
5145 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5146 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5147 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5149 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5150 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5151 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5153 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5154 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5155 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5156 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5157 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5159 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5161 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5162 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5163 // script push size limit so that the below script length checks match
5164 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5165 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5166 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5168 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5169 assert_eq!(commitment_txn[0].input.len(), 1);
5170 check_spends!(commitment_txn[0], chan_2.3);
5172 mine_transaction(&nodes[1], &commitment_txn[0]);
5173 check_closed_broadcast!(nodes[1], true);
5174 check_added_monitors!(nodes[1], 1);
5175 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5176 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5178 let htlc_timeout_tx;
5179 { // Extract one of the two HTLC-Timeout transaction
5180 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5181 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5182 assert_eq!(node_txn.len(), 4);
5183 check_spends!(node_txn[0], chan_2.3);
5185 check_spends!(node_txn[1], commitment_txn[0]);
5186 assert_eq!(node_txn[1].input.len(), 1);
5187 check_spends!(node_txn[2], commitment_txn[0]);
5188 assert_eq!(node_txn[2].input.len(), 1);
5189 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5190 check_spends!(node_txn[3], commitment_txn[0]);
5191 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5193 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5194 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5195 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5196 htlc_timeout_tx = node_txn[1].clone();
5199 nodes[2].node.claim_funds(our_payment_preimage);
5200 mine_transaction(&nodes[2], &commitment_txn[0]);
5201 check_added_monitors!(nodes[2], 2);
5202 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5203 let events = nodes[2].node.get_and_clear_pending_msg_events();
5205 MessageSendEvent::UpdateHTLCs { .. } => {},
5206 _ => panic!("Unexpected event"),
5209 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5210 _ => panic!("Unexepected event"),
5212 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5213 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)
5214 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5215 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5216 assert_eq!(htlc_success_txn[0].input.len(), 1);
5217 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5218 assert_eq!(htlc_success_txn[1].input.len(), 1);
5219 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5220 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5221 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5222 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5223 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5224 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5226 mine_transaction(&nodes[1], &htlc_timeout_tx);
5227 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5228 expect_pending_htlcs_forwardable!(nodes[1]);
5229 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5230 assert!(htlc_updates.update_add_htlcs.is_empty());
5231 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5232 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5233 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5234 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5235 check_added_monitors!(nodes[1], 1);
5237 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5238 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5240 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5242 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5244 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5245 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5246 // and nodes[2] fee) is rounded down and then claimed in full.
5247 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5248 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5249 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5250 assert!(updates.update_add_htlcs.is_empty());
5251 assert!(updates.update_fail_htlcs.is_empty());
5252 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5253 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5254 assert!(updates.update_fail_malformed_htlcs.is_empty());
5255 check_added_monitors!(nodes[1], 1);
5257 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5258 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5260 let events = nodes[0].node.get_and_clear_pending_events();
5262 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5263 assert_eq!(*payment_preimage, our_payment_preimage);
5264 assert_eq!(*payment_hash, duplicate_payment_hash);
5266 _ => panic!("Unexpected event"),
5271 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5272 let chanmon_cfgs = create_chanmon_cfgs(2);
5273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5275 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5277 // Create some initial channels
5278 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5280 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5281 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5282 assert_eq!(local_txn.len(), 1);
5283 assert_eq!(local_txn[0].input.len(), 1);
5284 check_spends!(local_txn[0], chan_1.3);
5286 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5287 nodes[1].node.claim_funds(payment_preimage);
5288 check_added_monitors!(nodes[1], 1);
5289 mine_transaction(&nodes[1], &local_txn[0]);
5290 check_added_monitors!(nodes[1], 1);
5291 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5292 let events = nodes[1].node.get_and_clear_pending_msg_events();
5294 MessageSendEvent::UpdateHTLCs { .. } => {},
5295 _ => panic!("Unexpected event"),
5298 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5299 _ => panic!("Unexepected event"),
5302 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5303 assert_eq!(node_txn.len(), 3);
5304 assert_eq!(node_txn[0], node_txn[2]);
5305 assert_eq!(node_txn[1], local_txn[0]);
5306 assert_eq!(node_txn[0].input.len(), 1);
5307 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5308 check_spends!(node_txn[0], local_txn[0]);
5312 mine_transaction(&nodes[1], &node_tx);
5313 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5315 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5316 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5317 assert_eq!(spend_txn.len(), 1);
5318 assert_eq!(spend_txn[0].input.len(), 1);
5319 check_spends!(spend_txn[0], node_tx);
5320 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5323 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5324 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5325 // unrevoked commitment transaction.
5326 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5327 // a remote RAA before they could be failed backwards (and combinations thereof).
5328 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5329 // use the same payment hashes.
5330 // Thus, we use a six-node network:
5335 // And test where C fails back to A/B when D announces its latest commitment transaction
5336 let chanmon_cfgs = create_chanmon_cfgs(6);
5337 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5338 // When this test was written, the default base fee floated based on the HTLC count.
5339 // It is now fixed, so we simply set the fee to the expected value here.
5340 let mut config = test_default_channel_config();
5341 config.channel_options.forwarding_fee_base_msat = 196;
5342 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5343 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5344 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5346 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5347 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5348 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5349 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5350 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5352 // Rebalance and check output sanity...
5353 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5354 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5355 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5357 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5359 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
5361 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
5362 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5364 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
5366 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
5368 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5370 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5371 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5373 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());
5375 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());
5378 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5380 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5381 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
5384 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
5386 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5387 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());
5389 // Double-check that six of the new HTLC were added
5390 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5391 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5392 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5393 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5395 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5396 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5397 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5398 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5399 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5400 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5401 check_added_monitors!(nodes[4], 0);
5402 expect_pending_htlcs_forwardable!(nodes[4]);
5403 check_added_monitors!(nodes[4], 1);
5405 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5406 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5407 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5408 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5409 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5410 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5412 // Fail 3rd below-dust and 7th above-dust HTLCs
5413 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5414 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5415 check_added_monitors!(nodes[5], 0);
5416 expect_pending_htlcs_forwardable!(nodes[5]);
5417 check_added_monitors!(nodes[5], 1);
5419 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5420 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5421 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5422 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5424 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5426 expect_pending_htlcs_forwardable!(nodes[3]);
5427 check_added_monitors!(nodes[3], 1);
5428 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5429 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5430 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5431 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5432 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5433 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5434 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5435 if deliver_last_raa {
5436 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5438 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5441 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5442 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5443 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5444 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5446 // We now broadcast the latest commitment transaction, which *should* result in failures for
5447 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5448 // the non-broadcast above-dust HTLCs.
5450 // Alternatively, we may broadcast the previous commitment transaction, which should only
5451 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5452 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5454 if announce_latest {
5455 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5457 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5459 let events = nodes[2].node.get_and_clear_pending_events();
5460 let close_event = if deliver_last_raa {
5461 assert_eq!(events.len(), 2);
5464 assert_eq!(events.len(), 1);
5468 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5469 _ => panic!("Unexpected event"),
5472 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5473 check_closed_broadcast!(nodes[2], true);
5474 if deliver_last_raa {
5475 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5477 expect_pending_htlcs_forwardable!(nodes[2]);
5479 check_added_monitors!(nodes[2], 3);
5481 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5482 assert_eq!(cs_msgs.len(), 2);
5483 let mut a_done = false;
5484 for msg in cs_msgs {
5486 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5487 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5488 // should be failed-backwards here.
5489 let target = if *node_id == nodes[0].node.get_our_node_id() {
5490 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5491 for htlc in &updates.update_fail_htlcs {
5492 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 });
5494 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5499 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5500 for htlc in &updates.update_fail_htlcs {
5501 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5503 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5504 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5507 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5508 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5509 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5510 if announce_latest {
5511 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5512 if *node_id == nodes[0].node.get_our_node_id() {
5513 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5516 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5518 _ => panic!("Unexpected event"),
5522 let as_events = nodes[0].node.get_and_clear_pending_events();
5523 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5524 let mut as_failds = HashSet::new();
5525 let mut as_updates = 0;
5526 for event in as_events.iter() {
5527 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5528 assert!(as_failds.insert(*payment_hash));
5529 if *payment_hash != payment_hash_2 {
5530 assert_eq!(*rejected_by_dest, deliver_last_raa);
5532 assert!(!rejected_by_dest);
5534 if network_update.is_some() {
5537 } else { panic!("Unexpected event"); }
5539 assert!(as_failds.contains(&payment_hash_1));
5540 assert!(as_failds.contains(&payment_hash_2));
5541 if announce_latest {
5542 assert!(as_failds.contains(&payment_hash_3));
5543 assert!(as_failds.contains(&payment_hash_5));
5545 assert!(as_failds.contains(&payment_hash_6));
5547 let bs_events = nodes[1].node.get_and_clear_pending_events();
5548 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5549 let mut bs_failds = HashSet::new();
5550 let mut bs_updates = 0;
5551 for event in bs_events.iter() {
5552 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5553 assert!(bs_failds.insert(*payment_hash));
5554 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5555 assert_eq!(*rejected_by_dest, deliver_last_raa);
5557 assert!(!rejected_by_dest);
5559 if network_update.is_some() {
5562 } else { panic!("Unexpected event"); }
5564 assert!(bs_failds.contains(&payment_hash_1));
5565 assert!(bs_failds.contains(&payment_hash_2));
5566 if announce_latest {
5567 assert!(bs_failds.contains(&payment_hash_4));
5569 assert!(bs_failds.contains(&payment_hash_5));
5571 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5572 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5573 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5574 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5575 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5576 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5580 fn test_fail_backwards_latest_remote_announce_a() {
5581 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5585 fn test_fail_backwards_latest_remote_announce_b() {
5586 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5590 fn test_fail_backwards_previous_remote_announce() {
5591 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5592 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5593 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5597 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5598 let chanmon_cfgs = create_chanmon_cfgs(2);
5599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5601 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5603 // Create some initial channels
5604 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5606 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5607 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5608 assert_eq!(local_txn[0].input.len(), 1);
5609 check_spends!(local_txn[0], chan_1.3);
5611 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5612 mine_transaction(&nodes[0], &local_txn[0]);
5613 check_closed_broadcast!(nodes[0], true);
5614 check_added_monitors!(nodes[0], 1);
5615 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5616 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5618 let htlc_timeout = {
5619 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5620 assert_eq!(node_txn.len(), 2);
5621 check_spends!(node_txn[0], chan_1.3);
5622 assert_eq!(node_txn[1].input.len(), 1);
5623 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5624 check_spends!(node_txn[1], local_txn[0]);
5628 mine_transaction(&nodes[0], &htlc_timeout);
5629 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5630 expect_payment_failed!(nodes[0], our_payment_hash, true);
5632 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5633 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5634 assert_eq!(spend_txn.len(), 3);
5635 check_spends!(spend_txn[0], local_txn[0]);
5636 assert_eq!(spend_txn[1].input.len(), 1);
5637 check_spends!(spend_txn[1], htlc_timeout);
5638 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5639 assert_eq!(spend_txn[2].input.len(), 2);
5640 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5641 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5642 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5646 fn test_key_derivation_params() {
5647 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5648 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5649 // let us re-derive the channel key set to then derive a delayed_payment_key.
5651 let chanmon_cfgs = create_chanmon_cfgs(3);
5653 // We manually create the node configuration to backup the seed.
5654 let seed = [42; 32];
5655 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5656 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);
5657 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() };
5658 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5659 node_cfgs.remove(0);
5660 node_cfgs.insert(0, node);
5662 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5663 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5665 // Create some initial channels
5666 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5668 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5669 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5670 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5672 // Ensure all nodes are at the same height
5673 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5674 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5675 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5676 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5678 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5679 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5680 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5681 assert_eq!(local_txn_1[0].input.len(), 1);
5682 check_spends!(local_txn_1[0], chan_1.3);
5684 // We check funding pubkey are unique
5685 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]));
5686 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]));
5687 if from_0_funding_key_0 == from_1_funding_key_0
5688 || from_0_funding_key_0 == from_1_funding_key_1
5689 || from_0_funding_key_1 == from_1_funding_key_0
5690 || from_0_funding_key_1 == from_1_funding_key_1 {
5691 panic!("Funding pubkeys aren't unique");
5694 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5695 mine_transaction(&nodes[0], &local_txn_1[0]);
5696 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5697 check_closed_broadcast!(nodes[0], true);
5698 check_added_monitors!(nodes[0], 1);
5699 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5701 let htlc_timeout = {
5702 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5703 assert_eq!(node_txn[1].input.len(), 1);
5704 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5705 check_spends!(node_txn[1], local_txn_1[0]);
5709 mine_transaction(&nodes[0], &htlc_timeout);
5710 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5711 expect_payment_failed!(nodes[0], our_payment_hash, true);
5713 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5714 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5715 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5716 assert_eq!(spend_txn.len(), 3);
5717 check_spends!(spend_txn[0], local_txn_1[0]);
5718 assert_eq!(spend_txn[1].input.len(), 1);
5719 check_spends!(spend_txn[1], htlc_timeout);
5720 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5721 assert_eq!(spend_txn[2].input.len(), 2);
5722 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5723 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5724 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5728 fn test_static_output_closing_tx() {
5729 let chanmon_cfgs = create_chanmon_cfgs(2);
5730 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5731 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5732 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5734 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5736 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5737 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5739 mine_transaction(&nodes[0], &closing_tx);
5740 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5741 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5743 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5744 assert_eq!(spend_txn.len(), 1);
5745 check_spends!(spend_txn[0], closing_tx);
5747 mine_transaction(&nodes[1], &closing_tx);
5748 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5749 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5751 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5752 assert_eq!(spend_txn.len(), 1);
5753 check_spends!(spend_txn[0], closing_tx);
5756 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5757 let chanmon_cfgs = create_chanmon_cfgs(2);
5758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5760 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5761 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5763 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5765 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5766 // present in B's local commitment transaction, but none of A's commitment transactions.
5767 assert!(nodes[1].node.claim_funds(payment_preimage));
5768 check_added_monitors!(nodes[1], 1);
5770 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5771 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5772 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5774 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5775 check_added_monitors!(nodes[0], 1);
5776 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5777 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5778 check_added_monitors!(nodes[1], 1);
5780 let starting_block = nodes[1].best_block_info();
5781 let mut block = Block {
5782 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5785 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5786 connect_block(&nodes[1], &block);
5787 block.header.prev_blockhash = block.block_hash();
5789 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5790 check_closed_broadcast!(nodes[1], true);
5791 check_added_monitors!(nodes[1], 1);
5792 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5795 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5796 let chanmon_cfgs = create_chanmon_cfgs(2);
5797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5800 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5803 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5804 check_added_monitors!(nodes[0], 1);
5806 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5808 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5809 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5810 // to "time out" the HTLC.
5812 let starting_block = nodes[1].best_block_info();
5813 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5815 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5816 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5817 header.prev_blockhash = header.block_hash();
5819 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5820 check_closed_broadcast!(nodes[0], true);
5821 check_added_monitors!(nodes[0], 1);
5822 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5825 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5826 let chanmon_cfgs = create_chanmon_cfgs(3);
5827 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5828 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5829 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5830 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5832 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5833 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5834 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5835 // actually revoked.
5836 let htlc_value = if use_dust { 50000 } else { 3000000 };
5837 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5838 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5839 expect_pending_htlcs_forwardable!(nodes[1]);
5840 check_added_monitors!(nodes[1], 1);
5842 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5843 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5844 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5845 check_added_monitors!(nodes[0], 1);
5846 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5847 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5848 check_added_monitors!(nodes[1], 1);
5849 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5850 check_added_monitors!(nodes[1], 1);
5851 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5853 if check_revoke_no_close {
5854 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5855 check_added_monitors!(nodes[0], 1);
5858 let starting_block = nodes[1].best_block_info();
5859 let mut block = Block {
5860 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5863 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5864 connect_block(&nodes[0], &block);
5865 block.header.prev_blockhash = block.block_hash();
5867 if !check_revoke_no_close {
5868 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5869 check_closed_broadcast!(nodes[0], true);
5870 check_added_monitors!(nodes[0], 1);
5871 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5873 let events = nodes[0].node.get_and_clear_pending_events();
5874 assert_eq!(events.len(), 2);
5875 if let Event::PaymentPathFailed { ref payment_hash, .. } = events[0] {
5876 assert_eq!(*payment_hash, our_payment_hash);
5877 } else { panic!("Unexpected event"); }
5878 if let Event::PaymentFailed { ref payment_hash, .. } = events[1] {
5879 assert_eq!(*payment_hash, our_payment_hash);
5880 } else { panic!("Unexpected event"); }
5884 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5885 // There are only a few cases to test here:
5886 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5887 // broadcastable commitment transactions result in channel closure,
5888 // * its included in an unrevoked-but-previous remote commitment transaction,
5889 // * its included in the latest remote or local commitment transactions.
5890 // We test each of the three possible commitment transactions individually and use both dust and
5892 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5893 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5894 // tested for at least one of the cases in other tests.
5896 fn htlc_claim_single_commitment_only_a() {
5897 do_htlc_claim_local_commitment_only(true);
5898 do_htlc_claim_local_commitment_only(false);
5900 do_htlc_claim_current_remote_commitment_only(true);
5901 do_htlc_claim_current_remote_commitment_only(false);
5905 fn htlc_claim_single_commitment_only_b() {
5906 do_htlc_claim_previous_remote_commitment_only(true, false);
5907 do_htlc_claim_previous_remote_commitment_only(false, false);
5908 do_htlc_claim_previous_remote_commitment_only(true, true);
5909 do_htlc_claim_previous_remote_commitment_only(false, true);
5914 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5915 let chanmon_cfgs = create_chanmon_cfgs(2);
5916 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5917 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5918 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5919 // Force duplicate randomness for every get-random call
5920 for node in nodes.iter() {
5921 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5924 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5925 let channel_value_satoshis=10000;
5926 let push_msat=10001;
5927 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5928 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5929 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5930 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5932 // Create a second channel with the same random values. This used to panic due to a colliding
5933 // channel_id, but now panics due to a colliding outbound SCID alias.
5934 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5938 fn bolt2_open_channel_sending_node_checks_part2() {
5939 let chanmon_cfgs = create_chanmon_cfgs(2);
5940 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5941 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5942 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5944 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5945 let channel_value_satoshis=2^24;
5946 let push_msat=10001;
5947 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5949 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5950 let channel_value_satoshis=10000;
5951 // Test when push_msat is equal to 1000 * funding_satoshis.
5952 let push_msat=1000*channel_value_satoshis+1;
5953 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5955 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5956 let channel_value_satoshis=10000;
5957 let push_msat=10001;
5958 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
5959 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5960 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5962 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5963 // 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
5964 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5966 // 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.
5967 assert!(BREAKDOWN_TIMEOUT>0);
5968 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5970 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5971 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5972 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5974 // 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.
5975 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5976 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5977 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5978 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5979 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5983 fn bolt2_open_channel_sane_dust_limit() {
5984 let chanmon_cfgs = create_chanmon_cfgs(2);
5985 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5986 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5987 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5989 let channel_value_satoshis=1000000;
5990 let push_msat=10001;
5991 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5992 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5993 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5994 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5996 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5997 let events = nodes[1].node.get_and_clear_pending_msg_events();
5998 let err_msg = match events[0] {
5999 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6002 _ => panic!("Unexpected event"),
6004 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6007 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6008 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6009 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6010 // is no longer affordable once it's freed.
6012 fn test_fail_holding_cell_htlc_upon_free() {
6013 let chanmon_cfgs = create_chanmon_cfgs(2);
6014 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6015 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6016 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6017 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6019 // First nodes[0] generates an update_fee, setting the channel's
6020 // pending_update_fee.
6022 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6023 *feerate_lock += 20;
6025 nodes[0].node.timer_tick_occurred();
6026 check_added_monitors!(nodes[0], 1);
6028 let events = nodes[0].node.get_and_clear_pending_msg_events();
6029 assert_eq!(events.len(), 1);
6030 let (update_msg, commitment_signed) = match events[0] {
6031 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6032 (update_fee.as_ref(), commitment_signed)
6034 _ => panic!("Unexpected event"),
6037 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6039 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6040 let channel_reserve = chan_stat.channel_reserve_msat;
6041 let feerate = get_feerate!(nodes[0], chan.2);
6042 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6044 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6045 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6046 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6048 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6049 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6050 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6051 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6053 // Flush the pending fee update.
6054 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6055 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6056 check_added_monitors!(nodes[1], 1);
6057 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6058 check_added_monitors!(nodes[0], 1);
6060 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6061 // HTLC, but now that the fee has been raised the payment will now fail, causing
6062 // us to surface its failure to the user.
6063 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6064 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6065 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);
6066 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 {}",
6067 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6068 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6070 // Check that the payment failed to be sent out.
6071 let events = nodes[0].node.get_and_clear_pending_events();
6072 assert_eq!(events.len(), 1);
6074 &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, .. } => {
6075 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
6076 assert_eq!(our_payment_hash.clone(), *payment_hash);
6077 assert_eq!(*rejected_by_dest, false);
6078 assert_eq!(*all_paths_failed, true);
6079 assert_eq!(*network_update, None);
6080 assert_eq!(*short_channel_id, None);
6081 assert_eq!(*error_code, None);
6082 assert_eq!(*error_data, None);
6084 _ => panic!("Unexpected event"),
6088 // Test that if multiple HTLCs are released from the holding cell and one is
6089 // valid but the other is no longer valid upon release, the valid HTLC can be
6090 // successfully completed while the other one fails as expected.
6092 fn test_free_and_fail_holding_cell_htlcs() {
6093 let chanmon_cfgs = create_chanmon_cfgs(2);
6094 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6095 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6096 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6097 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6099 // First nodes[0] generates an update_fee, setting the channel's
6100 // pending_update_fee.
6102 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6103 *feerate_lock += 200;
6105 nodes[0].node.timer_tick_occurred();
6106 check_added_monitors!(nodes[0], 1);
6108 let events = nodes[0].node.get_and_clear_pending_msg_events();
6109 assert_eq!(events.len(), 1);
6110 let (update_msg, commitment_signed) = match events[0] {
6111 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6112 (update_fee.as_ref(), commitment_signed)
6114 _ => panic!("Unexpected event"),
6117 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6119 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6120 let channel_reserve = chan_stat.channel_reserve_msat;
6121 let feerate = get_feerate!(nodes[0], chan.2);
6122 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6124 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6126 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
6127 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6128 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6130 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6131 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6132 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6133 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6134 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6135 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6136 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6138 // Flush the pending fee update.
6139 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6140 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6141 check_added_monitors!(nodes[1], 1);
6142 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6143 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6144 check_added_monitors!(nodes[0], 2);
6146 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6147 // but now that the fee has been raised the second payment will now fail, causing us
6148 // to surface its failure to the user. The first payment should succeed.
6149 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6150 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6151 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);
6152 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 {}",
6153 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6154 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6156 // Check that the second payment failed to be sent out.
6157 let events = nodes[0].node.get_and_clear_pending_events();
6158 assert_eq!(events.len(), 1);
6160 &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, .. } => {
6161 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6162 assert_eq!(payment_hash_2.clone(), *payment_hash);
6163 assert_eq!(*rejected_by_dest, false);
6164 assert_eq!(*all_paths_failed, true);
6165 assert_eq!(*network_update, None);
6166 assert_eq!(*short_channel_id, None);
6167 assert_eq!(*error_code, None);
6168 assert_eq!(*error_data, None);
6170 _ => panic!("Unexpected event"),
6173 // Complete the first payment and the RAA from the fee update.
6174 let (payment_event, send_raa_event) = {
6175 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6176 assert_eq!(msgs.len(), 2);
6177 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6179 let raa = match send_raa_event {
6180 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6181 _ => panic!("Unexpected event"),
6183 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6184 check_added_monitors!(nodes[1], 1);
6185 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6186 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6187 let events = nodes[1].node.get_and_clear_pending_events();
6188 assert_eq!(events.len(), 1);
6190 Event::PendingHTLCsForwardable { .. } => {},
6191 _ => panic!("Unexpected event"),
6193 nodes[1].node.process_pending_htlc_forwards();
6194 let events = nodes[1].node.get_and_clear_pending_events();
6195 assert_eq!(events.len(), 1);
6197 Event::PaymentReceived { .. } => {},
6198 _ => panic!("Unexpected event"),
6200 nodes[1].node.claim_funds(payment_preimage_1);
6201 check_added_monitors!(nodes[1], 1);
6202 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6203 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6204 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6205 expect_payment_sent!(nodes[0], payment_preimage_1);
6208 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6209 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6210 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6213 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6214 let chanmon_cfgs = create_chanmon_cfgs(3);
6215 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6216 // When this test was written, the default base fee floated based on the HTLC count.
6217 // It is now fixed, so we simply set the fee to the expected value here.
6218 let mut config = test_default_channel_config();
6219 config.channel_options.forwarding_fee_base_msat = 196;
6220 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6221 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6222 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6223 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6225 // First nodes[1] generates an update_fee, setting the channel's
6226 // pending_update_fee.
6228 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6229 *feerate_lock += 20;
6231 nodes[1].node.timer_tick_occurred();
6232 check_added_monitors!(nodes[1], 1);
6234 let events = nodes[1].node.get_and_clear_pending_msg_events();
6235 assert_eq!(events.len(), 1);
6236 let (update_msg, commitment_signed) = match events[0] {
6237 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6238 (update_fee.as_ref(), commitment_signed)
6240 _ => panic!("Unexpected event"),
6243 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6245 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6246 let channel_reserve = chan_stat.channel_reserve_msat;
6247 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6248 let opt_anchors = get_opt_anchors!(nodes[0], chan_0_1.2);
6250 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6252 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6253 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
6254 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6255 let payment_event = {
6256 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6257 check_added_monitors!(nodes[0], 1);
6259 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6260 assert_eq!(events.len(), 1);
6262 SendEvent::from_event(events.remove(0))
6264 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6265 check_added_monitors!(nodes[1], 0);
6266 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6267 expect_pending_htlcs_forwardable!(nodes[1]);
6269 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6270 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6272 // Flush the pending fee update.
6273 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6274 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6275 check_added_monitors!(nodes[2], 1);
6276 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6277 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6278 check_added_monitors!(nodes[1], 2);
6280 // A final RAA message is generated to finalize the fee update.
6281 let events = nodes[1].node.get_and_clear_pending_msg_events();
6282 assert_eq!(events.len(), 1);
6284 let raa_msg = match &events[0] {
6285 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6288 _ => panic!("Unexpected event"),
6291 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6292 check_added_monitors!(nodes[2], 1);
6293 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6295 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6296 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6297 assert_eq!(process_htlc_forwards_event.len(), 1);
6298 match &process_htlc_forwards_event[0] {
6299 &Event::PendingHTLCsForwardable { .. } => {},
6300 _ => panic!("Unexpected event"),
6303 // In response, we call ChannelManager's process_pending_htlc_forwards
6304 nodes[1].node.process_pending_htlc_forwards();
6305 check_added_monitors!(nodes[1], 1);
6307 // This causes the HTLC to be failed backwards.
6308 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6309 assert_eq!(fail_event.len(), 1);
6310 let (fail_msg, commitment_signed) = match &fail_event[0] {
6311 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6312 assert_eq!(updates.update_add_htlcs.len(), 0);
6313 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6314 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6315 assert_eq!(updates.update_fail_htlcs.len(), 1);
6316 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6318 _ => panic!("Unexpected event"),
6321 // Pass the failure messages back to nodes[0].
6322 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6323 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6325 // Complete the HTLC failure+removal process.
6326 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6327 check_added_monitors!(nodes[0], 1);
6328 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6329 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6330 check_added_monitors!(nodes[1], 2);
6331 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6332 assert_eq!(final_raa_event.len(), 1);
6333 let raa = match &final_raa_event[0] {
6334 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6335 _ => panic!("Unexpected event"),
6337 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6338 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6339 check_added_monitors!(nodes[0], 1);
6342 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6343 // 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.
6344 //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.
6347 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6348 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6349 let chanmon_cfgs = create_chanmon_cfgs(2);
6350 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6351 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6352 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6353 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6355 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6356 route.paths[0][0].fee_msat = 100;
6358 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6359 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6360 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6361 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6365 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6366 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6367 let chanmon_cfgs = create_chanmon_cfgs(2);
6368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6370 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6371 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6373 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6374 route.paths[0][0].fee_msat = 0;
6375 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6376 assert_eq!(err, "Cannot send 0-msat HTLC"));
6378 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6379 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6383 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6384 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6385 let chanmon_cfgs = create_chanmon_cfgs(2);
6386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6391 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6392 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6393 check_added_monitors!(nodes[0], 1);
6394 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6395 updates.update_add_htlcs[0].amount_msat = 0;
6397 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6398 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6399 check_closed_broadcast!(nodes[1], true).unwrap();
6400 check_added_monitors!(nodes[1], 1);
6401 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6405 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6406 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6407 //It is enforced when constructing a route.
6408 let chanmon_cfgs = create_chanmon_cfgs(2);
6409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6411 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6412 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6414 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 0);
6415 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6416 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6417 assert_eq!(err, &"Channel CLTV overflowed?"));
6421 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6422 //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.
6423 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6424 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
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, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6430 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6432 for i in 0..max_accepted_htlcs {
6433 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6434 let payment_event = {
6435 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6436 check_added_monitors!(nodes[0], 1);
6438 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6439 assert_eq!(events.len(), 1);
6440 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6441 assert_eq!(htlcs[0].htlc_id, i);
6445 SendEvent::from_event(events.remove(0))
6447 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6448 check_added_monitors!(nodes[1], 0);
6449 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6451 expect_pending_htlcs_forwardable!(nodes[1]);
6452 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6454 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6455 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6456 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6458 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6459 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6463 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6464 //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.
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 channel_value = 100000;
6470 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6471 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6473 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6475 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6476 // Manually create a route over our max in flight (which our router normally automatically
6478 route.paths[0][0].fee_msat = max_in_flight + 1;
6479 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6480 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)));
6482 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6483 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);
6485 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6488 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6490 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6491 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6492 let chanmon_cfgs = create_chanmon_cfgs(2);
6493 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6494 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6495 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6496 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6497 let htlc_minimum_msat: u64;
6499 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6500 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6501 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6504 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6505 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6506 check_added_monitors!(nodes[0], 1);
6507 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6508 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6509 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6510 assert!(nodes[1].node.list_channels().is_empty());
6511 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6512 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()));
6513 check_added_monitors!(nodes[1], 1);
6514 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6518 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6519 //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
6520 let chanmon_cfgs = create_chanmon_cfgs(2);
6521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6526 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6527 let channel_reserve = chan_stat.channel_reserve_msat;
6528 let feerate = get_feerate!(nodes[0], chan.2);
6529 let opt_anchors = get_opt_anchors!(nodes[0], chan.2);
6530 // The 2* and +1 are for the fee spike reserve.
6531 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6533 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6534 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6535 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6536 check_added_monitors!(nodes[0], 1);
6537 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6539 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6540 // at this time channel-initiatee receivers are not required to enforce that senders
6541 // respect the fee_spike_reserve.
6542 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6543 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6545 assert!(nodes[1].node.list_channels().is_empty());
6546 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6547 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6548 check_added_monitors!(nodes[1], 1);
6549 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6553 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6554 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6555 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6556 let chanmon_cfgs = create_chanmon_cfgs(2);
6557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6560 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6562 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6563 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6564 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6565 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6566 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6567 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6569 let mut msg = msgs::UpdateAddHTLC {
6573 payment_hash: our_payment_hash,
6574 cltv_expiry: htlc_cltv,
6575 onion_routing_packet: onion_packet.clone(),
6578 for i in 0..super::channel::OUR_MAX_HTLCS {
6579 msg.htlc_id = i as u64;
6580 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6582 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6583 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6585 assert!(nodes[1].node.list_channels().is_empty());
6586 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6587 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
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_in_flight_msat() {
6594 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6595 let chanmon_cfgs = create_chanmon_cfgs(2);
6596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6598 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6599 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6601 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6602 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6603 check_added_monitors!(nodes[0], 1);
6604 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6605 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6606 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6608 assert!(nodes[1].node.list_channels().is_empty());
6609 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6610 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6611 check_added_monitors!(nodes[1], 1);
6612 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6616 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6617 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6618 let chanmon_cfgs = create_chanmon_cfgs(2);
6619 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6620 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6621 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6623 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6625 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6626 check_added_monitors!(nodes[0], 1);
6627 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6628 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6629 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6631 assert!(nodes[1].node.list_channels().is_empty());
6632 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6633 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6634 check_added_monitors!(nodes[1], 1);
6635 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6639 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6640 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6641 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6642 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6643 let chanmon_cfgs = create_chanmon_cfgs(2);
6644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6648 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6649 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6650 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6651 check_added_monitors!(nodes[0], 1);
6652 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6653 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6655 //Disconnect and Reconnect
6656 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6657 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6658 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6659 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6660 assert_eq!(reestablish_1.len(), 1);
6661 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6662 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6663 assert_eq!(reestablish_2.len(), 1);
6664 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6665 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6666 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6667 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6670 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6671 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6672 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6673 check_added_monitors!(nodes[1], 1);
6674 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6678 assert!(nodes[1].node.list_channels().is_empty());
6679 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6680 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6681 check_added_monitors!(nodes[1], 1);
6682 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6686 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6687 //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.
6689 let chanmon_cfgs = create_chanmon_cfgs(2);
6690 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6691 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6692 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6693 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6694 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6695 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6697 check_added_monitors!(nodes[0], 1);
6698 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6699 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6701 let update_msg = msgs::UpdateFulfillHTLC{
6704 payment_preimage: our_payment_preimage,
6707 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6709 assert!(nodes[0].node.list_channels().is_empty());
6710 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6711 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()));
6712 check_added_monitors!(nodes[0], 1);
6713 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6717 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6718 //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.
6720 let chanmon_cfgs = create_chanmon_cfgs(2);
6721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6723 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6724 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6726 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6727 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6728 check_added_monitors!(nodes[0], 1);
6729 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6730 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6732 let update_msg = msgs::UpdateFailHTLC{
6735 reason: msgs::OnionErrorPacket { data: Vec::new()},
6738 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6740 assert!(nodes[0].node.list_channels().is_empty());
6741 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6742 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()));
6743 check_added_monitors!(nodes[0], 1);
6744 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6748 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6749 //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.
6751 let chanmon_cfgs = create_chanmon_cfgs(2);
6752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6755 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6757 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6758 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6759 check_added_monitors!(nodes[0], 1);
6760 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6761 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6762 let update_msg = msgs::UpdateFailMalformedHTLC{
6765 sha256_of_onion: [1; 32],
6766 failure_code: 0x8000,
6769 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6771 assert!(nodes[0].node.list_channels().is_empty());
6772 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6773 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()));
6774 check_added_monitors!(nodes[0], 1);
6775 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6779 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6780 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6782 let chanmon_cfgs = create_chanmon_cfgs(2);
6783 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6784 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6785 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6786 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6788 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6790 nodes[1].node.claim_funds(our_payment_preimage);
6791 check_added_monitors!(nodes[1], 1);
6793 let events = nodes[1].node.get_and_clear_pending_msg_events();
6794 assert_eq!(events.len(), 1);
6795 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6797 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, .. } } => {
6798 assert!(update_add_htlcs.is_empty());
6799 assert_eq!(update_fulfill_htlcs.len(), 1);
6800 assert!(update_fail_htlcs.is_empty());
6801 assert!(update_fail_malformed_htlcs.is_empty());
6802 assert!(update_fee.is_none());
6803 update_fulfill_htlcs[0].clone()
6805 _ => panic!("Unexpected event"),
6809 update_fulfill_msg.htlc_id = 1;
6811 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6813 assert!(nodes[0].node.list_channels().is_empty());
6814 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6815 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6816 check_added_monitors!(nodes[0], 1);
6817 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6821 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6822 //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.
6824 let chanmon_cfgs = create_chanmon_cfgs(2);
6825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6827 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6828 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6830 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6832 nodes[1].node.claim_funds(our_payment_preimage);
6833 check_added_monitors!(nodes[1], 1);
6835 let events = nodes[1].node.get_and_clear_pending_msg_events();
6836 assert_eq!(events.len(), 1);
6837 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6839 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, .. } } => {
6840 assert!(update_add_htlcs.is_empty());
6841 assert_eq!(update_fulfill_htlcs.len(), 1);
6842 assert!(update_fail_htlcs.is_empty());
6843 assert!(update_fail_malformed_htlcs.is_empty());
6844 assert!(update_fee.is_none());
6845 update_fulfill_htlcs[0].clone()
6847 _ => panic!("Unexpected event"),
6851 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6853 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6855 assert!(nodes[0].node.list_channels().is_empty());
6856 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6857 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6858 check_added_monitors!(nodes[0], 1);
6859 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6863 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6864 //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.
6866 let chanmon_cfgs = create_chanmon_cfgs(2);
6867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6869 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6870 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6872 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6873 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6874 check_added_monitors!(nodes[0], 1);
6876 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6877 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6879 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6880 check_added_monitors!(nodes[1], 0);
6881 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6883 let events = nodes[1].node.get_and_clear_pending_msg_events();
6885 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6887 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, .. } } => {
6888 assert!(update_add_htlcs.is_empty());
6889 assert!(update_fulfill_htlcs.is_empty());
6890 assert!(update_fail_htlcs.is_empty());
6891 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6892 assert!(update_fee.is_none());
6893 update_fail_malformed_htlcs[0].clone()
6895 _ => panic!("Unexpected event"),
6898 update_msg.failure_code &= !0x8000;
6899 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6901 assert!(nodes[0].node.list_channels().is_empty());
6902 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6903 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6904 check_added_monitors!(nodes[0], 1);
6905 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6909 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6910 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6911 // * 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.
6913 let chanmon_cfgs = create_chanmon_cfgs(3);
6914 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6915 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6916 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6917 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6918 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6920 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6923 let mut payment_event = {
6924 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6925 check_added_monitors!(nodes[0], 1);
6926 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6927 assert_eq!(events.len(), 1);
6928 SendEvent::from_event(events.remove(0))
6930 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6931 check_added_monitors!(nodes[1], 0);
6932 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6933 expect_pending_htlcs_forwardable!(nodes[1]);
6934 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6935 assert_eq!(events_2.len(), 1);
6936 check_added_monitors!(nodes[1], 1);
6937 payment_event = SendEvent::from_event(events_2.remove(0));
6938 assert_eq!(payment_event.msgs.len(), 1);
6941 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6942 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6943 check_added_monitors!(nodes[2], 0);
6944 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6946 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6947 assert_eq!(events_3.len(), 1);
6948 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6950 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 } } => {
6951 assert!(update_add_htlcs.is_empty());
6952 assert!(update_fulfill_htlcs.is_empty());
6953 assert!(update_fail_htlcs.is_empty());
6954 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6955 assert!(update_fee.is_none());
6956 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6958 _ => panic!("Unexpected event"),
6962 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6964 check_added_monitors!(nodes[1], 0);
6965 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6966 expect_pending_htlcs_forwardable!(nodes[1]);
6967 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6968 assert_eq!(events_4.len(), 1);
6970 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6972 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, .. } } => {
6973 assert!(update_add_htlcs.is_empty());
6974 assert!(update_fulfill_htlcs.is_empty());
6975 assert_eq!(update_fail_htlcs.len(), 1);
6976 assert!(update_fail_malformed_htlcs.is_empty());
6977 assert!(update_fee.is_none());
6979 _ => panic!("Unexpected event"),
6982 check_added_monitors!(nodes[1], 1);
6985 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6986 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6987 // 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
6988 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6990 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6991 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6992 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6993 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6994 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6995 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6997 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6999 // We route 2 dust-HTLCs between A and B
7000 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7001 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7002 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7004 // Cache one local commitment tx as previous
7005 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7007 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7008 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7009 check_added_monitors!(nodes[1], 0);
7010 expect_pending_htlcs_forwardable!(nodes[1]);
7011 check_added_monitors!(nodes[1], 1);
7013 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7014 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7015 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7016 check_added_monitors!(nodes[0], 1);
7018 // Cache one local commitment tx as lastest
7019 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7021 let events = nodes[0].node.get_and_clear_pending_msg_events();
7023 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7024 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7026 _ => panic!("Unexpected event"),
7029 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7030 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7032 _ => panic!("Unexpected event"),
7035 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7036 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7037 if announce_latest {
7038 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7040 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7043 check_closed_broadcast!(nodes[0], true);
7044 check_added_monitors!(nodes[0], 1);
7045 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7047 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7048 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7049 let events = nodes[0].node.get_and_clear_pending_events();
7050 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7051 assert_eq!(events.len(), 2);
7052 let mut first_failed = false;
7053 for event in events {
7055 Event::PaymentPathFailed { payment_hash, .. } => {
7056 if payment_hash == payment_hash_1 {
7057 assert!(!first_failed);
7058 first_failed = true;
7060 assert_eq!(payment_hash, payment_hash_2);
7063 _ => panic!("Unexpected event"),
7069 fn test_failure_delay_dust_htlc_local_commitment() {
7070 do_test_failure_delay_dust_htlc_local_commitment(true);
7071 do_test_failure_delay_dust_htlc_local_commitment(false);
7074 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7075 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7076 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7077 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7078 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7079 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7080 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7082 let chanmon_cfgs = create_chanmon_cfgs(3);
7083 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7084 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7085 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7086 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7088 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7090 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7091 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7093 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7094 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7096 // We revoked bs_commitment_tx
7098 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7099 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7102 let mut timeout_tx = Vec::new();
7104 // We fail dust-HTLC 1 by broadcast of local commitment tx
7105 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7106 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7107 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7108 expect_payment_failed!(nodes[0], dust_hash, true);
7110 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7111 check_closed_broadcast!(nodes[0], true);
7112 check_added_monitors!(nodes[0], 1);
7113 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7114 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7115 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7116 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7117 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7118 mine_transaction(&nodes[0], &timeout_tx[0]);
7119 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7120 expect_payment_failed!(nodes[0], non_dust_hash, true);
7122 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7123 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7124 check_closed_broadcast!(nodes[0], true);
7125 check_added_monitors!(nodes[0], 1);
7126 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7127 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7128 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7129 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7131 expect_payment_failed!(nodes[0], dust_hash, true);
7132 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7133 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7134 mine_transaction(&nodes[0], &timeout_tx[0]);
7135 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7136 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7137 expect_payment_failed!(nodes[0], non_dust_hash, true);
7139 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7141 let events = nodes[0].node.get_and_clear_pending_events();
7142 assert_eq!(events.len(), 2);
7145 Event::PaymentPathFailed { payment_hash, .. } => {
7146 if payment_hash == dust_hash { first = true; }
7147 else { first = false; }
7149 _ => panic!("Unexpected event"),
7152 Event::PaymentPathFailed { payment_hash, .. } => {
7153 if first { assert_eq!(payment_hash, non_dust_hash); }
7154 else { assert_eq!(payment_hash, dust_hash); }
7156 _ => panic!("Unexpected event"),
7163 fn test_sweep_outbound_htlc_failure_update() {
7164 do_test_sweep_outbound_htlc_failure_update(false, true);
7165 do_test_sweep_outbound_htlc_failure_update(false, false);
7166 do_test_sweep_outbound_htlc_failure_update(true, false);
7170 fn test_user_configurable_csv_delay() {
7171 // We test our channel constructors yield errors when we pass them absurd csv delay
7173 let mut low_our_to_self_config = UserConfig::default();
7174 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7175 let mut high_their_to_self_config = UserConfig::default();
7176 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7177 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7178 let chanmon_cfgs = create_chanmon_cfgs(2);
7179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7181 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7183 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7184 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7185 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0,
7186 &low_our_to_self_config, 0, 42)
7189 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())); },
7190 _ => panic!("Unexpected event"),
7192 } else { assert!(false) }
7194 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7195 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7196 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7197 open_channel.to_self_delay = 200;
7198 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7199 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7200 &low_our_to_self_config, 0, &nodes[0].logger, 42)
7203 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())); },
7204 _ => panic!("Unexpected event"),
7206 } else { assert!(false); }
7208 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7209 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7210 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()));
7211 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7212 accept_channel.to_self_delay = 200;
7213 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7215 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7217 &ErrorAction::SendErrorMessage { ref msg } => {
7218 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()));
7219 reason_msg = msg.data.clone();
7223 } else { panic!(); }
7224 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7226 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7227 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7228 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7229 open_channel.to_self_delay = 200;
7230 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) },
7231 &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0,
7232 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7235 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())); },
7236 _ => panic!("Unexpected event"),
7238 } else { assert!(false); }
7242 fn test_data_loss_protect() {
7243 // We want to be sure that :
7244 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7245 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7246 // * we close channel in case of detecting other being fallen behind
7247 // * we are able to claim our own outputs thanks to to_remote being static
7248 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7254 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7255 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7256 // during signing due to revoked tx
7257 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7258 let keys_manager = &chanmon_cfgs[0].keys_manager;
7261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7263 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7265 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7267 // Cache node A state before any channel update
7268 let previous_node_state = nodes[0].node.encode();
7269 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7270 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7272 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7273 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7275 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7276 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7278 // Restore node A from previous state
7279 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7280 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7281 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7282 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7283 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7284 persister = test_utils::TestPersister::new();
7285 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7287 let mut channel_monitors = HashMap::new();
7288 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7289 <(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 {
7290 keys_manager: keys_manager,
7291 fee_estimator: &fee_estimator,
7292 chain_monitor: &monitor,
7294 tx_broadcaster: &tx_broadcaster,
7295 default_config: UserConfig::default(),
7299 nodes[0].node = &node_state_0;
7300 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7301 nodes[0].chain_monitor = &monitor;
7302 nodes[0].chain_source = &chain_source;
7304 check_added_monitors!(nodes[0], 1);
7306 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7307 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7309 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7311 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7312 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7313 check_added_monitors!(nodes[0], 1);
7316 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7317 assert_eq!(node_txn.len(), 0);
7320 let mut reestablish_1 = Vec::with_capacity(1);
7321 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7322 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7323 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7324 reestablish_1.push(msg.clone());
7325 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7326 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7328 &ErrorAction::SendErrorMessage { ref msg } => {
7329 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");
7331 _ => panic!("Unexpected event!"),
7334 panic!("Unexpected event")
7338 // Check we close channel detecting A is fallen-behind
7339 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7340 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7341 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7342 check_added_monitors!(nodes[1], 1);
7344 // Check A is able to claim to_remote output
7345 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7346 assert_eq!(node_txn.len(), 1);
7347 check_spends!(node_txn[0], chan.3);
7348 assert_eq!(node_txn[0].output.len(), 2);
7349 mine_transaction(&nodes[0], &node_txn[0]);
7350 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7351 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() });
7352 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7353 assert_eq!(spend_txn.len(), 1);
7354 check_spends!(spend_txn[0], node_txn[0]);
7358 fn test_check_htlc_underpaying() {
7359 // Send payment through A -> B but A is maliciously
7360 // sending a probe payment (i.e less than expected value0
7361 // to B, B should refuse payment.
7363 let chanmon_cfgs = create_chanmon_cfgs(2);
7364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7368 // Create some initial channels
7369 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7371 let scorer = test_utils::TestScorer::with_penalty(0);
7372 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7373 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7374 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();
7375 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7376 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7377 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7378 check_added_monitors!(nodes[0], 1);
7380 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7381 assert_eq!(events.len(), 1);
7382 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7383 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7384 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7386 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7387 // and then will wait a second random delay before failing the HTLC back:
7388 expect_pending_htlcs_forwardable!(nodes[1]);
7389 expect_pending_htlcs_forwardable!(nodes[1]);
7391 // Node 3 is expecting payment of 100_000 but received 10_000,
7392 // it should fail htlc like we didn't know the preimage.
7393 nodes[1].node.process_pending_htlc_forwards();
7395 let events = nodes[1].node.get_and_clear_pending_msg_events();
7396 assert_eq!(events.len(), 1);
7397 let (update_fail_htlc, commitment_signed) = match events[0] {
7398 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 } } => {
7399 assert!(update_add_htlcs.is_empty());
7400 assert!(update_fulfill_htlcs.is_empty());
7401 assert_eq!(update_fail_htlcs.len(), 1);
7402 assert!(update_fail_malformed_htlcs.is_empty());
7403 assert!(update_fee.is_none());
7404 (update_fail_htlcs[0].clone(), commitment_signed)
7406 _ => panic!("Unexpected event"),
7408 check_added_monitors!(nodes[1], 1);
7410 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7411 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7413 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7414 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7415 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7416 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7420 fn test_announce_disable_channels() {
7421 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7422 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7424 let chanmon_cfgs = create_chanmon_cfgs(2);
7425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7427 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7429 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7430 create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known());
7431 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7434 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7435 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7437 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7438 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7439 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7440 assert_eq!(msg_events.len(), 3);
7441 let mut chans_disabled = HashMap::new();
7442 for e in msg_events {
7444 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7445 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7446 // Check that each channel gets updated exactly once
7447 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7448 panic!("Generated ChannelUpdate for wrong chan!");
7451 _ => panic!("Unexpected event"),
7455 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7456 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7457 assert_eq!(reestablish_1.len(), 3);
7458 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7459 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7460 assert_eq!(reestablish_2.len(), 3);
7462 // Reestablish chan_1
7463 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7464 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7465 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7466 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7467 // Reestablish chan_2
7468 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7469 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7470 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7471 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7472 // Reestablish chan_3
7473 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7474 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7475 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7476 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7478 nodes[0].node.timer_tick_occurred();
7479 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7480 nodes[0].node.timer_tick_occurred();
7481 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7482 assert_eq!(msg_events.len(), 3);
7483 for e in msg_events {
7485 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7486 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7487 match chans_disabled.remove(&msg.contents.short_channel_id) {
7488 // Each update should have a higher timestamp than the previous one, replacing
7490 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7491 None => panic!("Generated ChannelUpdate for wrong chan!"),
7494 _ => panic!("Unexpected event"),
7497 // Check that each channel gets updated exactly once
7498 assert!(chans_disabled.is_empty());
7502 fn test_bump_penalty_txn_on_revoked_commitment() {
7503 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7504 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7506 let chanmon_cfgs = create_chanmon_cfgs(2);
7507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7511 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7513 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7514 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7515 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7517 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7518 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7519 assert_eq!(revoked_txn[0].output.len(), 4);
7520 assert_eq!(revoked_txn[0].input.len(), 1);
7521 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7522 let revoked_txid = revoked_txn[0].txid();
7524 let mut penalty_sum = 0;
7525 for outp in revoked_txn[0].output.iter() {
7526 if outp.script_pubkey.is_v0_p2wsh() {
7527 penalty_sum += outp.value;
7531 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7532 let header_114 = connect_blocks(&nodes[1], 14);
7534 // Actually revoke tx by claiming a HTLC
7535 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7536 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7537 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7538 check_added_monitors!(nodes[1], 1);
7540 // One or more justice tx should have been broadcast, check it
7544 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7545 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7546 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7547 assert_eq!(node_txn[0].output.len(), 1);
7548 check_spends!(node_txn[0], revoked_txn[0]);
7549 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7550 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7551 penalty_1 = node_txn[0].txid();
7555 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7556 connect_blocks(&nodes[1], 15);
7557 let mut penalty_2 = penalty_1;
7558 let mut feerate_2 = 0;
7560 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7561 assert_eq!(node_txn.len(), 1);
7562 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7563 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7564 assert_eq!(node_txn[0].output.len(), 1);
7565 check_spends!(node_txn[0], revoked_txn[0]);
7566 penalty_2 = node_txn[0].txid();
7567 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7568 assert_ne!(penalty_2, penalty_1);
7569 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7570 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7571 // Verify 25% bump heuristic
7572 assert!(feerate_2 * 100 >= feerate_1 * 125);
7576 assert_ne!(feerate_2, 0);
7578 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7579 connect_blocks(&nodes[1], 1);
7581 let mut feerate_3 = 0;
7583 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7584 assert_eq!(node_txn.len(), 1);
7585 if node_txn[0].input[0].previous_output.txid == revoked_txid {
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 penalty_3 = node_txn[0].txid();
7590 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7591 assert_ne!(penalty_3, penalty_2);
7592 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7593 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7594 // Verify 25% bump heuristic
7595 assert!(feerate_3 * 100 >= feerate_2 * 125);
7599 assert_ne!(feerate_3, 0);
7601 nodes[1].node.get_and_clear_pending_events();
7602 nodes[1].node.get_and_clear_pending_msg_events();
7606 fn test_bump_penalty_txn_on_revoked_htlcs() {
7607 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7608 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7610 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7611 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7614 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7616 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7617 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7618 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7619 let scorer = test_utils::TestScorer::with_penalty(0);
7620 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7621 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7622 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7623 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7624 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7625 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7626 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7627 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7629 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7630 assert_eq!(revoked_local_txn[0].input.len(), 1);
7631 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7633 // Revoke local commitment tx
7634 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7636 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7637 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7638 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7639 check_closed_broadcast!(nodes[1], true);
7640 check_added_monitors!(nodes[1], 1);
7641 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7642 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7644 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7645 assert_eq!(revoked_htlc_txn.len(), 3);
7646 check_spends!(revoked_htlc_txn[1], chan.3);
7648 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7649 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7650 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7652 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7653 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7654 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7655 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7657 // Broadcast set of revoked txn on A
7658 let hash_128 = connect_blocks(&nodes[0], 40);
7659 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7660 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7661 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7662 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7663 let events = nodes[0].node.get_and_clear_pending_events();
7664 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7666 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7667 _ => panic!("Unexpected event"),
7673 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7674 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7675 // Verify claim tx are spending revoked HTLC txn
7677 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7678 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7679 // which are included in the same block (they are broadcasted because we scan the
7680 // transactions linearly and generate claims as we go, they likely should be removed in the
7682 assert_eq!(node_txn[0].input.len(), 1);
7683 check_spends!(node_txn[0], revoked_local_txn[0]);
7684 assert_eq!(node_txn[1].input.len(), 1);
7685 check_spends!(node_txn[1], revoked_local_txn[0]);
7686 assert_eq!(node_txn[2].input.len(), 1);
7687 check_spends!(node_txn[2], revoked_local_txn[0]);
7689 // Each of the three justice transactions claim a separate (single) output of the three
7690 // available, which we check here:
7691 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7692 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7693 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7695 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7696 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7698 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7699 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7700 // a remote commitment tx has already been confirmed).
7701 check_spends!(node_txn[3], chan.3);
7703 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7704 // output, checked above).
7705 assert_eq!(node_txn[4].input.len(), 2);
7706 assert_eq!(node_txn[4].output.len(), 1);
7707 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7709 first = node_txn[4].txid();
7710 // Store both feerates for later comparison
7711 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7712 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7713 penalty_txn = vec![node_txn[2].clone()];
7717 // Connect one more block to see if bumped penalty are issued for HTLC txn
7718 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7719 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7720 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7721 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7723 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7724 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7726 check_spends!(node_txn[0], revoked_local_txn[0]);
7727 check_spends!(node_txn[1], revoked_local_txn[0]);
7728 // Note that these are both bogus - they spend outputs already claimed in block 129:
7729 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7730 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7732 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7733 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7739 // Few more blocks to confirm penalty txn
7740 connect_blocks(&nodes[0], 4);
7741 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7742 let header_144 = connect_blocks(&nodes[0], 9);
7744 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7745 assert_eq!(node_txn.len(), 1);
7747 assert_eq!(node_txn[0].input.len(), 2);
7748 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7749 // Verify bumped tx is different and 25% bump heuristic
7750 assert_ne!(first, node_txn[0].txid());
7751 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7752 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7753 assert!(feerate_2 * 100 > feerate_1 * 125);
7754 let txn = vec![node_txn[0].clone()];
7758 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7759 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7760 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7761 connect_blocks(&nodes[0], 20);
7763 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7764 // We verify than no new transaction has been broadcast because previously
7765 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7766 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7767 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7768 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7769 // up bumped justice generation.
7770 assert_eq!(node_txn.len(), 0);
7773 check_closed_broadcast!(nodes[0], true);
7774 check_added_monitors!(nodes[0], 1);
7778 fn test_bump_penalty_txn_on_remote_commitment() {
7779 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7780 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7783 // Provide preimage for one
7784 // Check aggregation
7786 let chanmon_cfgs = create_chanmon_cfgs(2);
7787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7789 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7791 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7792 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7793 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7795 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7796 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7797 assert_eq!(remote_txn[0].output.len(), 4);
7798 assert_eq!(remote_txn[0].input.len(), 1);
7799 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7801 // Claim a HTLC without revocation (provide B monitor with preimage)
7802 nodes[1].node.claim_funds(payment_preimage);
7803 mine_transaction(&nodes[1], &remote_txn[0]);
7804 check_added_monitors!(nodes[1], 2);
7805 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7807 // One or more claim tx should have been broadcast, check it
7811 let feerate_timeout;
7812 let feerate_preimage;
7814 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7815 // 9 transactions including:
7816 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7817 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7818 // 2 * HTLC-Success (one RBF bump we'll check later)
7820 assert_eq!(node_txn.len(), 8);
7821 assert_eq!(node_txn[0].input.len(), 1);
7822 assert_eq!(node_txn[6].input.len(), 1);
7823 check_spends!(node_txn[0], remote_txn[0]);
7824 check_spends!(node_txn[6], remote_txn[0]);
7825 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7826 preimage_bump = node_txn[3].clone();
7828 check_spends!(node_txn[1], chan.3);
7829 check_spends!(node_txn[2], node_txn[1]);
7830 assert_eq!(node_txn[1], node_txn[4]);
7831 assert_eq!(node_txn[2], node_txn[5]);
7833 timeout = node_txn[6].txid();
7834 let index = node_txn[6].input[0].previous_output.vout;
7835 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7836 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7838 preimage = node_txn[0].txid();
7839 let index = node_txn[0].input[0].previous_output.vout;
7840 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7841 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7845 assert_ne!(feerate_timeout, 0);
7846 assert_ne!(feerate_preimage, 0);
7848 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7849 connect_blocks(&nodes[1], 15);
7851 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7852 assert_eq!(node_txn.len(), 1);
7853 assert_eq!(node_txn[0].input.len(), 1);
7854 assert_eq!(preimage_bump.input.len(), 1);
7855 check_spends!(node_txn[0], remote_txn[0]);
7856 check_spends!(preimage_bump, remote_txn[0]);
7858 let index = preimage_bump.input[0].previous_output.vout;
7859 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7860 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7861 assert!(new_feerate * 100 > feerate_timeout * 125);
7862 assert_ne!(timeout, preimage_bump.txid());
7864 let index = node_txn[0].input[0].previous_output.vout;
7865 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7866 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7867 assert!(new_feerate * 100 > feerate_preimage * 125);
7868 assert_ne!(preimage, node_txn[0].txid());
7873 nodes[1].node.get_and_clear_pending_events();
7874 nodes[1].node.get_and_clear_pending_msg_events();
7878 fn test_counterparty_raa_skip_no_crash() {
7879 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7880 // commitment transaction, we would have happily carried on and provided them the next
7881 // commitment transaction based on one RAA forward. This would probably eventually have led to
7882 // channel closure, but it would not have resulted in funds loss. Still, our
7883 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7884 // check simply that the channel is closed in response to such an RAA, but don't check whether
7885 // we decide to punish our counterparty for revoking their funds (as we don't currently
7887 let chanmon_cfgs = create_chanmon_cfgs(2);
7888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7890 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7891 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7893 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7894 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7896 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7898 // Make signer believe we got a counterparty signature, so that it allows the revocation
7899 keys.get_enforcement_state().last_holder_commitment -= 1;
7900 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7902 // Must revoke without gaps
7903 keys.get_enforcement_state().last_holder_commitment -= 1;
7904 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7906 keys.get_enforcement_state().last_holder_commitment -= 1;
7907 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7908 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7910 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7911 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7912 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7913 check_added_monitors!(nodes[1], 1);
7914 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7918 fn test_bump_txn_sanitize_tracking_maps() {
7919 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7920 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7922 let chanmon_cfgs = create_chanmon_cfgs(2);
7923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7925 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7927 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7928 // Lock HTLC in both directions
7929 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7930 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7932 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7933 assert_eq!(revoked_local_txn[0].input.len(), 1);
7934 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7936 // Revoke local commitment tx
7937 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7939 // Broadcast set of revoked txn on A
7940 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7941 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7942 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7944 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7945 check_closed_broadcast!(nodes[0], true);
7946 check_added_monitors!(nodes[0], 1);
7947 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7949 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7950 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7951 check_spends!(node_txn[0], revoked_local_txn[0]);
7952 check_spends!(node_txn[1], revoked_local_txn[0]);
7953 check_spends!(node_txn[2], revoked_local_txn[0]);
7954 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7958 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7959 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7960 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7962 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7963 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7964 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7969 fn test_pending_claimed_htlc_no_balance_underflow() {
7970 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7971 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7972 let chanmon_cfgs = create_chanmon_cfgs(2);
7973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7975 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7976 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
7978 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1_010_000).0;
7979 nodes[1].node.claim_funds(payment_preimage);
7980 check_added_monitors!(nodes[1], 1);
7981 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7983 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7984 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7985 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7986 check_added_monitors!(nodes[0], 1);
7987 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7989 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7990 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7991 // can get our balance.
7993 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7994 // the public key of the only hop. This works around ChannelDetails not showing the
7995 // almost-claimed HTLC as available balance.
7996 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7997 route.payment_params = None; // This is all wrong, but unnecessary
7998 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7999 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
8000 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
8002 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
8006 fn test_channel_conf_timeout() {
8007 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8008 // confirm within 2016 blocks, as recommended by BOLT 2.
8009 let chanmon_cfgs = create_chanmon_cfgs(2);
8010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8012 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8014 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8016 // The outbound node should wait forever for confirmation:
8017 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8018 // copied here instead of directly referencing the constant.
8019 connect_blocks(&nodes[0], 2016);
8020 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8022 // The inbound node should fail the channel after exactly 2016 blocks
8023 connect_blocks(&nodes[1], 2015);
8024 check_added_monitors!(nodes[1], 0);
8025 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8027 connect_blocks(&nodes[1], 1);
8028 check_added_monitors!(nodes[1], 1);
8029 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8030 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8031 assert_eq!(close_ev.len(), 1);
8033 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8034 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8035 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8037 _ => panic!("Unexpected event"),
8042 fn test_override_channel_config() {
8043 let chanmon_cfgs = create_chanmon_cfgs(2);
8044 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8045 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8046 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8048 // Node0 initiates a channel to node1 using the override config.
8049 let mut override_config = UserConfig::default();
8050 override_config.own_channel_config.our_to_self_delay = 200;
8052 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8054 // Assert the channel created by node0 is using the override config.
8055 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8056 assert_eq!(res.channel_flags, 0);
8057 assert_eq!(res.to_self_delay, 200);
8061 fn test_override_0msat_htlc_minimum() {
8062 let mut zero_config = UserConfig::default();
8063 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8064 let chanmon_cfgs = create_chanmon_cfgs(2);
8065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8067 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8069 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8070 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8071 assert_eq!(res.htlc_minimum_msat, 1);
8073 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8074 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8075 assert_eq!(res.htlc_minimum_msat, 1);
8079 fn test_manually_accept_inbound_channel_request() {
8080 let mut manually_accept_conf = UserConfig::default();
8081 manually_accept_conf.manually_accept_inbound_channels = true;
8082 let chanmon_cfgs = create_chanmon_cfgs(2);
8083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8087 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8088 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8090 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8092 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8093 // accepting the inbound channel request.
8094 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8096 let events = nodes[1].node.get_and_clear_pending_events();
8098 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8099 nodes[1].node.accept_inbound_channel(&temporary_channel_id).unwrap();
8101 _ => panic!("Unexpected event"),
8104 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8105 assert_eq!(accept_msg_ev.len(), 1);
8107 match accept_msg_ev[0] {
8108 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8109 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8111 _ => panic!("Unexpected event"),
8116 fn test_manually_reject_inbound_channel_request() {
8117 let mut manually_accept_conf = UserConfig::default();
8118 manually_accept_conf.manually_accept_inbound_channels = true;
8119 let chanmon_cfgs = create_chanmon_cfgs(2);
8120 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8121 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8122 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8124 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8125 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8127 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8129 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8130 // rejecting the inbound channel request.
8131 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8133 let events = nodes[1].node.get_and_clear_pending_events();
8135 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8136 nodes[1].node.force_close_channel(&temporary_channel_id).unwrap();
8138 _ => panic!("Unexpected event"),
8141 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8142 assert_eq!(close_msg_ev.len(), 1);
8144 match close_msg_ev[0] {
8145 MessageSendEvent::HandleError { ref node_id, .. } => {
8146 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8148 _ => panic!("Unexpected event"),
8150 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8154 fn test_reject_funding_before_inbound_channel_accepted() {
8155 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
8156 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
8157 // the node operator before the counterparty sends a `FundingCreated` message. If a
8158 // `FundingCreated` message is received before the channel is accepted, it should be rejected
8159 // and the channel should be closed.
8160 let mut manually_accept_conf = UserConfig::default();
8161 manually_accept_conf.manually_accept_inbound_channels = true;
8162 let chanmon_cfgs = create_chanmon_cfgs(2);
8163 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8164 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8165 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8167 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8168 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8169 let temp_channel_id = res.temporary_channel_id;
8171 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8173 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
8174 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8176 // Clear the `Event::OpenChannelRequest` event without responding to the request.
8177 nodes[1].node.get_and_clear_pending_events();
8179 // Get the `AcceptChannel` message of `nodes[1]` without calling
8180 // `ChannelManager::accept_inbound_channel`, which generates a
8181 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
8182 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
8183 // succeed when `nodes[0]` is passed to it.
8186 let channel = get_channel_ref!(&nodes[1], lock, temp_channel_id);
8187 let accept_chan_msg = channel.get_accept_channel_message();
8188 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8191 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8193 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8194 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8196 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
8197 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8199 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8200 assert_eq!(close_msg_ev.len(), 1);
8202 let expected_err = "FundingCreated message received before the channel was accepted";
8203 match close_msg_ev[0] {
8204 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
8205 assert_eq!(msg.channel_id, temp_channel_id);
8206 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8207 assert_eq!(msg.data, expected_err);
8209 _ => panic!("Unexpected event"),
8212 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8216 fn test_can_not_accept_inbound_channel_twice() {
8217 let mut manually_accept_conf = UserConfig::default();
8218 manually_accept_conf.manually_accept_inbound_channels = true;
8219 let chanmon_cfgs = create_chanmon_cfgs(2);
8220 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8221 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8222 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8224 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
8225 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8227 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8229 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8230 // accepting the inbound channel request.
8231 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8233 let events = nodes[1].node.get_and_clear_pending_events();
8235 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8236 nodes[1].node.accept_inbound_channel(&temporary_channel_id).unwrap();
8237 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id);
8239 Err(APIError::APIMisuseError { err }) => {
8240 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
8242 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8243 Err(_) => panic!("Unexpected Error"),
8246 _ => panic!("Unexpected event"),
8249 // Ensure that the channel wasn't closed after attempting to accept it twice.
8250 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8251 assert_eq!(accept_msg_ev.len(), 1);
8253 match accept_msg_ev[0] {
8254 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8255 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8257 _ => panic!("Unexpected event"),
8262 fn test_can_not_accept_unknown_inbound_channel() {
8263 let chanmon_cfg = create_chanmon_cfgs(1);
8264 let node_cfg = create_node_cfgs(1, &chanmon_cfg);
8265 let node_chanmgr = create_node_chanmgrs(1, &node_cfg, &[None]);
8266 let node = create_network(1, &node_cfg, &node_chanmgr)[0].node;
8268 let unknown_channel_id = [0; 32];
8269 let api_res = node.accept_inbound_channel(&unknown_channel_id);
8271 Err(APIError::ChannelUnavailable { err }) => {
8272 assert_eq!(err, "Can't accept a channel that doesn't exist");
8274 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8275 Err(_) => panic!("Unexpected Error"),
8280 fn test_simple_mpp() {
8281 // Simple test of sending a multi-path payment.
8282 let chanmon_cfgs = create_chanmon_cfgs(4);
8283 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8284 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8285 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8287 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8288 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8289 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8290 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8292 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8293 let path = route.paths[0].clone();
8294 route.paths.push(path);
8295 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8296 route.paths[0][0].short_channel_id = chan_1_id;
8297 route.paths[0][1].short_channel_id = chan_3_id;
8298 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8299 route.paths[1][0].short_channel_id = chan_2_id;
8300 route.paths[1][1].short_channel_id = chan_4_id;
8301 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8302 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8306 fn test_preimage_storage() {
8307 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8308 let chanmon_cfgs = create_chanmon_cfgs(2);
8309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8311 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8313 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8316 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200).unwrap();
8317 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8318 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8319 check_added_monitors!(nodes[0], 1);
8320 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8321 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8323 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8325 // Note that after leaving the above scope we have no knowledge of any arguments or return
8326 // values from previous calls.
8327 expect_pending_htlcs_forwardable!(nodes[1]);
8328 let events = nodes[1].node.get_and_clear_pending_events();
8329 assert_eq!(events.len(), 1);
8331 Event::PaymentReceived { ref purpose, .. } => {
8333 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8334 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8336 _ => panic!("expected PaymentPurpose::InvoicePayment")
8339 _ => panic!("Unexpected event"),
8344 #[allow(deprecated)]
8345 fn test_secret_timeout() {
8346 // Simple test of payment secret storage time outs. After
8347 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8348 let chanmon_cfgs = create_chanmon_cfgs(2);
8349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8351 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8353 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8355 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8357 // We should fail to register the same payment hash twice, at least until we've connected a
8358 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8359 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8360 assert_eq!(err, "Duplicate payment hash");
8361 } else { panic!(); }
8363 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8365 header: BlockHeader {
8367 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8368 merkle_root: Default::default(),
8369 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8373 connect_block(&nodes[1], &block);
8374 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8375 assert_eq!(err, "Duplicate payment hash");
8376 } else { panic!(); }
8378 // If we then connect the second block, we should be able to register the same payment hash
8379 // again (this time getting a new payment secret).
8380 block.header.prev_blockhash = block.header.block_hash();
8381 block.header.time += 1;
8382 connect_block(&nodes[1], &block);
8383 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8384 assert_ne!(payment_secret_1, our_payment_secret);
8387 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8388 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8389 check_added_monitors!(nodes[0], 1);
8390 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8391 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8392 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8393 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8395 // Note that after leaving the above scope we have no knowledge of any arguments or return
8396 // values from previous calls.
8397 expect_pending_htlcs_forwardable!(nodes[1]);
8398 let events = nodes[1].node.get_and_clear_pending_events();
8399 assert_eq!(events.len(), 1);
8401 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8402 assert!(payment_preimage.is_none());
8403 assert_eq!(payment_secret, our_payment_secret);
8404 // We don't actually have the payment preimage with which to claim this payment!
8406 _ => panic!("Unexpected event"),
8411 fn test_bad_secret_hash() {
8412 // Simple test of unregistered payment hash/invalid payment secret handling
8413 let chanmon_cfgs = create_chanmon_cfgs(2);
8414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8416 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8418 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8420 let random_payment_hash = PaymentHash([42; 32]);
8421 let random_payment_secret = PaymentSecret([43; 32]);
8422 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2).unwrap();
8423 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8425 // All the below cases should end up being handled exactly identically, so we macro the
8426 // resulting events.
8427 macro_rules! handle_unknown_invalid_payment_data {
8429 check_added_monitors!(nodes[0], 1);
8430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8431 let payment_event = SendEvent::from_event(events.pop().unwrap());
8432 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8433 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8435 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8436 // again to process the pending backwards-failure of the HTLC
8437 expect_pending_htlcs_forwardable!(nodes[1]);
8438 expect_pending_htlcs_forwardable!(nodes[1]);
8439 check_added_monitors!(nodes[1], 1);
8441 // We should fail the payment back
8442 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8443 match events.pop().unwrap() {
8444 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8445 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8446 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8448 _ => panic!("Unexpected event"),
8453 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8454 // Error data is the HTLC value (100,000) and current block height
8455 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8457 // Send a payment with the right payment hash but the wrong payment secret
8458 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8459 handle_unknown_invalid_payment_data!();
8460 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8462 // Send a payment with a random payment hash, but the right payment secret
8463 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8464 handle_unknown_invalid_payment_data!();
8465 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8467 // Send a payment with a random payment hash and random payment secret
8468 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8469 handle_unknown_invalid_payment_data!();
8470 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8474 fn test_update_err_monitor_lockdown() {
8475 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8476 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8477 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8479 // This scenario may happen in a watchtower setup, where watchtower process a block height
8480 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8481 // commitment at same time.
8483 let chanmon_cfgs = create_chanmon_cfgs(2);
8484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8486 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8488 // Create some initial channel
8489 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8490 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8492 // Rebalance the network to generate htlc in the two directions
8493 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8495 // Route a HTLC from node 0 to node 1 (but don't settle)
8496 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8498 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8499 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8500 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8501 let persister = test_utils::TestPersister::new();
8503 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8504 let mut w = test_utils::TestVecWriter(Vec::new());
8505 monitor.write(&mut w).unwrap();
8506 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8507 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8508 assert!(new_monitor == *monitor);
8509 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);
8510 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8513 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8514 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8515 // transaction lock time requirements here.
8516 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8517 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8519 // Try to update ChannelMonitor
8520 assert!(nodes[1].node.claim_funds(preimage));
8521 check_added_monitors!(nodes[1], 1);
8522 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8523 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8524 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8525 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8526 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8527 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8528 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8529 } else { assert!(false); }
8530 } else { assert!(false); };
8531 // Our local monitor is in-sync and hasn't processed yet timeout
8532 check_added_monitors!(nodes[0], 1);
8533 let events = nodes[0].node.get_and_clear_pending_events();
8534 assert_eq!(events.len(), 1);
8538 fn test_concurrent_monitor_claim() {
8539 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8540 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8541 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8542 // state N+1 confirms. Alice claims output from state N+1.
8544 let chanmon_cfgs = create_chanmon_cfgs(2);
8545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8547 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8549 // Create some initial channel
8550 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8551 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8553 // Rebalance the network to generate htlc in the two directions
8554 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8556 // Route a HTLC from node 0 to node 1 (but don't settle)
8557 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8559 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8560 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8561 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8562 let persister = test_utils::TestPersister::new();
8563 let watchtower_alice = {
8564 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8565 let mut w = test_utils::TestVecWriter(Vec::new());
8566 monitor.write(&mut w).unwrap();
8567 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8568 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8569 assert!(new_monitor == *monitor);
8570 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);
8571 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8574 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8575 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8576 // transaction lock time requirements here.
8577 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8578 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8580 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8582 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8583 assert_eq!(txn.len(), 2);
8587 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8588 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8589 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8590 let persister = test_utils::TestPersister::new();
8591 let watchtower_bob = {
8592 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8593 let mut w = test_utils::TestVecWriter(Vec::new());
8594 monitor.write(&mut w).unwrap();
8595 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8596 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8597 assert!(new_monitor == *monitor);
8598 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);
8599 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8602 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8603 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8605 // Route another payment to generate another update with still previous HTLC pending
8606 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8608 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8610 check_added_monitors!(nodes[1], 1);
8612 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8613 assert_eq!(updates.update_add_htlcs.len(), 1);
8614 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8615 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8616 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8617 // Watchtower Alice should already have seen the block and reject the update
8618 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8619 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8620 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8621 } else { assert!(false); }
8622 } else { assert!(false); };
8623 // Our local monitor is in-sync and hasn't processed yet timeout
8624 check_added_monitors!(nodes[0], 1);
8626 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8627 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8628 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8630 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8633 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8634 assert_eq!(txn.len(), 2);
8635 bob_state_y = txn[0].clone();
8639 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8640 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8641 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);
8643 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8644 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8645 // the onchain detection of the HTLC output
8646 assert_eq!(htlc_txn.len(), 2);
8647 check_spends!(htlc_txn[0], bob_state_y);
8648 check_spends!(htlc_txn[1], bob_state_y);
8653 fn test_pre_lockin_no_chan_closed_update() {
8654 // Test that if a peer closes a channel in response to a funding_created message we don't
8655 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8658 // Doing so would imply a channel monitor update before the initial channel monitor
8659 // registration, violating our API guarantees.
8661 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8662 // then opening a second channel with the same funding output as the first (which is not
8663 // rejected because the first channel does not exist in the ChannelManager) and closing it
8664 // before receiving funding_signed.
8665 let chanmon_cfgs = create_chanmon_cfgs(2);
8666 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8667 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8668 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8670 // Create an initial channel
8671 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8672 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8673 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8674 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8675 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8677 // Move the first channel through the funding flow...
8678 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8680 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8681 check_added_monitors!(nodes[0], 0);
8683 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8684 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8685 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8686 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8687 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8691 fn test_htlc_no_detection() {
8692 // This test is a mutation to underscore the detection logic bug we had
8693 // before #653. HTLC value routed is above the remaining balance, thus
8694 // inverting HTLC and `to_remote` output. HTLC will come second and
8695 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8696 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8697 // outputs order detection for correct spending children filtring.
8699 let chanmon_cfgs = create_chanmon_cfgs(2);
8700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8704 // Create some initial channels
8705 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8707 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8708 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8709 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8710 assert_eq!(local_txn[0].input.len(), 1);
8711 assert_eq!(local_txn[0].output.len(), 3);
8712 check_spends!(local_txn[0], chan_1.3);
8714 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8715 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8716 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8717 // We deliberately connect the local tx twice as this should provoke a failure calling
8718 // this test before #653 fix.
8719 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);
8720 check_closed_broadcast!(nodes[0], true);
8721 check_added_monitors!(nodes[0], 1);
8722 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8723 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8725 let htlc_timeout = {
8726 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8727 assert_eq!(node_txn[1].input.len(), 1);
8728 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8729 check_spends!(node_txn[1], local_txn[0]);
8733 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8734 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8735 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8736 expect_payment_failed!(nodes[0], our_payment_hash, true);
8739 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8740 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8741 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8742 // Carol, Alice would be the upstream node, and Carol the downstream.)
8744 // Steps of the test:
8745 // 1) Alice sends a HTLC to Carol through Bob.
8746 // 2) Carol doesn't settle the HTLC.
8747 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8748 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8749 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8750 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8751 // 5) Carol release the preimage to Bob off-chain.
8752 // 6) Bob claims the offered output on the broadcasted commitment.
8753 let chanmon_cfgs = create_chanmon_cfgs(3);
8754 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8755 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8756 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8758 // Create some initial channels
8759 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8760 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8762 // Steps (1) and (2):
8763 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8764 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8766 // Check that Alice's commitment transaction now contains an output for this HTLC.
8767 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8768 check_spends!(alice_txn[0], chan_ab.3);
8769 assert_eq!(alice_txn[0].output.len(), 2);
8770 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8771 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8772 assert_eq!(alice_txn.len(), 2);
8774 // Steps (3) and (4):
8775 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8776 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8777 let mut force_closing_node = 0; // Alice force-closes
8778 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8779 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8780 check_closed_broadcast!(nodes[force_closing_node], true);
8781 check_added_monitors!(nodes[force_closing_node], 1);
8782 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8783 if go_onchain_before_fulfill {
8784 let txn_to_broadcast = match broadcast_alice {
8785 true => alice_txn.clone(),
8786 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8788 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8789 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8790 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8791 if broadcast_alice {
8792 check_closed_broadcast!(nodes[1], true);
8793 check_added_monitors!(nodes[1], 1);
8794 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8796 assert_eq!(bob_txn.len(), 1);
8797 check_spends!(bob_txn[0], chan_ab.3);
8801 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8802 // process of removing the HTLC from their commitment transactions.
8803 assert!(nodes[2].node.claim_funds(payment_preimage));
8804 check_added_monitors!(nodes[2], 1);
8805 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8806 assert!(carol_updates.update_add_htlcs.is_empty());
8807 assert!(carol_updates.update_fail_htlcs.is_empty());
8808 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8809 assert!(carol_updates.update_fee.is_none());
8810 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8812 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8813 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8814 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8815 if !go_onchain_before_fulfill && broadcast_alice {
8816 let events = nodes[1].node.get_and_clear_pending_msg_events();
8817 assert_eq!(events.len(), 1);
8819 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8820 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8822 _ => panic!("Unexpected event"),
8825 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8826 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8827 // Carol<->Bob's updated commitment transaction info.
8828 check_added_monitors!(nodes[1], 2);
8830 let events = nodes[1].node.get_and_clear_pending_msg_events();
8831 assert_eq!(events.len(), 2);
8832 let bob_revocation = match events[0] {
8833 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8834 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8837 _ => panic!("Unexpected event"),
8839 let bob_updates = match events[1] {
8840 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8841 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8844 _ => panic!("Unexpected event"),
8847 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8848 check_added_monitors!(nodes[2], 1);
8849 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8850 check_added_monitors!(nodes[2], 1);
8852 let events = nodes[2].node.get_and_clear_pending_msg_events();
8853 assert_eq!(events.len(), 1);
8854 let carol_revocation = match events[0] {
8855 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8856 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8859 _ => panic!("Unexpected event"),
8861 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8862 check_added_monitors!(nodes[1], 1);
8864 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8865 // here's where we put said channel's commitment tx on-chain.
8866 let mut txn_to_broadcast = alice_txn.clone();
8867 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8868 if !go_onchain_before_fulfill {
8869 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8870 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8871 // If Bob was the one to force-close, he will have already passed these checks earlier.
8872 if broadcast_alice {
8873 check_closed_broadcast!(nodes[1], true);
8874 check_added_monitors!(nodes[1], 1);
8875 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8877 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8878 if broadcast_alice {
8879 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8880 // new block being connected. The ChannelManager being notified triggers a monitor update,
8881 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8882 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8884 assert_eq!(bob_txn.len(), 3);
8885 check_spends!(bob_txn[1], chan_ab.3);
8887 assert_eq!(bob_txn.len(), 2);
8888 check_spends!(bob_txn[0], chan_ab.3);
8893 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8894 // broadcasted commitment transaction.
8896 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8897 if go_onchain_before_fulfill {
8898 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8899 assert_eq!(bob_txn.len(), 2);
8901 let script_weight = match broadcast_alice {
8902 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8903 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8905 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8906 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8907 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8908 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8909 if broadcast_alice && !go_onchain_before_fulfill {
8910 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8911 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8913 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8914 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8920 fn test_onchain_htlc_settlement_after_close() {
8921 do_test_onchain_htlc_settlement_after_close(true, true);
8922 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8923 do_test_onchain_htlc_settlement_after_close(true, false);
8924 do_test_onchain_htlc_settlement_after_close(false, false);
8928 fn test_duplicate_chan_id() {
8929 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8930 // already open we reject it and keep the old channel.
8932 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8933 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8934 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8935 // updating logic for the existing channel.
8936 let chanmon_cfgs = create_chanmon_cfgs(2);
8937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8939 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8941 // Create an initial channel
8942 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8943 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8944 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8945 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()));
8947 // Try to create a second channel with the same temporary_channel_id as the first and check
8948 // that it is rejected.
8949 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8951 let events = nodes[1].node.get_and_clear_pending_msg_events();
8952 assert_eq!(events.len(), 1);
8954 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8955 // Technically, at this point, nodes[1] would be justified in thinking both the
8956 // first (valid) and second (invalid) channels are closed, given they both have
8957 // the same non-temporary channel_id. However, currently we do not, so we just
8958 // move forward with it.
8959 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8960 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8962 _ => panic!("Unexpected event"),
8966 // Move the first channel through the funding flow...
8967 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8969 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8970 check_added_monitors!(nodes[0], 0);
8972 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8973 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8975 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8976 assert_eq!(added_monitors.len(), 1);
8977 assert_eq!(added_monitors[0].0, funding_output);
8978 added_monitors.clear();
8980 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8982 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8983 let channel_id = funding_outpoint.to_channel_id();
8985 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8988 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8989 // Technically this is allowed by the spec, but we don't support it and there's little reason
8990 // to. Still, it shouldn't cause any other issues.
8991 open_chan_msg.temporary_channel_id = channel_id;
8992 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8994 let events = nodes[1].node.get_and_clear_pending_msg_events();
8995 assert_eq!(events.len(), 1);
8997 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8998 // Technically, at this point, nodes[1] would be justified in thinking both
8999 // channels are closed, but currently we do not, so we just move forward with it.
9000 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9001 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9003 _ => panic!("Unexpected event"),
9007 // Now try to create a second channel which has a duplicate funding output.
9008 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9009 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9010 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9011 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()));
9012 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9014 let funding_created = {
9015 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9016 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9017 let logger = test_utils::TestLogger::new();
9018 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9020 check_added_monitors!(nodes[0], 0);
9021 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9022 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9023 // still needs to be cleared here.
9024 check_added_monitors!(nodes[1], 1);
9026 // ...still, nodes[1] will reject the duplicate channel.
9028 let events = nodes[1].node.get_and_clear_pending_msg_events();
9029 assert_eq!(events.len(), 1);
9031 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9032 // Technically, at this point, nodes[1] would be justified in thinking both
9033 // channels are closed, but currently we do not, so we just move forward with it.
9034 assert_eq!(msg.channel_id, channel_id);
9035 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9037 _ => panic!("Unexpected event"),
9041 // finally, finish creating the original channel and send a payment over it to make sure
9042 // everything is functional.
9043 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9045 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9046 assert_eq!(added_monitors.len(), 1);
9047 assert_eq!(added_monitors[0].0, funding_output);
9048 added_monitors.clear();
9051 let events_4 = nodes[0].node.get_and_clear_pending_events();
9052 assert_eq!(events_4.len(), 0);
9053 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9054 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9056 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9057 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9058 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9059 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9063 fn test_error_chans_closed() {
9064 // Test that we properly handle error messages, closing appropriate channels.
9066 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9067 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9068 // we can test various edge cases around it to ensure we don't regress.
9069 let chanmon_cfgs = create_chanmon_cfgs(3);
9070 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9071 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9072 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9074 // Create some initial channels
9075 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9076 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9077 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9079 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9080 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9081 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9083 // Closing a channel from a different peer has no effect
9084 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9085 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9087 // Closing one channel doesn't impact others
9088 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9089 check_added_monitors!(nodes[0], 1);
9090 check_closed_broadcast!(nodes[0], false);
9091 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9092 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9093 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9094 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);
9095 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);
9097 // A null channel ID should close all channels
9098 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9099 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9100 check_added_monitors!(nodes[0], 2);
9101 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9102 let events = nodes[0].node.get_and_clear_pending_msg_events();
9103 assert_eq!(events.len(), 2);
9105 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9106 assert_eq!(msg.contents.flags & 2, 2);
9108 _ => panic!("Unexpected event"),
9111 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9112 assert_eq!(msg.contents.flags & 2, 2);
9114 _ => panic!("Unexpected event"),
9116 // Note that at this point users of a standard PeerHandler will end up calling
9117 // peer_disconnected with no_connection_possible set to false, duplicating the
9118 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9119 // users with their own peer handling logic. We duplicate the call here, however.
9120 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9121 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9123 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9124 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9125 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9129 fn test_invalid_funding_tx() {
9130 // Test that we properly handle invalid funding transactions sent to us from a peer.
9132 // Previously, all other major lightning implementations had failed to properly sanitize
9133 // funding transactions from their counterparties, leading to a multi-implementation critical
9134 // security vulnerability (though we always sanitized properly, we've previously had
9135 // un-released crashes in the sanitization process).
9136 let chanmon_cfgs = create_chanmon_cfgs(2);
9137 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9138 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9139 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9141 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9142 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()));
9143 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()));
9145 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9146 for output in tx.output.iter_mut() {
9147 // Make the confirmed funding transaction have a bogus script_pubkey
9148 output.script_pubkey = bitcoin::Script::new();
9151 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9152 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()));
9153 check_added_monitors!(nodes[1], 1);
9155 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()));
9156 check_added_monitors!(nodes[0], 1);
9158 let events_1 = nodes[0].node.get_and_clear_pending_events();
9159 assert_eq!(events_1.len(), 0);
9161 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9162 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9163 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9165 let expected_err = "funding tx had wrong script/value or output index";
9166 confirm_transaction_at(&nodes[1], &tx, 1);
9167 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9168 check_added_monitors!(nodes[1], 1);
9169 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9170 assert_eq!(events_2.len(), 1);
9171 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9172 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9173 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9174 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9175 } else { panic!(); }
9176 } else { panic!(); }
9177 assert_eq!(nodes[1].node.list_channels().len(), 0);
9180 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9181 // In the first version of the chain::Confirm interface, after a refactor was made to not
9182 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9183 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9184 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9185 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9186 // spending transaction until height N+1 (or greater). This was due to the way
9187 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9188 // spending transaction at the height the input transaction was confirmed at, not whether we
9189 // should broadcast a spending transaction at the current height.
9190 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9191 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9192 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9193 // until we learned about an additional block.
9195 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9196 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9197 let chanmon_cfgs = create_chanmon_cfgs(3);
9198 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9199 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9200 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9201 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9203 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9204 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9205 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9206 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9207 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9209 nodes[1].node.force_close_channel(&channel_id).unwrap();
9210 check_closed_broadcast!(nodes[1], true);
9211 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9212 check_added_monitors!(nodes[1], 1);
9213 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9214 assert_eq!(node_txn.len(), 1);
9216 let conf_height = nodes[1].best_block_info().1;
9217 if !test_height_before_timelock {
9218 connect_blocks(&nodes[1], 24 * 6);
9220 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9221 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9222 if test_height_before_timelock {
9223 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9224 // generate any events or broadcast any transactions
9225 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9226 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9228 // We should broadcast an HTLC transaction spending our funding transaction first
9229 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9230 assert_eq!(spending_txn.len(), 2);
9231 assert_eq!(spending_txn[0], node_txn[0]);
9232 check_spends!(spending_txn[1], node_txn[0]);
9233 // We should also generate a SpendableOutputs event with the to_self output (as its
9235 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9236 assert_eq!(descriptor_spend_txn.len(), 1);
9238 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9239 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9240 // additional block built on top of the current chain.
9241 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9242 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9243 expect_pending_htlcs_forwardable!(nodes[1]);
9244 check_added_monitors!(nodes[1], 1);
9246 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9247 assert!(updates.update_add_htlcs.is_empty());
9248 assert!(updates.update_fulfill_htlcs.is_empty());
9249 assert_eq!(updates.update_fail_htlcs.len(), 1);
9250 assert!(updates.update_fail_malformed_htlcs.is_empty());
9251 assert!(updates.update_fee.is_none());
9252 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9253 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9254 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9259 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9260 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9261 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9265 fn test_forwardable_regen() {
9266 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9267 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9269 // We test it for both payment receipt and payment forwarding.
9271 let chanmon_cfgs = create_chanmon_cfgs(3);
9272 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9273 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9274 let persister: test_utils::TestPersister;
9275 let new_chain_monitor: test_utils::TestChainMonitor;
9276 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9277 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9278 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9279 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9281 // First send a payment to nodes[1]
9282 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9283 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9284 check_added_monitors!(nodes[0], 1);
9286 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9287 assert_eq!(events.len(), 1);
9288 let payment_event = SendEvent::from_event(events.pop().unwrap());
9289 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9290 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9292 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9294 // Next send a payment which is forwarded by nodes[1]
9295 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9296 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9297 check_added_monitors!(nodes[0], 1);
9299 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9300 assert_eq!(events.len(), 1);
9301 let payment_event = SendEvent::from_event(events.pop().unwrap());
9302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9303 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9305 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9307 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9309 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9310 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9311 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9313 let nodes_1_serialized = nodes[1].node.encode();
9314 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9315 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9316 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9317 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9319 persister = test_utils::TestPersister::new();
9320 let keys_manager = &chanmon_cfgs[1].keys_manager;
9321 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);
9322 nodes[1].chain_monitor = &new_chain_monitor;
9324 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9325 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9326 &mut chan_0_monitor_read, keys_manager).unwrap();
9327 assert!(chan_0_monitor_read.is_empty());
9328 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9329 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9330 &mut chan_1_monitor_read, keys_manager).unwrap();
9331 assert!(chan_1_monitor_read.is_empty());
9333 let mut nodes_1_read = &nodes_1_serialized[..];
9334 let (_, nodes_1_deserialized_tmp) = {
9335 let mut channel_monitors = HashMap::new();
9336 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9337 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9338 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9339 default_config: UserConfig::default(),
9341 fee_estimator: node_cfgs[1].fee_estimator,
9342 chain_monitor: nodes[1].chain_monitor,
9343 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9344 logger: nodes[1].logger,
9348 nodes_1_deserialized = nodes_1_deserialized_tmp;
9349 assert!(nodes_1_read.is_empty());
9351 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9352 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9353 nodes[1].node = &nodes_1_deserialized;
9354 check_added_monitors!(nodes[1], 2);
9356 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9357 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9358 // the commitment state.
9359 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9361 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9363 expect_pending_htlcs_forwardable!(nodes[1]);
9364 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9365 check_added_monitors!(nodes[1], 1);
9367 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9368 assert_eq!(events.len(), 1);
9369 let payment_event = SendEvent::from_event(events.pop().unwrap());
9370 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9371 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9372 expect_pending_htlcs_forwardable!(nodes[2]);
9373 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9375 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9376 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9380 fn test_dup_htlc_second_fail_panic() {
9381 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9382 // value for the payment, we'd fail back both HTLCs after generating a `PaymentReceived` event.
9383 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9384 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9385 let chanmon_cfgs = create_chanmon_cfgs(2);
9386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9390 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9392 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())
9393 .with_features(InvoiceFeatures::known());
9394 let scorer = test_utils::TestScorer::with_penalty(0);
9395 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9396 let route = get_route(
9397 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
9398 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
9399 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9401 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9404 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9405 check_added_monitors!(nodes[0], 1);
9406 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9407 assert_eq!(events.len(), 1);
9408 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9409 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9410 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9412 expect_pending_htlcs_forwardable!(nodes[1]);
9413 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9416 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
9417 check_added_monitors!(nodes[0], 1);
9418 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9419 assert_eq!(events.len(), 1);
9420 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9421 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9422 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9423 // At this point, nodes[1] would notice it has too much value for the payment. It will
9424 // assume the second is a privacy attack (no longer particularly relevant
9425 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9426 // the first HTLC delivered above.
9429 // Now we go fail back the first HTLC from the user end.
9430 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9431 nodes[1].node.process_pending_htlc_forwards();
9432 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9434 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9435 nodes[1].node.process_pending_htlc_forwards();
9437 check_added_monitors!(nodes[1], 1);
9438 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9439 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9441 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9442 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9443 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9445 let failure_events = nodes[0].node.get_and_clear_pending_events();
9446 assert_eq!(failure_events.len(), 2);
9447 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9448 if let Event::PaymentPathFailed { .. } = failure_events[1] {} else { panic!(); }
9452 fn test_keysend_payments_to_public_node() {
9453 let chanmon_cfgs = create_chanmon_cfgs(2);
9454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9456 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9458 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9459 let network_graph = nodes[0].network_graph;
9460 let payer_pubkey = nodes[0].node.get_our_node_id();
9461 let payee_pubkey = nodes[1].node.get_our_node_id();
9462 let route_params = RouteParameters {
9463 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9464 final_value_msat: 10000,
9465 final_cltv_expiry_delta: 40,
9467 let scorer = test_utils::TestScorer::with_penalty(0);
9468 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9469 let route = find_route(&payer_pubkey, &route_params, network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9471 let test_preimage = PaymentPreimage([42; 32]);
9472 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9473 check_added_monitors!(nodes[0], 1);
9474 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9475 assert_eq!(events.len(), 1);
9476 let event = events.pop().unwrap();
9477 let path = vec![&nodes[1]];
9478 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9479 claim_payment(&nodes[0], &path, test_preimage);
9483 fn test_keysend_payments_to_private_node() {
9484 let chanmon_cfgs = create_chanmon_cfgs(2);
9485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9487 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9489 let payer_pubkey = nodes[0].node.get_our_node_id();
9490 let payee_pubkey = nodes[1].node.get_our_node_id();
9491 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9492 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9494 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9495 let route_params = RouteParameters {
9496 payment_params: PaymentParameters::for_keysend(payee_pubkey),
9497 final_value_msat: 10000,
9498 final_cltv_expiry_delta: 40,
9500 let network_graph = nodes[0].network_graph;
9501 let first_hops = nodes[0].node.list_usable_channels();
9502 let scorer = test_utils::TestScorer::with_penalty(0);
9503 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9504 let route = find_route(
9505 &payer_pubkey, &route_params, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9506 nodes[0].logger, &scorer, &random_seed_bytes
9509 let test_preimage = PaymentPreimage([42; 32]);
9510 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9511 check_added_monitors!(nodes[0], 1);
9512 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9513 assert_eq!(events.len(), 1);
9514 let event = events.pop().unwrap();
9515 let path = vec![&nodes[1]];
9516 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9517 claim_payment(&nodes[0], &path, test_preimage);
9520 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9521 #[derive(Clone, Copy, PartialEq)]
9522 enum ExposureEvent {
9523 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9525 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9527 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9528 AtUpdateFeeOutbound,
9531 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9532 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9535 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9536 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9537 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9538 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9539 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9540 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9541 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9542 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9544 let chanmon_cfgs = create_chanmon_cfgs(2);
9545 let mut config = test_default_channel_config();
9546 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9547 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9548 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9549 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9551 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9552 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9553 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9554 open_channel.max_accepted_htlcs = 60;
9556 open_channel.dust_limit_satoshis = 546;
9558 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9559 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9560 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9562 let opt_anchors = false;
9564 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9567 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9568 chan.holder_dust_limit_satoshis = 546;
9572 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9573 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()));
9574 check_added_monitors!(nodes[1], 1);
9576 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()));
9577 check_added_monitors!(nodes[0], 1);
9579 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9580 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9581 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9583 let dust_buffer_feerate = {
9584 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9585 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9586 chan.get_dust_buffer_feerate(None) as u64
9588 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;
9589 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9591 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;
9592 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9594 let dust_htlc_on_counterparty_tx: u64 = 25;
9595 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9598 if dust_outbound_balance {
9599 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9600 // Outbound dust balance: 4372 sats
9601 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9602 for i in 0..dust_outbound_htlc_on_holder_tx {
9603 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9604 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9607 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9608 // Inbound dust balance: 4372 sats
9609 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9610 for _ in 0..dust_inbound_htlc_on_holder_tx {
9611 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9615 if dust_outbound_balance {
9616 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9617 // Outbound dust balance: 5000 sats
9618 for i in 0..dust_htlc_on_counterparty_tx {
9619 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9620 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9623 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9624 // Inbound dust balance: 5000 sats
9625 for _ in 0..dust_htlc_on_counterparty_tx {
9626 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9631 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9632 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9633 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 });
9634 let mut config = UserConfig::default();
9635 // With default dust exposure: 5000 sats
9637 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9638 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9639 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)));
9641 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)));
9643 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9644 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 });
9645 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9646 check_added_monitors!(nodes[1], 1);
9647 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9648 assert_eq!(events.len(), 1);
9649 let payment_event = SendEvent::from_event(events.remove(0));
9650 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9651 // With default dust exposure: 5000 sats
9653 // Outbound dust balance: 6399 sats
9654 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9655 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9656 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);
9658 // Outbound dust balance: 5200 sats
9659 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);
9661 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9662 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9663 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9665 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9666 *feerate_lock = *feerate_lock * 10;
9668 nodes[0].node.timer_tick_occurred();
9669 check_added_monitors!(nodes[0], 1);
9670 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);
9673 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9674 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9675 added_monitors.clear();
9679 fn test_max_dust_htlc_exposure() {
9680 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9681 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9682 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9683 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9684 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9685 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9686 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9687 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9688 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9689 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9690 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9691 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);