1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::BaseSign;
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, HTLCOutputInCommitment};
26 use routing::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Payee, Route, RouteHop, RouteHint, RouteHintHop, RouteParameters, find_route, get_route};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hash_types::BlockHash;
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
45 use bitcoin::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::Hash;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use sync::{Arc, Mutex};
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
63 fn test_insane_channel_opens() {
64 // Stand up a network of 2 nodes
65 let chanmon_cfgs = create_chanmon_cfgs(2);
66 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
67 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
68 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
70 // Instantiate channel parameters where we push the maximum msats given our
72 let channel_value_sat = 31337; // same as funding satoshis
73 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
74 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
76 // Have node0 initiate a channel to node1 with aforementioned parameters
77 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
79 // Extract the channel open message from node0 to node1
80 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
82 // Test helper that asserts we get the correct error string given a mutator
83 // that supposedly makes the channel open message insane
84 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
85 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
86 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
87 assert_eq!(msg_events.len(), 1);
88 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
89 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
91 &ErrorAction::SendErrorMessage { .. } => {
92 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
94 _ => panic!("unexpected event!"),
96 } else { assert!(false); }
99 use ln::channel::MAX_FUNDING_SATOSHIS;
100 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102 // Test all mutations that would make the channel open message insane
103 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 });
105 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
107 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 });
109 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
111 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
113 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 });
115 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 });
117 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 fn test_async_inbound_update_fee() {
124 let chanmon_cfgs = create_chanmon_cfgs(2);
125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
127 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
128 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
131 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
135 // send (1) commitment_signed -.
136 // <- update_add_htlc/commitment_signed
137 // send (2) RAA (awaiting remote revoke) -.
138 // (1) commitment_signed is delivered ->
139 // .- send (3) RAA (awaiting remote revoke)
140 // (2) RAA is delivered ->
141 // .- send (4) commitment_signed
142 // <- (3) RAA is delivered
143 // send (5) commitment_signed -.
144 // <- (4) commitment_signed is delivered
146 // (5) commitment_signed is delivered ->
148 // (6) RAA is delivered ->
150 // First nodes[0] generates an update_fee
152 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
155 nodes[0].node.timer_tick_occurred();
156 check_added_monitors!(nodes[0], 1);
158 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events_0.len(), 1);
160 let (update_msg, commitment_signed) = match events_0[0] { // (1)
161 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162 (update_fee.as_ref(), commitment_signed)
164 _ => panic!("Unexpected event"),
167 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
171 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
172 check_added_monitors!(nodes[1], 1);
174 let payment_event = {
175 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
176 assert_eq!(events_1.len(), 1);
177 SendEvent::from_event(events_1.remove(0))
179 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
180 assert_eq!(payment_event.msgs.len(), 1);
182 // ...now when the messages get delivered everyone should be happy
183 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
185 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
186 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
187 check_added_monitors!(nodes[0], 1);
189 // deliver(1), generate (3):
190 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
191 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
192 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
193 check_added_monitors!(nodes[1], 1);
195 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
196 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
197 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
198 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
199 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fee.is_none()); // (4)
202 check_added_monitors!(nodes[1], 1);
204 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
205 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
206 assert!(as_update.update_add_htlcs.is_empty()); // (5)
207 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
208 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fee.is_none()); // (5)
211 check_added_monitors!(nodes[0], 1);
213 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
214 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
215 // only (6) so get_event_msg's assert(len == 1) passes
216 check_added_monitors!(nodes[0], 1);
218 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
219 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
220 check_added_monitors!(nodes[1], 1);
222 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
223 check_added_monitors!(nodes[0], 1);
225 let events_2 = nodes[0].node.get_and_clear_pending_events();
226 assert_eq!(events_2.len(), 1);
228 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
229 _ => panic!("Unexpected event"),
232 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
233 check_added_monitors!(nodes[1], 1);
237 fn test_update_fee_unordered_raa() {
238 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
239 // crash in an earlier version of the update_fee patch)
240 let chanmon_cfgs = create_chanmon_cfgs(2);
241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
243 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
244 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
249 // First nodes[0] generates an update_fee
251 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
254 nodes[0].node.timer_tick_occurred();
255 check_added_monitors!(nodes[0], 1);
257 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258 assert_eq!(events_0.len(), 1);
259 let update_msg = match events_0[0] { // (1)
260 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
263 _ => panic!("Unexpected event"),
266 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
268 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
270 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
271 check_added_monitors!(nodes[1], 1);
273 let payment_event = {
274 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275 assert_eq!(events_1.len(), 1);
276 SendEvent::from_event(events_1.remove(0))
278 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279 assert_eq!(payment_event.msgs.len(), 1);
281 // ...now when the messages get delivered everyone should be happy
282 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286 check_added_monitors!(nodes[0], 1);
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289 check_added_monitors!(nodes[1], 1);
291 // We can't continue, sadly, because our (1) now has a bogus signature
295 fn test_multi_flight_update_fee() {
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
303 // update_fee/commitment_signed ->
304 // .- send (1) RAA and (2) commitment_signed
305 // update_fee (never committed) ->
307 // We have to manually generate the above update_fee, it is allowed by the protocol but we
308 // don't track which updates correspond to which revoke_and_ack responses so we're in
309 // AwaitingRAA mode and will not generate the update_fee yet.
310 // <- (1) RAA delivered
311 // (3) is generated and send (4) CS -.
312 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
313 // know the per_commitment_point to use for it.
314 // <- (2) commitment_signed delivered
316 // B should send no response here
317 // (4) commitment_signed delivered ->
318 // <- RAA/commitment_signed delivered
321 // First nodes[0] generates an update_fee
324 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
325 initial_feerate = *feerate_lock;
326 *feerate_lock = initial_feerate + 20;
328 nodes[0].node.timer_tick_occurred();
329 check_added_monitors!(nodes[0], 1);
331 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
332 assert_eq!(events_0.len(), 1);
333 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
334 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
335 (update_fee.as_ref().unwrap(), commitment_signed)
337 _ => panic!("Unexpected event"),
340 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
341 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
342 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
343 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
344 check_added_monitors!(nodes[1], 1);
346 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
349 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
350 *feerate_lock = initial_feerate + 40;
352 nodes[0].node.timer_tick_occurred();
353 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356 // Create the (3) update_fee message that nodes[0] will generate before it does...
357 let mut update_msg_2 = msgs::UpdateFee {
358 channel_id: update_msg_1.channel_id.clone(),
359 feerate_per_kw: (initial_feerate + 30) as u32,
362 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
364 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
366 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
368 // Deliver (1), generating (3) and (4)
369 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
370 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
371 check_added_monitors!(nodes[0], 1);
372 assert!(as_second_update.update_add_htlcs.is_empty());
373 assert!(as_second_update.update_fulfill_htlcs.is_empty());
374 assert!(as_second_update.update_fail_htlcs.is_empty());
375 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
376 // Check that the update_fee newly generated matches what we delivered:
377 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
378 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
380 // Deliver (2) commitment_signed
381 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
382 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383 check_added_monitors!(nodes[0], 1);
384 // No commitment_signed so get_event_msg's assert(len == 1) passes
386 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
387 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388 check_added_monitors!(nodes[1], 1);
391 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
392 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
393 check_added_monitors!(nodes[1], 1);
395 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
396 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
397 check_added_monitors!(nodes[0], 1);
399 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
400 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
401 // No commitment_signed so get_event_msg's assert(len == 1) passes
402 check_added_monitors!(nodes[0], 1);
404 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
405 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
406 check_added_monitors!(nodes[1], 1);
409 fn do_test_1_conf_open(connect_style: ConnectStyle) {
410 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
411 // tests that we properly send one in that case.
412 let mut alice_config = UserConfig::default();
413 alice_config.own_channel_config.minimum_depth = 1;
414 alice_config.channel_options.announced_channel = true;
415 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
416 let mut bob_config = UserConfig::default();
417 bob_config.own_channel_config.minimum_depth = 1;
418 bob_config.channel_options.announced_channel = true;
419 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
420 let chanmon_cfgs = create_chanmon_cfgs(2);
421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
423 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
424 *nodes[0].connect_style.borrow_mut() = connect_style;
426 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
427 mine_transaction(&nodes[1], &tx);
428 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
430 mine_transaction(&nodes[0], &tx);
431 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
432 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
435 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
436 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
437 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
441 fn test_1_conf_open() {
442 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
443 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
444 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
447 fn do_test_sanity_on_in_flight_opens(steps: u8) {
448 // Previously, we had issues deserializing channels when we hadn't connected the first block
449 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
450 // serialization round-trips and simply do steps towards opening a channel and then drop the
453 let chanmon_cfgs = create_chanmon_cfgs(2);
454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
456 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
458 if steps & 0b1000_0000 != 0{
460 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
463 connect_block(&nodes[0], &block);
464 connect_block(&nodes[1], &block);
467 if steps & 0x0f == 0 { return; }
468 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
469 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
471 if steps & 0x0f == 1 { return; }
472 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
473 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
475 if steps & 0x0f == 2 { return; }
476 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
478 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
480 if steps & 0x0f == 3 { return; }
481 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
482 check_added_monitors!(nodes[0], 0);
483 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
485 if steps & 0x0f == 4 { return; }
486 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
488 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
489 assert_eq!(added_monitors.len(), 1);
490 assert_eq!(added_monitors[0].0, funding_output);
491 added_monitors.clear();
493 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
495 if steps & 0x0f == 5 { return; }
496 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
498 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
499 assert_eq!(added_monitors.len(), 1);
500 assert_eq!(added_monitors[0].0, funding_output);
501 added_monitors.clear();
504 let events_4 = nodes[0].node.get_and_clear_pending_events();
505 assert_eq!(events_4.len(), 0);
507 if steps & 0x0f == 6 { return; }
508 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
510 if steps & 0x0f == 7 { return; }
511 confirm_transaction_at(&nodes[0], &tx, 2);
512 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
513 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
517 fn test_sanity_on_in_flight_opens() {
518 do_test_sanity_on_in_flight_opens(0);
519 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(1);
521 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(2);
523 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(3);
525 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(4);
527 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
528 do_test_sanity_on_in_flight_opens(5);
529 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
530 do_test_sanity_on_in_flight_opens(6);
531 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
532 do_test_sanity_on_in_flight_opens(7);
533 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
534 do_test_sanity_on_in_flight_opens(8);
535 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
539 fn test_update_fee_vanilla() {
540 let chanmon_cfgs = create_chanmon_cfgs(2);
541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
543 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
544 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
547 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
550 nodes[0].node.timer_tick_occurred();
551 check_added_monitors!(nodes[0], 1);
553 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
554 assert_eq!(events_0.len(), 1);
555 let (update_msg, commitment_signed) = match events_0[0] {
556 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 } } => {
557 (update_fee.as_ref(), commitment_signed)
559 _ => panic!("Unexpected event"),
561 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
563 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
564 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
565 check_added_monitors!(nodes[1], 1);
567 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
568 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
569 check_added_monitors!(nodes[0], 1);
571 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
572 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
573 // No commitment_signed so get_event_msg's assert(len == 1) passes
574 check_added_monitors!(nodes[0], 1);
576 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
577 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
578 check_added_monitors!(nodes[1], 1);
582 fn test_update_fee_that_funder_cannot_afford() {
583 let chanmon_cfgs = create_chanmon_cfgs(2);
584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587 let channel_value = 5000;
589 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
590 let channel_id = chan.2;
591 let secp_ctx = Secp256k1::new();
592 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
594 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
595 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
596 // calculate two different feerates here - the expected local limit as well as the expected
598 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (COMMITMENT_TX_BASE_WEIGHT + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
599 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / COMMITMENT_TX_BASE_WEIGHT) as u32;
601 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
602 *feerate_lock = feerate;
604 nodes[0].node.timer_tick_occurred();
605 check_added_monitors!(nodes[0], 1);
606 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
608 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
610 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
612 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
614 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
616 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
617 assert_eq!(commitment_tx.output.len(), 2);
618 let total_fee: u64 = commit_tx_fee_msat(feerate, 0) / 1000;
619 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
620 actual_fee = channel_value - actual_fee;
621 assert_eq!(total_fee, actual_fee);
625 // Increment the feerate by a small constant, accounting for rounding errors
626 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
629 nodes[0].node.timer_tick_occurred();
630 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
631 check_added_monitors!(nodes[0], 0);
633 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
635 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
636 // needed to sign the new commitment tx and (2) sign the new commitment tx.
637 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
638 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
639 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
640 let chan_signer = local_chan.get_signer();
641 let pubkeys = chan_signer.pubkeys();
642 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
643 pubkeys.funding_pubkey)
645 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
646 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
647 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
648 let chan_signer = remote_chan.get_signer();
649 let pubkeys = chan_signer.pubkeys();
650 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
651 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
652 pubkeys.funding_pubkey)
655 // Assemble the set of keys we can use for signatures for our commitment_signed message.
656 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
657 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
660 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
661 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
662 let local_chan_signer = local_chan.get_signer();
663 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
664 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
665 INITIAL_COMMITMENT_NUMBER - 1,
667 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0) / 1000,
668 false, local_funding, remote_funding,
669 commit_tx_keys.clone(),
670 non_buffer_feerate + 4,
672 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
674 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
677 let commit_signed_msg = msgs::CommitmentSigned {
680 htlc_signatures: res.1
683 let update_fee = msgs::UpdateFee {
685 feerate_per_kw: non_buffer_feerate + 4,
688 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
690 //While producing the commitment_signed response after handling a received update_fee request the
691 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
692 //Should produce and error.
693 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
694 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
695 check_added_monitors!(nodes[1], 1);
696 check_closed_broadcast!(nodes[1], true);
697 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
701 fn test_update_fee_with_fundee_update_add_htlc() {
702 let chanmon_cfgs = create_chanmon_cfgs(2);
703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
705 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
706 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
709 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
712 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
715 nodes[0].node.timer_tick_occurred();
716 check_added_monitors!(nodes[0], 1);
718 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
719 assert_eq!(events_0.len(), 1);
720 let (update_msg, commitment_signed) = match events_0[0] {
721 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 } } => {
722 (update_fee.as_ref(), commitment_signed)
724 _ => panic!("Unexpected event"),
726 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
727 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
728 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
729 check_added_monitors!(nodes[1], 1);
731 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
733 // nothing happens since node[1] is in AwaitingRemoteRevoke
734 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
736 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
737 assert_eq!(added_monitors.len(), 0);
738 added_monitors.clear();
740 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
741 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
742 // node[1] has nothing to do
744 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
745 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
746 check_added_monitors!(nodes[0], 1);
748 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
749 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
750 // No commitment_signed so get_event_msg's assert(len == 1) passes
751 check_added_monitors!(nodes[0], 1);
752 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
753 check_added_monitors!(nodes[1], 1);
754 // AwaitingRemoteRevoke ends here
756 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
757 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
758 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
759 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
760 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
761 assert_eq!(commitment_update.update_fee.is_none(), true);
763 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
764 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
765 check_added_monitors!(nodes[0], 1);
766 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
768 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
769 check_added_monitors!(nodes[1], 1);
770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
772 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
773 check_added_monitors!(nodes[1], 1);
774 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
775 // No commitment_signed so get_event_msg's assert(len == 1) passes
777 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
778 check_added_monitors!(nodes[0], 1);
779 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
781 expect_pending_htlcs_forwardable!(nodes[0]);
783 let events = nodes[0].node.get_and_clear_pending_events();
784 assert_eq!(events.len(), 1);
786 Event::PaymentReceived { .. } => { },
787 _ => panic!("Unexpected event"),
790 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
792 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
793 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
794 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
795 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
796 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
800 fn test_update_fee() {
801 let chanmon_cfgs = create_chanmon_cfgs(2);
802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
805 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
806 let channel_id = chan.2;
809 // (1) update_fee/commitment_signed ->
810 // <- (2) revoke_and_ack
811 // .- send (3) commitment_signed
812 // (4) update_fee/commitment_signed ->
813 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
814 // <- (3) commitment_signed delivered
815 // send (6) revoke_and_ack -.
816 // <- (5) deliver revoke_and_ack
817 // (6) deliver revoke_and_ack ->
818 // .- send (7) commitment_signed in response to (4)
819 // <- (7) deliver commitment_signed
822 // Create and deliver (1)...
825 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
826 feerate = *feerate_lock;
827 *feerate_lock = feerate + 20;
829 nodes[0].node.timer_tick_occurred();
830 check_added_monitors!(nodes[0], 1);
832 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
833 assert_eq!(events_0.len(), 1);
834 let (update_msg, commitment_signed) = match events_0[0] {
835 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 } } => {
836 (update_fee.as_ref(), commitment_signed)
838 _ => panic!("Unexpected event"),
840 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
842 // Generate (2) and (3):
843 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
844 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
845 check_added_monitors!(nodes[1], 1);
848 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
849 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
850 check_added_monitors!(nodes[0], 1);
852 // Create and deliver (4)...
854 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
855 *feerate_lock = feerate + 30;
857 nodes[0].node.timer_tick_occurred();
858 check_added_monitors!(nodes[0], 1);
859 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
860 assert_eq!(events_0.len(), 1);
861 let (update_msg, commitment_signed) = match events_0[0] {
862 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 } } => {
863 (update_fee.as_ref(), commitment_signed)
865 _ => panic!("Unexpected event"),
868 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
869 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
870 check_added_monitors!(nodes[1], 1);
872 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
873 // No commitment_signed so get_event_msg's assert(len == 1) passes
875 // Handle (3), creating (6):
876 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
877 check_added_monitors!(nodes[0], 1);
878 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
879 // No commitment_signed so get_event_msg's assert(len == 1) passes
882 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
883 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
884 check_added_monitors!(nodes[0], 1);
886 // Deliver (6), creating (7):
887 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
888 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889 assert!(commitment_update.update_add_htlcs.is_empty());
890 assert!(commitment_update.update_fulfill_htlcs.is_empty());
891 assert!(commitment_update.update_fail_htlcs.is_empty());
892 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
893 assert!(commitment_update.update_fee.is_none());
894 check_added_monitors!(nodes[1], 1);
897 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
898 check_added_monitors!(nodes[0], 1);
899 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
900 // No commitment_signed so get_event_msg's assert(len == 1) passes
902 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
903 check_added_monitors!(nodes[1], 1);
904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
906 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
907 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
908 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
909 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
910 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
914 fn fake_network_test() {
915 // Simple test which builds a network of ChannelManagers, connects them to each other, and
916 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
917 let chanmon_cfgs = create_chanmon_cfgs(4);
918 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
919 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
920 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
922 // Create some initial channels
923 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
924 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
925 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
927 // Rebalance the network a bit by relaying one payment through all the channels...
928 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
929 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
930 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
931 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
933 // Send some more payments
934 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
935 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
936 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
938 // Test failure packets
939 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
940 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
942 // Add a new channel that skips 3
943 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
945 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
946 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
947 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
948 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
949 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
950 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
951 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
953 // Do some rebalance loop payments, simultaneously
954 let mut hops = Vec::with_capacity(3);
956 pubkey: nodes[2].node.get_our_node_id(),
957 node_features: NodeFeatures::empty(),
958 short_channel_id: chan_2.0.contents.short_channel_id,
959 channel_features: ChannelFeatures::empty(),
961 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
964 pubkey: nodes[3].node.get_our_node_id(),
965 node_features: NodeFeatures::empty(),
966 short_channel_id: chan_3.0.contents.short_channel_id,
967 channel_features: ChannelFeatures::empty(),
969 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
972 pubkey: nodes[1].node.get_our_node_id(),
973 node_features: NodeFeatures::known(),
974 short_channel_id: chan_4.0.contents.short_channel_id,
975 channel_features: ChannelFeatures::known(),
977 cltv_expiry_delta: TEST_FINAL_CLTV,
979 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;
980 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;
981 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
983 let mut hops = Vec::with_capacity(3);
985 pubkey: nodes[3].node.get_our_node_id(),
986 node_features: NodeFeatures::empty(),
987 short_channel_id: chan_4.0.contents.short_channel_id,
988 channel_features: ChannelFeatures::empty(),
990 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
993 pubkey: nodes[2].node.get_our_node_id(),
994 node_features: NodeFeatures::empty(),
995 short_channel_id: chan_3.0.contents.short_channel_id,
996 channel_features: ChannelFeatures::empty(),
998 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1000 hops.push(RouteHop {
1001 pubkey: nodes[1].node.get_our_node_id(),
1002 node_features: NodeFeatures::known(),
1003 short_channel_id: chan_2.0.contents.short_channel_id,
1004 channel_features: ChannelFeatures::known(),
1006 cltv_expiry_delta: TEST_FINAL_CLTV,
1008 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;
1009 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;
1010 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1012 // Claim the rebalances...
1013 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1014 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1016 // Add a duplicate new channel from 2 to 4
1017 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1019 // Send some payments across both channels
1020 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1021 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1022 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1025 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1026 let events = nodes[0].node.get_and_clear_pending_msg_events();
1027 assert_eq!(events.len(), 0);
1028 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);
1030 //TODO: Test that routes work again here as we've been notified that the channel is full
1032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1033 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1034 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1036 // Close down the channels...
1037 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1038 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1039 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1040 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1041 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1042 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1043 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1044 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1045 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1046 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1047 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1048 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1049 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1050 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1051 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1055 fn holding_cell_htlc_counting() {
1056 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1057 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1058 // commitment dance rounds.
1059 let chanmon_cfgs = create_chanmon_cfgs(3);
1060 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1061 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1062 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1063 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1064 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1066 let mut payments = Vec::new();
1067 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1068 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1069 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1070 payments.push((payment_preimage, payment_hash));
1072 check_added_monitors!(nodes[1], 1);
1074 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1075 assert_eq!(events.len(), 1);
1076 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1077 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1079 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1080 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1082 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1084 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1085 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1086 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1087 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1090 // This should also be true if we try to forward a payment.
1091 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1093 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1094 check_added_monitors!(nodes[0], 1);
1097 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1098 assert_eq!(events.len(), 1);
1099 let payment_event = SendEvent::from_event(events.pop().unwrap());
1100 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1102 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1103 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1104 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1105 // fails), the second will process the resulting failure and fail the HTLC backward.
1106 expect_pending_htlcs_forwardable!(nodes[1]);
1107 expect_pending_htlcs_forwardable!(nodes[1]);
1108 check_added_monitors!(nodes[1], 1);
1110 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1111 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1112 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1114 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1116 // Now forward all the pending HTLCs and claim them back
1117 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1118 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1119 check_added_monitors!(nodes[2], 1);
1121 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1122 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1123 check_added_monitors!(nodes[1], 1);
1124 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1126 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1127 check_added_monitors!(nodes[1], 1);
1128 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1130 for ref update in as_updates.update_add_htlcs.iter() {
1131 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1133 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1134 check_added_monitors!(nodes[2], 1);
1135 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1136 check_added_monitors!(nodes[2], 1);
1137 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1139 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1140 check_added_monitors!(nodes[1], 1);
1141 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1142 check_added_monitors!(nodes[1], 1);
1143 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1145 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1146 check_added_monitors!(nodes[2], 1);
1148 expect_pending_htlcs_forwardable!(nodes[2]);
1150 let events = nodes[2].node.get_and_clear_pending_events();
1151 assert_eq!(events.len(), payments.len());
1152 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1154 &Event::PaymentReceived { ref payment_hash, .. } => {
1155 assert_eq!(*payment_hash, *hash);
1157 _ => panic!("Unexpected event"),
1161 for (preimage, _) in payments.drain(..) {
1162 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1165 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1169 fn duplicate_htlc_test() {
1170 // Test that we accept duplicate payment_hash HTLCs across the network and that
1171 // claiming/failing them are all separate and don't affect each other
1172 let chanmon_cfgs = create_chanmon_cfgs(6);
1173 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1174 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1175 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1177 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1178 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1179 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1180 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1181 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1182 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1184 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1186 *nodes[0].network_payment_count.borrow_mut() -= 1;
1187 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1189 *nodes[0].network_payment_count.borrow_mut() -= 1;
1190 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1192 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1193 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1194 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1198 fn test_duplicate_htlc_different_direction_onchain() {
1199 // Test that ChannelMonitor doesn't generate 2 preimage txn
1200 // when we have 2 HTLCs with same preimage that go across a node
1201 // in opposite directions, even with the same payment secret.
1202 let chanmon_cfgs = create_chanmon_cfgs(2);
1203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1207 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1210 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1212 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1214 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1215 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1216 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1218 // Provide preimage to node 0 by claiming payment
1219 nodes[0].node.claim_funds(payment_preimage);
1220 check_added_monitors!(nodes[0], 1);
1222 // Broadcast node 1 commitment txn
1223 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1225 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1226 let mut has_both_htlcs = 0; // check htlcs match ones committed
1227 for outp in remote_txn[0].output.iter() {
1228 if outp.value == 800_000 / 1000 {
1229 has_both_htlcs += 1;
1230 } else if outp.value == 900_000 / 1000 {
1231 has_both_htlcs += 1;
1234 assert_eq!(has_both_htlcs, 2);
1236 mine_transaction(&nodes[0], &remote_txn[0]);
1237 check_added_monitors!(nodes[0], 1);
1238 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1239 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1241 // Check we only broadcast 1 timeout tx
1242 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1243 assert_eq!(claim_txn.len(), 8);
1244 assert_eq!(claim_txn[1], claim_txn[4]);
1245 assert_eq!(claim_txn[2], claim_txn[5]);
1246 check_spends!(claim_txn[1], chan_1.3);
1247 check_spends!(claim_txn[2], claim_txn[1]);
1248 check_spends!(claim_txn[7], claim_txn[1]);
1250 assert_eq!(claim_txn[0].input.len(), 1);
1251 assert_eq!(claim_txn[3].input.len(), 1);
1252 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1254 assert_eq!(claim_txn[0].input.len(), 1);
1255 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1256 check_spends!(claim_txn[0], remote_txn[0]);
1257 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1258 assert_eq!(claim_txn[6].input.len(), 1);
1259 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1260 check_spends!(claim_txn[6], remote_txn[0]);
1261 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1263 let events = nodes[0].node.get_and_clear_pending_msg_events();
1264 assert_eq!(events.len(), 3);
1267 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1268 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1269 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1270 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1272 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, .. } } => {
1273 assert!(update_add_htlcs.is_empty());
1274 assert!(update_fail_htlcs.is_empty());
1275 assert_eq!(update_fulfill_htlcs.len(), 1);
1276 assert!(update_fail_malformed_htlcs.is_empty());
1277 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1279 _ => panic!("Unexpected event"),
1285 fn test_basic_channel_reserve() {
1286 let chanmon_cfgs = create_chanmon_cfgs(2);
1287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1289 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1290 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1292 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1293 let channel_reserve = chan_stat.channel_reserve_msat;
1295 // The 2* and +1 are for the fee spike reserve.
1296 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1297 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1299 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1301 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1303 &APIError::ChannelUnavailable{ref err} =>
1304 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1305 _ => panic!("Unexpected error variant"),
1308 _ => panic!("Unexpected error variant"),
1310 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1311 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);
1313 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1317 fn test_fee_spike_violation_fails_htlc() {
1318 let chanmon_cfgs = create_chanmon_cfgs(2);
1319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1322 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1324 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1325 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1326 let secp_ctx = Secp256k1::new();
1327 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1329 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1331 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1332 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1333 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1334 let msg = msgs::UpdateAddHTLC {
1337 amount_msat: htlc_msat,
1338 payment_hash: payment_hash,
1339 cltv_expiry: htlc_cltv,
1340 onion_routing_packet: onion_packet,
1343 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1345 // Now manually create the commitment_signed message corresponding to the update_add
1346 // nodes[0] just sent. In the code for construction of this message, "local" refers
1347 // to the sender of the message, and "remote" refers to the receiver.
1349 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1351 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1353 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1354 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1355 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1356 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1357 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1358 let chan_signer = local_chan.get_signer();
1359 // Make the signer believe we validated another commitment, so we can release the secret
1360 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1362 let pubkeys = chan_signer.pubkeys();
1363 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1364 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1365 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1366 chan_signer.pubkeys().funding_pubkey)
1368 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1369 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1370 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1371 let chan_signer = remote_chan.get_signer();
1372 let pubkeys = chan_signer.pubkeys();
1373 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1374 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1375 chan_signer.pubkeys().funding_pubkey)
1378 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1379 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1380 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1382 // Build the remote commitment transaction so we can sign it, and then later use the
1383 // signature for the commitment_signed message.
1384 let local_chan_balance = 1313;
1386 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1388 amount_msat: 3460001,
1389 cltv_expiry: htlc_cltv,
1391 transaction_output_index: Some(1),
1394 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1397 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1398 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1399 let local_chan_signer = local_chan.get_signer();
1400 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1404 false, local_funding, remote_funding,
1405 commit_tx_keys.clone(),
1407 &mut vec![(accepted_htlc_info, ())],
1408 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1410 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1413 let commit_signed_msg = msgs::CommitmentSigned {
1416 htlc_signatures: res.1
1419 // Send the commitment_signed message to the nodes[1].
1420 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1421 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1423 // Send the RAA to nodes[1].
1424 let raa_msg = msgs::RevokeAndACK {
1426 per_commitment_secret: local_secret,
1427 next_per_commitment_point: next_local_point
1429 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1431 let events = nodes[1].node.get_and_clear_pending_msg_events();
1432 assert_eq!(events.len(), 1);
1433 // Make sure the HTLC failed in the way we expect.
1435 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1436 assert_eq!(update_fail_htlcs.len(), 1);
1437 update_fail_htlcs[0].clone()
1439 _ => panic!("Unexpected event"),
1441 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1442 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1444 check_added_monitors!(nodes[1], 2);
1448 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1449 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1450 // Set the fee rate for the channel very high, to the point where the fundee
1451 // sending any above-dust amount would result in a channel reserve violation.
1452 // In this test we check that we would be prevented from sending an HTLC in
1454 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1457 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1459 let mut push_amt = 100_000_000;
1460 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1461 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1463 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1465 // Sending exactly enough to hit the reserve amount should be accepted
1466 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1467 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1470 // However one more HTLC should be significantly over the reserve amount and fail.
1471 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1472 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1473 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1474 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1475 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);
1479 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1480 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1481 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1484 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1486 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1487 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1488 // transaction fee with 0 HTLCs (183 sats)).
1489 let mut push_amt = 100_000_000;
1490 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1491 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1492 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1494 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1495 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1496 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1499 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1500 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1501 let secp_ctx = Secp256k1::new();
1502 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1503 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1504 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1505 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1506 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1507 let msg = msgs::UpdateAddHTLC {
1509 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1510 amount_msat: htlc_msat,
1511 payment_hash: payment_hash,
1512 cltv_expiry: htlc_cltv,
1513 onion_routing_packet: onion_packet,
1516 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1517 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1518 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);
1519 assert_eq!(nodes[0].node.list_channels().len(), 0);
1520 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1521 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1522 check_added_monitors!(nodes[0], 1);
1523 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() });
1527 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1528 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1529 // calculating our commitment transaction fee (this was previously broken).
1530 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1531 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1535 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1537 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1538 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1539 // transaction fee with 0 HTLCs (183 sats)).
1540 let mut push_amt = 100_000_000;
1541 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1542 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1543 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1545 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1546 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1547 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1548 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1549 // commitment transaction fee.
1550 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1552 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1553 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1554 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1557 // One more than the dust amt should fail, however.
1558 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1559 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1560 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1564 fn test_chan_init_feerate_unaffordability() {
1565 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1566 // channel reserve and feerate requirements.
1567 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1568 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1573 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1575 let mut push_amt = 100_000_000;
1576 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1577 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1578 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1580 // During open, we don't have a "counterparty channel reserve" to check against, so that
1581 // requirement only comes into play on the open_channel handling side.
1582 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1583 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1584 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1585 open_channel_msg.push_msat += 1;
1586 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel_msg);
1588 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1589 assert_eq!(msg_events.len(), 1);
1590 match msg_events[0] {
1591 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1592 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1594 _ => panic!("Unexpected event"),
1599 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1600 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1601 // calculating our counterparty's commitment transaction fee (this was previously broken).
1602 let chanmon_cfgs = create_chanmon_cfgs(2);
1603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1605 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1606 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1608 let payment_amt = 46000; // Dust amount
1609 // In the previous code, these first four payments would succeed.
1610 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1611 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1612 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1613 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1615 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1616 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1617 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1618 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1619 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1620 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1622 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1623 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1624 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1625 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1629 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1630 let chanmon_cfgs = create_chanmon_cfgs(3);
1631 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1632 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1633 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1634 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1635 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1638 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1639 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1640 let feerate = get_feerate!(nodes[0], chan.2);
1642 // Add a 2* and +1 for the fee spike reserve.
1643 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1644 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;
1645 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1647 // Add a pending HTLC.
1648 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1649 let payment_event_1 = {
1650 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1651 check_added_monitors!(nodes[0], 1);
1653 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1654 assert_eq!(events.len(), 1);
1655 SendEvent::from_event(events.remove(0))
1657 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1659 // Attempt to trigger a channel reserve violation --> payment failure.
1660 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1661 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;
1662 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1663 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1665 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1666 let secp_ctx = Secp256k1::new();
1667 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1668 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1669 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1670 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1671 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1672 let msg = msgs::UpdateAddHTLC {
1675 amount_msat: htlc_msat + 1,
1676 payment_hash: our_payment_hash_1,
1677 cltv_expiry: htlc_cltv,
1678 onion_routing_packet: onion_packet,
1681 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1682 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1683 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1684 assert_eq!(nodes[1].node.list_channels().len(), 1);
1685 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1686 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1687 check_added_monitors!(nodes[1], 1);
1688 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1692 fn test_inbound_outbound_capacity_is_not_zero() {
1693 let chanmon_cfgs = create_chanmon_cfgs(2);
1694 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1695 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1696 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1697 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1698 let channels0 = node_chanmgrs[0].list_channels();
1699 let channels1 = node_chanmgrs[1].list_channels();
1700 assert_eq!(channels0.len(), 1);
1701 assert_eq!(channels1.len(), 1);
1703 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1704 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1705 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1707 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1708 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1711 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1712 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1716 fn test_channel_reserve_holding_cell_htlcs() {
1717 let chanmon_cfgs = create_chanmon_cfgs(3);
1718 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1719 // When this test was written, the default base fee floated based on the HTLC count.
1720 // It is now fixed, so we simply set the fee to the expected value here.
1721 let mut config = test_default_channel_config();
1722 config.channel_options.forwarding_fee_base_msat = 239;
1723 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1724 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1725 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1726 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1728 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1729 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1731 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1732 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1734 macro_rules! expect_forward {
1736 let mut events = $node.node.get_and_clear_pending_msg_events();
1737 assert_eq!(events.len(), 1);
1738 check_added_monitors!($node, 1);
1739 let payment_event = SendEvent::from_event(events.remove(0));
1744 let feemsat = 239; // set above
1745 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1746 let feerate = get_feerate!(nodes[0], chan_1.2);
1748 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1750 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1752 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1753 route.paths[0].last_mut().unwrap().fee_msat += 1;
1754 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1755 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1756 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)));
1757 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1758 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);
1761 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1762 // nodes[0]'s wealth
1764 let amt_msat = recv_value_0 + total_fee_msat;
1765 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1766 // Also, ensure that each payment has enough to be over the dust limit to
1767 // ensure it'll be included in each commit tx fee calculation.
1768 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1769 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1770 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1773 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1775 let (stat01_, stat11_, stat12_, stat22_) = (
1776 get_channel_value_stat!(nodes[0], chan_1.2),
1777 get_channel_value_stat!(nodes[1], chan_1.2),
1778 get_channel_value_stat!(nodes[1], chan_2.2),
1779 get_channel_value_stat!(nodes[2], chan_2.2),
1782 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1783 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1784 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1785 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1786 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1789 // adding pending output.
1790 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1791 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1792 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1793 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1794 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1795 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1796 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1797 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1798 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1800 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1801 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1802 let amt_msat_1 = recv_value_1 + total_fee_msat;
1804 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);
1805 let payment_event_1 = {
1806 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1807 check_added_monitors!(nodes[0], 1);
1809 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1810 assert_eq!(events.len(), 1);
1811 SendEvent::from_event(events.remove(0))
1813 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1815 // channel reserve test with htlc pending output > 0
1816 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1818 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1819 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1820 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1824 // split the rest to test holding cell
1825 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1826 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1827 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1828 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1830 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1831 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);
1834 // now see if they go through on both sides
1835 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);
1836 // but this will stuck in the holding cell
1837 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1838 check_added_monitors!(nodes[0], 0);
1839 let events = nodes[0].node.get_and_clear_pending_events();
1840 assert_eq!(events.len(), 0);
1842 // test with outbound holding cell amount > 0
1844 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1845 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1846 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1847 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1848 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);
1851 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);
1852 // this will also stuck in the holding cell
1853 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1854 check_added_monitors!(nodes[0], 0);
1855 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1856 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1858 // flush the pending htlc
1859 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1860 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1861 check_added_monitors!(nodes[1], 1);
1863 // the pending htlc should be promoted to committed
1864 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1865 check_added_monitors!(nodes[0], 1);
1866 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1868 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1869 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1870 // No commitment_signed so get_event_msg's assert(len == 1) passes
1871 check_added_monitors!(nodes[0], 1);
1873 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1874 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1875 check_added_monitors!(nodes[1], 1);
1877 expect_pending_htlcs_forwardable!(nodes[1]);
1879 let ref payment_event_11 = expect_forward!(nodes[1]);
1880 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1881 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1883 expect_pending_htlcs_forwardable!(nodes[2]);
1884 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1886 // flush the htlcs in the holding cell
1887 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1889 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1890 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1891 expect_pending_htlcs_forwardable!(nodes[1]);
1893 let ref payment_event_3 = expect_forward!(nodes[1]);
1894 assert_eq!(payment_event_3.msgs.len(), 2);
1895 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1896 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1898 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1899 expect_pending_htlcs_forwardable!(nodes[2]);
1901 let events = nodes[2].node.get_and_clear_pending_events();
1902 assert_eq!(events.len(), 2);
1904 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1905 assert_eq!(our_payment_hash_21, *payment_hash);
1906 assert_eq!(recv_value_21, amt);
1908 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1909 assert!(payment_preimage.is_none());
1910 assert_eq!(our_payment_secret_21, *payment_secret);
1912 _ => panic!("expected PaymentPurpose::InvoicePayment")
1915 _ => panic!("Unexpected event"),
1918 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1919 assert_eq!(our_payment_hash_22, *payment_hash);
1920 assert_eq!(recv_value_22, amt);
1922 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1923 assert!(payment_preimage.is_none());
1924 assert_eq!(our_payment_secret_22, *payment_secret);
1926 _ => panic!("expected PaymentPurpose::InvoicePayment")
1929 _ => panic!("Unexpected event"),
1932 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1933 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1934 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1936 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1937 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1938 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1940 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1941 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);
1942 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1943 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1944 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1946 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1947 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1951 fn channel_reserve_in_flight_removes() {
1952 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1953 // can send to its counterparty, but due to update ordering, the other side may not yet have
1954 // considered those HTLCs fully removed.
1955 // This tests that we don't count HTLCs which will not be included in the next remote
1956 // commitment transaction towards the reserve value (as it implies no commitment transaction
1957 // will be generated which violates the remote reserve value).
1958 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1960 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1961 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1962 // you only consider the value of the first HTLC, it may not),
1963 // * start routing a third HTLC from A to B,
1964 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1965 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1966 // * deliver the first fulfill from B
1967 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1969 // * deliver A's response CS and RAA.
1970 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1971 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1972 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1973 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1974 let chanmon_cfgs = create_chanmon_cfgs(2);
1975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1977 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1978 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1980 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1981 // Route the first two HTLCs.
1982 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1983 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1985 // Start routing the third HTLC (this is just used to get everyone in the right state).
1986 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1988 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1989 check_added_monitors!(nodes[0], 1);
1990 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1991 assert_eq!(events.len(), 1);
1992 SendEvent::from_event(events.remove(0))
1995 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1996 // initial fulfill/CS.
1997 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1998 check_added_monitors!(nodes[1], 1);
1999 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2001 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2002 // remove the second HTLC when we send the HTLC back from B to A.
2003 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2004 check_added_monitors!(nodes[1], 1);
2005 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2007 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2008 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2009 check_added_monitors!(nodes[0], 1);
2010 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2011 expect_payment_sent!(nodes[0], payment_preimage_1);
2013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2014 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2015 check_added_monitors!(nodes[1], 1);
2016 // B is already AwaitingRAA, so cant generate a CS here
2017 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2019 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2020 check_added_monitors!(nodes[1], 1);
2021 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2023 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2024 check_added_monitors!(nodes[0], 1);
2025 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2027 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2028 check_added_monitors!(nodes[1], 1);
2029 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2031 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2032 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2033 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2034 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2035 // on-chain as necessary).
2036 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2037 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2038 check_added_monitors!(nodes[0], 1);
2039 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2040 expect_payment_sent!(nodes[0], payment_preimage_2);
2042 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2043 check_added_monitors!(nodes[1], 1);
2044 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2046 expect_pending_htlcs_forwardable!(nodes[1]);
2047 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2049 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2050 // resolve the second HTLC from A's point of view.
2051 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2052 check_added_monitors!(nodes[0], 1);
2053 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2055 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2056 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2057 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2059 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2060 check_added_monitors!(nodes[1], 1);
2061 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2062 assert_eq!(events.len(), 1);
2063 SendEvent::from_event(events.remove(0))
2066 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
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());
2071 // Now just resolve all the outstanding messages/HTLCs for completeness...
2073 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2074 check_added_monitors!(nodes[1], 1);
2075 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2077 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2078 check_added_monitors!(nodes[1], 1);
2080 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2081 check_added_monitors!(nodes[0], 1);
2082 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2084 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2085 check_added_monitors!(nodes[1], 1);
2086 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2088 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2089 check_added_monitors!(nodes[0], 1);
2091 expect_pending_htlcs_forwardable!(nodes[0]);
2092 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2094 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2095 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2099 fn channel_monitor_network_test() {
2100 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2101 // tests that ChannelMonitor is able to recover from various states.
2102 let chanmon_cfgs = create_chanmon_cfgs(5);
2103 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2104 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2105 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2107 // Create some initial channels
2108 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2109 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2110 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2111 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2113 // Make sure all nodes are at the same starting height
2114 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2115 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2116 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2117 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2118 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2120 // Rebalance the network a bit by relaying one payment through all the channels...
2121 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2122 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2123 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2124 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2126 // Simple case with no pending HTLCs:
2127 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2128 check_added_monitors!(nodes[1], 1);
2129 check_closed_broadcast!(nodes[1], false);
2131 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2132 assert_eq!(node_txn.len(), 1);
2133 mine_transaction(&nodes[0], &node_txn[0]);
2134 check_added_monitors!(nodes[0], 1);
2135 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2137 check_closed_broadcast!(nodes[0], true);
2138 assert_eq!(nodes[0].node.list_channels().len(), 0);
2139 assert_eq!(nodes[1].node.list_channels().len(), 1);
2140 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2141 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2143 // One pending HTLC is discarded by the force-close:
2144 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2146 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2147 // broadcasted until we reach the timelock time).
2148 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2149 check_closed_broadcast!(nodes[1], false);
2150 check_added_monitors!(nodes[1], 1);
2152 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2153 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2154 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2155 mine_transaction(&nodes[2], &node_txn[0]);
2156 check_added_monitors!(nodes[2], 1);
2157 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2159 check_closed_broadcast!(nodes[2], true);
2160 assert_eq!(nodes[1].node.list_channels().len(), 0);
2161 assert_eq!(nodes[2].node.list_channels().len(), 1);
2162 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2163 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2165 macro_rules! claim_funds {
2166 ($node: expr, $prev_node: expr, $preimage: expr) => {
2168 assert!($node.node.claim_funds($preimage));
2169 check_added_monitors!($node, 1);
2171 let events = $node.node.get_and_clear_pending_msg_events();
2172 assert_eq!(events.len(), 1);
2174 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2175 assert!(update_add_htlcs.is_empty());
2176 assert!(update_fail_htlcs.is_empty());
2177 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2179 _ => panic!("Unexpected event"),
2185 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2186 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2187 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2188 check_added_monitors!(nodes[2], 1);
2189 check_closed_broadcast!(nodes[2], false);
2190 let node2_commitment_txid;
2192 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2193 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2194 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2195 node2_commitment_txid = node_txn[0].txid();
2197 // Claim the payment on nodes[3], giving it knowledge of the preimage
2198 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2199 mine_transaction(&nodes[3], &node_txn[0]);
2200 check_added_monitors!(nodes[3], 1);
2201 check_preimage_claim(&nodes[3], &node_txn);
2203 check_closed_broadcast!(nodes[3], true);
2204 assert_eq!(nodes[2].node.list_channels().len(), 0);
2205 assert_eq!(nodes[3].node.list_channels().len(), 1);
2206 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2207 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2209 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2210 // confusing us in the following tests.
2211 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2213 // One pending HTLC to time out:
2214 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2215 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2218 let (close_chan_update_1, close_chan_update_2) = {
2219 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2220 let events = nodes[3].node.get_and_clear_pending_msg_events();
2221 assert_eq!(events.len(), 2);
2222 let close_chan_update_1 = match events[0] {
2223 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2226 _ => panic!("Unexpected event"),
2229 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2230 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2232 _ => panic!("Unexpected event"),
2234 check_added_monitors!(nodes[3], 1);
2236 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2238 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2239 node_txn.retain(|tx| {
2240 if tx.input[0].previous_output.txid == node2_commitment_txid {
2246 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2248 // Claim the payment on nodes[4], giving it knowledge of the preimage
2249 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2251 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2252 let events = nodes[4].node.get_and_clear_pending_msg_events();
2253 assert_eq!(events.len(), 2);
2254 let close_chan_update_2 = 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[3].node.get_our_node_id());
2264 _ => panic!("Unexpected event"),
2266 check_added_monitors!(nodes[4], 1);
2267 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2269 mine_transaction(&nodes[4], &node_txn[0]);
2270 check_preimage_claim(&nodes[4], &node_txn);
2271 (close_chan_update_1, close_chan_update_2)
2273 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2274 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2275 assert_eq!(nodes[3].node.list_channels().len(), 0);
2276 assert_eq!(nodes[4].node.list_channels().len(), 0);
2278 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2279 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2280 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2284 fn test_justice_tx() {
2285 // Test justice txn built on revoked HTLC-Success tx, against both sides
2286 let mut alice_config = UserConfig::default();
2287 alice_config.channel_options.announced_channel = true;
2288 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2289 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2290 let mut bob_config = UserConfig::default();
2291 bob_config.channel_options.announced_channel = true;
2292 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2293 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2294 let user_cfgs = [Some(alice_config), Some(bob_config)];
2295 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2296 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2297 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2298 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2299 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2300 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2301 // Create some new channels:
2302 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2304 // A pending HTLC which will be revoked:
2305 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2306 // Get the will-be-revoked local txn from nodes[0]
2307 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2308 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2309 assert_eq!(revoked_local_txn[0].input.len(), 1);
2310 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2311 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2312 assert_eq!(revoked_local_txn[1].input.len(), 1);
2313 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2314 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2315 // Revoke the old state
2316 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2319 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2321 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2322 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2323 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2325 check_spends!(node_txn[0], revoked_local_txn[0]);
2326 node_txn.swap_remove(0);
2327 node_txn.truncate(1);
2329 check_added_monitors!(nodes[1], 1);
2330 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2331 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2333 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2334 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2335 // Verify broadcast of revoked HTLC-timeout
2336 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2337 check_added_monitors!(nodes[0], 1);
2338 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2339 // Broadcast revoked HTLC-timeout on node 1
2340 mine_transaction(&nodes[1], &node_txn[1]);
2341 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2343 get_announce_close_broadcast_events(&nodes, 0, 1);
2345 assert_eq!(nodes[0].node.list_channels().len(), 0);
2346 assert_eq!(nodes[1].node.list_channels().len(), 0);
2348 // We test justice_tx build by A on B's revoked HTLC-Success tx
2349 // Create some new channels:
2350 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2352 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2356 // A pending HTLC which will be revoked:
2357 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2358 // Get the will-be-revoked local txn from B
2359 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2360 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2361 assert_eq!(revoked_local_txn[0].input.len(), 1);
2362 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2363 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2364 // Revoke the old state
2365 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2367 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2369 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2370 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2371 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2373 check_spends!(node_txn[0], revoked_local_txn[0]);
2374 node_txn.swap_remove(0);
2376 check_added_monitors!(nodes[0], 1);
2377 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2379 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2380 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2381 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2382 check_added_monitors!(nodes[1], 1);
2383 mine_transaction(&nodes[0], &node_txn[1]);
2384 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2385 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2387 get_announce_close_broadcast_events(&nodes, 0, 1);
2388 assert_eq!(nodes[0].node.list_channels().len(), 0);
2389 assert_eq!(nodes[1].node.list_channels().len(), 0);
2393 fn revoked_output_claim() {
2394 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2395 // transaction is broadcast by its counterparty
2396 let chanmon_cfgs = create_chanmon_cfgs(2);
2397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2399 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2400 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2401 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2402 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2403 assert_eq!(revoked_local_txn.len(), 1);
2404 // Only output is the full channel value back to nodes[0]:
2405 assert_eq!(revoked_local_txn[0].output.len(), 1);
2406 // Send a payment through, updating everyone's latest commitment txn
2407 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2409 // Inform nodes[1] that nodes[0] broadcast a stale tx
2410 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2411 check_added_monitors!(nodes[1], 1);
2412 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2414 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2416 check_spends!(node_txn[0], revoked_local_txn[0]);
2417 check_spends!(node_txn[1], chan_1.3);
2419 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2420 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2421 get_announce_close_broadcast_events(&nodes, 0, 1);
2422 check_added_monitors!(nodes[0], 1);
2423 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2427 fn claim_htlc_outputs_shared_tx() {
2428 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2429 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2430 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2433 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2435 // Create some new channel:
2436 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2438 // Rebalance the network to generate htlc in the two directions
2439 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2440 // 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
2441 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2442 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2444 // Get the will-be-revoked local txn from node[0]
2445 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2446 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2447 assert_eq!(revoked_local_txn[0].input.len(), 1);
2448 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2449 assert_eq!(revoked_local_txn[1].input.len(), 1);
2450 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2451 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2452 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2454 //Revoke the old state
2455 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2458 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2459 check_added_monitors!(nodes[0], 1);
2460 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2461 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2462 check_added_monitors!(nodes[1], 1);
2463 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2464 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2465 expect_payment_failed!(nodes[1], payment_hash_2, true);
2467 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2468 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2470 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2471 check_spends!(node_txn[0], revoked_local_txn[0]);
2473 let mut witness_lens = BTreeSet::new();
2474 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2475 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2476 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2477 assert_eq!(witness_lens.len(), 3);
2478 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2479 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2480 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2482 // Next nodes[1] broadcasts its current local tx state:
2483 assert_eq!(node_txn[1].input.len(), 1);
2484 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2486 get_announce_close_broadcast_events(&nodes, 0, 1);
2487 assert_eq!(nodes[0].node.list_channels().len(), 0);
2488 assert_eq!(nodes[1].node.list_channels().len(), 0);
2492 fn claim_htlc_outputs_single_tx() {
2493 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2494 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2495 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2496 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2497 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2498 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2500 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2502 // Rebalance the network to generate htlc in the two directions
2503 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2504 // 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
2505 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2506 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2507 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2509 // Get the will-be-revoked local txn from node[0]
2510 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2512 //Revoke the old state
2513 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2516 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2517 check_added_monitors!(nodes[0], 1);
2518 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2519 check_added_monitors!(nodes[1], 1);
2520 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2521 let mut events = nodes[0].node.get_and_clear_pending_events();
2522 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2524 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2525 _ => panic!("Unexpected event"),
2528 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2529 expect_payment_failed!(nodes[1], payment_hash_2, true);
2531 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2532 assert_eq!(node_txn.len(), 9);
2533 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2534 // ChannelManager: local commmitment + local HTLC-timeout (2)
2535 // 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)
2536 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2538 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2539 assert_eq!(node_txn[0].input.len(), 1);
2540 check_spends!(node_txn[0], chan_1.3);
2541 assert_eq!(node_txn[1].input.len(), 1);
2542 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2543 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2544 check_spends!(node_txn[1], node_txn[0]);
2546 // Justice transactions are indices 1-2-4
2547 assert_eq!(node_txn[2].input.len(), 1);
2548 assert_eq!(node_txn[3].input.len(), 1);
2549 assert_eq!(node_txn[4].input.len(), 1);
2551 check_spends!(node_txn[2], revoked_local_txn[0]);
2552 check_spends!(node_txn[3], revoked_local_txn[0]);
2553 check_spends!(node_txn[4], revoked_local_txn[0]);
2555 let mut witness_lens = BTreeSet::new();
2556 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2557 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2558 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2559 assert_eq!(witness_lens.len(), 3);
2560 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2561 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2562 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2564 get_announce_close_broadcast_events(&nodes, 0, 1);
2565 assert_eq!(nodes[0].node.list_channels().len(), 0);
2566 assert_eq!(nodes[1].node.list_channels().len(), 0);
2570 fn test_htlc_on_chain_success() {
2571 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2572 // the preimage backward accordingly. So here we test that ChannelManager is
2573 // broadcasting the right event to other nodes in payment path.
2574 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2575 // A --------------------> B ----------------------> C (preimage)
2576 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2577 // commitment transaction was broadcast.
2578 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2580 // B should be able to claim via preimage if A then broadcasts its local tx.
2581 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2582 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2583 // PaymentSent event).
2585 let chanmon_cfgs = create_chanmon_cfgs(3);
2586 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2587 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2588 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2590 // Create some initial channels
2591 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2592 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2594 // Ensure all nodes are at the same height
2595 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2596 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2597 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2598 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2600 // Rebalance the network a bit by relaying one payment through all the channels...
2601 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2602 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2604 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2605 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2607 // Broadcast legit commitment tx from C on B's chain
2608 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2609 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2610 assert_eq!(commitment_tx.len(), 1);
2611 check_spends!(commitment_tx[0], chan_2.3);
2612 nodes[2].node.claim_funds(our_payment_preimage);
2613 nodes[2].node.claim_funds(our_payment_preimage_2);
2614 check_added_monitors!(nodes[2], 2);
2615 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2616 assert!(updates.update_add_htlcs.is_empty());
2617 assert!(updates.update_fail_htlcs.is_empty());
2618 assert!(updates.update_fail_malformed_htlcs.is_empty());
2619 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2621 mine_transaction(&nodes[2], &commitment_tx[0]);
2622 check_closed_broadcast!(nodes[2], true);
2623 check_added_monitors!(nodes[2], 1);
2624 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2625 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)
2626 assert_eq!(node_txn.len(), 5);
2627 assert_eq!(node_txn[0], node_txn[3]);
2628 assert_eq!(node_txn[1], node_txn[4]);
2629 assert_eq!(node_txn[2], commitment_tx[0]);
2630 check_spends!(node_txn[0], commitment_tx[0]);
2631 check_spends!(node_txn[1], commitment_tx[0]);
2632 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2633 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2634 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2635 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2636 assert_eq!(node_txn[0].lock_time, 0);
2637 assert_eq!(node_txn[1].lock_time, 0);
2639 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2640 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2641 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2642 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2644 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2645 assert_eq!(added_monitors.len(), 1);
2646 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2647 added_monitors.clear();
2649 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2650 assert_eq!(forwarded_events.len(), 3);
2651 match forwarded_events[0] {
2652 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2653 _ => panic!("Unexpected event"),
2655 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2656 } else { panic!(); }
2657 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2658 } else { panic!(); }
2659 let events = nodes[1].node.get_and_clear_pending_msg_events();
2661 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2662 assert_eq!(added_monitors.len(), 2);
2663 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2664 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2665 added_monitors.clear();
2667 assert_eq!(events.len(), 3);
2669 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2670 _ => panic!("Unexpected event"),
2673 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2674 _ => panic!("Unexpected event"),
2678 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, .. } } => {
2679 assert!(update_add_htlcs.is_empty());
2680 assert!(update_fail_htlcs.is_empty());
2681 assert_eq!(update_fulfill_htlcs.len(), 1);
2682 assert!(update_fail_malformed_htlcs.is_empty());
2683 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2685 _ => panic!("Unexpected event"),
2687 macro_rules! check_tx_local_broadcast {
2688 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2689 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2690 assert_eq!(node_txn.len(), 3);
2691 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2692 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2693 check_spends!(node_txn[1], $commitment_tx);
2694 check_spends!(node_txn[2], $commitment_tx);
2695 assert_ne!(node_txn[1].lock_time, 0);
2696 assert_ne!(node_txn[2].lock_time, 0);
2698 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2699 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2700 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2701 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2703 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2704 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2705 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2706 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2708 check_spends!(node_txn[0], $chan_tx);
2709 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2713 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2714 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2715 // timeout-claim of the output that nodes[2] just claimed via success.
2716 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2718 // Broadcast legit commitment tx from A on B's chain
2719 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2720 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2721 check_spends!(node_a_commitment_tx[0], chan_1.3);
2722 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2723 check_closed_broadcast!(nodes[1], true);
2724 check_added_monitors!(nodes[1], 1);
2725 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2726 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2727 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2728 let commitment_spend =
2729 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2730 check_spends!(node_txn[1], commitment_tx[0]);
2731 check_spends!(node_txn[2], commitment_tx[0]);
2732 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2735 check_spends!(node_txn[0], commitment_tx[0]);
2736 check_spends!(node_txn[1], commitment_tx[0]);
2737 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2741 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2742 assert_eq!(commitment_spend.input.len(), 2);
2743 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2744 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2745 assert_eq!(commitment_spend.lock_time, 0);
2746 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2747 check_spends!(node_txn[3], chan_1.3);
2748 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2749 check_spends!(node_txn[4], node_txn[3]);
2750 check_spends!(node_txn[5], node_txn[3]);
2751 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2752 // we already checked the same situation with A.
2754 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2755 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2756 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2757 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2758 check_closed_broadcast!(nodes[0], true);
2759 check_added_monitors!(nodes[0], 1);
2760 let events = nodes[0].node.get_and_clear_pending_events();
2761 assert_eq!(events.len(), 3);
2762 let mut first_claimed = false;
2763 for event in events {
2765 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2766 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2767 assert!(!first_claimed);
2768 first_claimed = true;
2770 assert_eq!(payment_preimage, our_payment_preimage_2);
2771 assert_eq!(payment_hash, payment_hash_2);
2774 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2775 _ => panic!("Unexpected event"),
2778 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2781 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2782 // Test that in case of a unilateral close onchain, we detect the state of output and
2783 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2784 // broadcasting the right event to other nodes in payment path.
2785 // A ------------------> B ----------------------> C (timeout)
2786 // B's commitment tx C's commitment tx
2788 // B's HTLC timeout tx B's timeout tx
2790 let chanmon_cfgs = create_chanmon_cfgs(3);
2791 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2792 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2793 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2794 *nodes[0].connect_style.borrow_mut() = connect_style;
2795 *nodes[1].connect_style.borrow_mut() = connect_style;
2796 *nodes[2].connect_style.borrow_mut() = connect_style;
2798 // Create some intial channels
2799 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2800 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2802 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2803 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2804 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2806 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2808 // Broadcast legit commitment tx from C on B's chain
2809 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2810 check_spends!(commitment_tx[0], chan_2.3);
2811 nodes[2].node.fail_htlc_backwards(&payment_hash);
2812 check_added_monitors!(nodes[2], 0);
2813 expect_pending_htlcs_forwardable!(nodes[2]);
2814 check_added_monitors!(nodes[2], 1);
2816 let events = nodes[2].node.get_and_clear_pending_msg_events();
2817 assert_eq!(events.len(), 1);
2819 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, .. } } => {
2820 assert!(update_add_htlcs.is_empty());
2821 assert!(!update_fail_htlcs.is_empty());
2822 assert!(update_fulfill_htlcs.is_empty());
2823 assert!(update_fail_malformed_htlcs.is_empty());
2824 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2826 _ => panic!("Unexpected event"),
2828 mine_transaction(&nodes[2], &commitment_tx[0]);
2829 check_closed_broadcast!(nodes[2], true);
2830 check_added_monitors!(nodes[2], 1);
2831 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2832 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2833 assert_eq!(node_txn.len(), 1);
2834 check_spends!(node_txn[0], chan_2.3);
2835 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2837 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2838 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2839 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2840 mine_transaction(&nodes[1], &commitment_tx[0]);
2841 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2844 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2845 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2846 assert_eq!(node_txn[0], node_txn[3]);
2847 assert_eq!(node_txn[1], node_txn[4]);
2849 check_spends!(node_txn[2], commitment_tx[0]);
2850 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2852 check_spends!(node_txn[0], chan_2.3);
2853 check_spends!(node_txn[1], node_txn[0]);
2854 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2855 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2857 timeout_tx = node_txn[2].clone();
2861 mine_transaction(&nodes[1], &timeout_tx);
2862 check_added_monitors!(nodes[1], 1);
2863 check_closed_broadcast!(nodes[1], true);
2865 // B will rebroadcast a fee-bumped timeout transaction here.
2866 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2867 assert_eq!(node_txn.len(), 1);
2868 check_spends!(node_txn[0], commitment_tx[0]);
2871 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2873 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2874 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2875 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2876 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2877 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2878 if node_txn.len() == 1 {
2879 check_spends!(node_txn[0], chan_2.3);
2881 assert_eq!(node_txn.len(), 0);
2885 expect_pending_htlcs_forwardable!(nodes[1]);
2886 check_added_monitors!(nodes[1], 1);
2887 let events = nodes[1].node.get_and_clear_pending_msg_events();
2888 assert_eq!(events.len(), 1);
2890 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, .. } } => {
2891 assert!(update_add_htlcs.is_empty());
2892 assert!(!update_fail_htlcs.is_empty());
2893 assert!(update_fulfill_htlcs.is_empty());
2894 assert!(update_fail_malformed_htlcs.is_empty());
2895 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2897 _ => panic!("Unexpected event"),
2900 // Broadcast legit commitment tx from B on A's chain
2901 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2902 check_spends!(commitment_tx[0], chan_1.3);
2904 mine_transaction(&nodes[0], &commitment_tx[0]);
2905 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2907 check_closed_broadcast!(nodes[0], true);
2908 check_added_monitors!(nodes[0], 1);
2909 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2910 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2911 assert_eq!(node_txn.len(), 2);
2912 check_spends!(node_txn[0], chan_1.3);
2913 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2914 check_spends!(node_txn[1], commitment_tx[0]);
2915 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2919 fn test_htlc_on_chain_timeout() {
2920 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2921 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2922 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2926 fn test_simple_commitment_revoked_fail_backward() {
2927 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2928 // and fail backward accordingly.
2930 let chanmon_cfgs = create_chanmon_cfgs(3);
2931 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2932 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2933 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2935 // Create some initial channels
2936 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2937 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2939 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2940 // Get the will-be-revoked local txn from nodes[2]
2941 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2942 // Revoke the old state
2943 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2945 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2947 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2948 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2949 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2950 check_added_monitors!(nodes[1], 1);
2951 check_closed_broadcast!(nodes[1], true);
2953 expect_pending_htlcs_forwardable!(nodes[1]);
2954 check_added_monitors!(nodes[1], 1);
2955 let events = nodes[1].node.get_and_clear_pending_msg_events();
2956 assert_eq!(events.len(), 1);
2958 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, .. } } => {
2959 assert!(update_add_htlcs.is_empty());
2960 assert_eq!(update_fail_htlcs.len(), 1);
2961 assert!(update_fulfill_htlcs.is_empty());
2962 assert!(update_fail_malformed_htlcs.is_empty());
2963 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2965 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2966 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2967 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2969 _ => panic!("Unexpected event"),
2973 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2974 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2975 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2976 // commitment transaction anymore.
2977 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2978 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2979 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2980 // technically disallowed and we should probably handle it reasonably.
2981 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2982 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2984 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2985 // commitment_signed (implying it will be in the latest remote commitment transaction).
2986 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2987 // and once they revoke the previous commitment transaction (allowing us to send a new
2988 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2989 let chanmon_cfgs = create_chanmon_cfgs(3);
2990 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2991 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2992 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2994 // Create some initial channels
2995 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2996 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2998 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2999 // Get the will-be-revoked local txn from nodes[2]
3000 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3001 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3002 // Revoke the old state
3003 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3005 let value = if use_dust {
3006 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3007 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3008 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3011 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3012 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3013 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3015 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3016 expect_pending_htlcs_forwardable!(nodes[2]);
3017 check_added_monitors!(nodes[2], 1);
3018 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3019 assert!(updates.update_add_htlcs.is_empty());
3020 assert!(updates.update_fulfill_htlcs.is_empty());
3021 assert!(updates.update_fail_malformed_htlcs.is_empty());
3022 assert_eq!(updates.update_fail_htlcs.len(), 1);
3023 assert!(updates.update_fee.is_none());
3024 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3025 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3026 // Drop the last RAA from 3 -> 2
3028 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3029 expect_pending_htlcs_forwardable!(nodes[2]);
3030 check_added_monitors!(nodes[2], 1);
3031 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3032 assert!(updates.update_add_htlcs.is_empty());
3033 assert!(updates.update_fulfill_htlcs.is_empty());
3034 assert!(updates.update_fail_malformed_htlcs.is_empty());
3035 assert_eq!(updates.update_fail_htlcs.len(), 1);
3036 assert!(updates.update_fee.is_none());
3037 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3038 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3039 check_added_monitors!(nodes[1], 1);
3040 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3041 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3042 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3043 check_added_monitors!(nodes[2], 1);
3045 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3046 expect_pending_htlcs_forwardable!(nodes[2]);
3047 check_added_monitors!(nodes[2], 1);
3048 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3049 assert!(updates.update_add_htlcs.is_empty());
3050 assert!(updates.update_fulfill_htlcs.is_empty());
3051 assert!(updates.update_fail_malformed_htlcs.is_empty());
3052 assert_eq!(updates.update_fail_htlcs.len(), 1);
3053 assert!(updates.update_fee.is_none());
3054 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3055 // At this point first_payment_hash has dropped out of the latest two commitment
3056 // transactions that nodes[1] is tracking...
3057 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3058 check_added_monitors!(nodes[1], 1);
3059 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3060 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3061 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3062 check_added_monitors!(nodes[2], 1);
3064 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3065 // on nodes[2]'s RAA.
3066 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3067 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3068 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3069 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3070 check_added_monitors!(nodes[1], 0);
3073 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3074 // One monitor for the new revocation preimage, no second on as we won't generate a new
3075 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3076 check_added_monitors!(nodes[1], 1);
3077 let events = nodes[1].node.get_and_clear_pending_events();
3078 assert_eq!(events.len(), 1);
3080 Event::PendingHTLCsForwardable { .. } => { },
3081 _ => panic!("Unexpected event"),
3083 // Deliberately don't process the pending fail-back so they all fail back at once after
3084 // block connection just like the !deliver_bs_raa case
3087 let mut failed_htlcs = HashSet::new();
3088 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3090 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3091 check_added_monitors!(nodes[1], 1);
3092 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3094 let events = nodes[1].node.get_and_clear_pending_events();
3095 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3097 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3098 _ => panic!("Unexepected event"),
3101 Event::PaymentPathFailed { ref payment_hash, .. } => {
3102 assert_eq!(*payment_hash, fourth_payment_hash);
3104 _ => panic!("Unexpected event"),
3106 if !deliver_bs_raa {
3108 Event::PendingHTLCsForwardable { .. } => { },
3109 _ => panic!("Unexpected event"),
3112 nodes[1].node.process_pending_htlc_forwards();
3113 check_added_monitors!(nodes[1], 1);
3115 let events = nodes[1].node.get_and_clear_pending_msg_events();
3116 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3117 match events[if deliver_bs_raa { 1 } else { 0 }] {
3118 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3119 _ => panic!("Unexpected event"),
3121 match events[if deliver_bs_raa { 2 } else { 1 }] {
3122 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3123 assert_eq!(channel_id, chan_2.2);
3124 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3126 _ => panic!("Unexpected event"),
3130 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, .. } } => {
3131 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3132 assert_eq!(update_add_htlcs.len(), 1);
3133 assert!(update_fulfill_htlcs.is_empty());
3134 assert!(update_fail_htlcs.is_empty());
3135 assert!(update_fail_malformed_htlcs.is_empty());
3137 _ => panic!("Unexpected event"),
3140 match events[if deliver_bs_raa { 3 } else { 2 }] {
3141 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, .. } } => {
3142 assert!(update_add_htlcs.is_empty());
3143 assert_eq!(update_fail_htlcs.len(), 3);
3144 assert!(update_fulfill_htlcs.is_empty());
3145 assert!(update_fail_malformed_htlcs.is_empty());
3146 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3148 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3149 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3150 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3152 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3154 let events = nodes[0].node.get_and_clear_pending_events();
3155 assert_eq!(events.len(), 3);
3157 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3158 assert!(failed_htlcs.insert(payment_hash.0));
3159 // If we delivered B's RAA we got an unknown preimage error, not something
3160 // that we should update our routing table for.
3161 if !deliver_bs_raa {
3162 assert!(network_update.is_some());
3165 _ => panic!("Unexpected event"),
3168 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3169 assert!(failed_htlcs.insert(payment_hash.0));
3170 assert!(network_update.is_some());
3172 _ => panic!("Unexpected event"),
3175 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3176 assert!(failed_htlcs.insert(payment_hash.0));
3177 assert!(network_update.is_some());
3179 _ => panic!("Unexpected event"),
3182 _ => panic!("Unexpected event"),
3185 assert!(failed_htlcs.contains(&first_payment_hash.0));
3186 assert!(failed_htlcs.contains(&second_payment_hash.0));
3187 assert!(failed_htlcs.contains(&third_payment_hash.0));
3191 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3192 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3193 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3194 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3195 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3199 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3200 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3201 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3202 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3203 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3207 fn fail_backward_pending_htlc_upon_channel_failure() {
3208 let chanmon_cfgs = create_chanmon_cfgs(2);
3209 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3210 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3211 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3212 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3214 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3216 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3217 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3218 check_added_monitors!(nodes[0], 1);
3220 let payment_event = {
3221 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3222 assert_eq!(events.len(), 1);
3223 SendEvent::from_event(events.remove(0))
3225 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3226 assert_eq!(payment_event.msgs.len(), 1);
3229 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3230 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3232 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3233 check_added_monitors!(nodes[0], 0);
3235 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3238 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3240 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3242 let secp_ctx = Secp256k1::new();
3243 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3244 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3245 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3246 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3247 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3249 // Send a 0-msat update_add_htlc to fail the channel.
3250 let update_add_htlc = msgs::UpdateAddHTLC {
3256 onion_routing_packet,
3258 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3260 let events = nodes[0].node.get_and_clear_pending_events();
3261 assert_eq!(events.len(), 2);
3262 // Check that Alice fails backward the pending HTLC from the second payment.
3264 Event::PaymentPathFailed { payment_hash, .. } => {
3265 assert_eq!(payment_hash, failed_payment_hash);
3267 _ => panic!("Unexpected event"),
3270 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3271 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3273 _ => panic!("Unexpected event {:?}", events[1]),
3275 check_closed_broadcast!(nodes[0], true);
3276 check_added_monitors!(nodes[0], 1);
3280 fn test_htlc_ignore_latest_remote_commitment() {
3281 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3282 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3283 let chanmon_cfgs = create_chanmon_cfgs(2);
3284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3286 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3287 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3289 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3290 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3291 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3292 check_closed_broadcast!(nodes[0], true);
3293 check_added_monitors!(nodes[0], 1);
3294 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3296 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3297 assert_eq!(node_txn.len(), 3);
3298 assert_eq!(node_txn[0], node_txn[1]);
3300 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3301 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3302 check_closed_broadcast!(nodes[1], true);
3303 check_added_monitors!(nodes[1], 1);
3304 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3306 // Duplicate the connect_block call since this may happen due to other listeners
3307 // registering new transactions
3308 header.prev_blockhash = header.block_hash();
3309 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3313 fn test_force_close_fail_back() {
3314 // Check which HTLCs are failed-backwards on channel force-closure
3315 let chanmon_cfgs = create_chanmon_cfgs(3);
3316 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3317 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3318 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3319 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3320 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3322 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3324 let mut payment_event = {
3325 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3326 check_added_monitors!(nodes[0], 1);
3328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3329 assert_eq!(events.len(), 1);
3330 SendEvent::from_event(events.remove(0))
3333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3334 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3336 expect_pending_htlcs_forwardable!(nodes[1]);
3338 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3339 assert_eq!(events_2.len(), 1);
3340 payment_event = SendEvent::from_event(events_2.remove(0));
3341 assert_eq!(payment_event.msgs.len(), 1);
3343 check_added_monitors!(nodes[1], 1);
3344 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3345 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3346 check_added_monitors!(nodes[2], 1);
3347 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3349 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3350 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3351 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3353 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3354 check_closed_broadcast!(nodes[2], true);
3355 check_added_monitors!(nodes[2], 1);
3356 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3358 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3359 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3360 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3361 // back to nodes[1] upon timeout otherwise.
3362 assert_eq!(node_txn.len(), 1);
3366 mine_transaction(&nodes[1], &tx);
3368 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3369 check_closed_broadcast!(nodes[1], true);
3370 check_added_monitors!(nodes[1], 1);
3371 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3373 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3375 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3376 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3378 mine_transaction(&nodes[2], &tx);
3379 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3380 assert_eq!(node_txn.len(), 1);
3381 assert_eq!(node_txn[0].input.len(), 1);
3382 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3383 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3384 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3386 check_spends!(node_txn[0], tx);
3390 fn test_dup_events_on_peer_disconnect() {
3391 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3392 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3393 // as we used to generate the event immediately upon receipt of the payment preimage in the
3394 // update_fulfill_htlc message.
3396 let chanmon_cfgs = create_chanmon_cfgs(2);
3397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3399 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3400 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3402 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3404 assert!(nodes[1].node.claim_funds(payment_preimage));
3405 check_added_monitors!(nodes[1], 1);
3406 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3407 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3408 expect_payment_sent!(nodes[0], payment_preimage);
3410 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3411 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3413 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3414 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3418 fn test_simple_peer_disconnect() {
3419 // Test that we can reconnect when there are no lost messages
3420 let chanmon_cfgs = create_chanmon_cfgs(3);
3421 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3422 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3423 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3424 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3425 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3427 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3428 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3429 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3431 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3432 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3433 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3434 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3436 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3437 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3438 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3440 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3441 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3442 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3443 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3445 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3446 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3448 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3449 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3451 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3453 let events = nodes[0].node.get_and_clear_pending_events();
3454 assert_eq!(events.len(), 2);
3456 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3457 assert_eq!(payment_preimage, payment_preimage_3);
3458 assert_eq!(payment_hash, payment_hash_3);
3460 _ => panic!("Unexpected event"),
3463 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3464 assert_eq!(payment_hash, payment_hash_5);
3465 assert!(rejected_by_dest);
3467 _ => panic!("Unexpected event"),
3471 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3472 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3475 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3476 // Test that we can reconnect when in-flight HTLC updates get dropped
3477 let chanmon_cfgs = create_chanmon_cfgs(2);
3478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3480 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3482 let mut as_funding_locked = None;
3483 if messages_delivered == 0 {
3484 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3485 as_funding_locked = Some(funding_locked);
3486 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3487 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3488 // it before the channel_reestablish message.
3490 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3493 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3495 let payment_event = {
3496 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3497 check_added_monitors!(nodes[0], 1);
3499 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3500 assert_eq!(events.len(), 1);
3501 SendEvent::from_event(events.remove(0))
3503 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3505 if messages_delivered < 2 {
3506 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3508 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3509 if messages_delivered >= 3 {
3510 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3511 check_added_monitors!(nodes[1], 1);
3512 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3514 if messages_delivered >= 4 {
3515 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3516 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3517 check_added_monitors!(nodes[0], 1);
3519 if messages_delivered >= 5 {
3520 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3521 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3522 // No commitment_signed so get_event_msg's assert(len == 1) passes
3523 check_added_monitors!(nodes[0], 1);
3525 if messages_delivered >= 6 {
3526 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3527 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3528 check_added_monitors!(nodes[1], 1);
3535 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3536 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3537 if messages_delivered < 3 {
3538 if simulate_broken_lnd {
3539 // lnd has a long-standing bug where they send a funding_locked prior to a
3540 // channel_reestablish if you reconnect prior to funding_locked time.
3542 // Here we simulate that behavior, delivering a funding_locked immediately on
3543 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3544 // in `reconnect_nodes` but we currently don't fail based on that.
3546 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3547 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3549 // Even if the funding_locked messages get exchanged, as long as nothing further was
3550 // received on either side, both sides will need to resend them.
3551 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3552 } else if messages_delivered == 3 {
3553 // nodes[0] still wants its RAA + commitment_signed
3554 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3555 } else if messages_delivered == 4 {
3556 // nodes[0] still wants its commitment_signed
3557 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3558 } else if messages_delivered == 5 {
3559 // nodes[1] still wants its final RAA
3560 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3561 } else if messages_delivered == 6 {
3562 // Everything was delivered...
3563 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3566 let events_1 = nodes[1].node.get_and_clear_pending_events();
3567 assert_eq!(events_1.len(), 1);
3569 Event::PendingHTLCsForwardable { .. } => { },
3570 _ => panic!("Unexpected event"),
3573 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3574 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3575 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3577 nodes[1].node.process_pending_htlc_forwards();
3579 let events_2 = nodes[1].node.get_and_clear_pending_events();
3580 assert_eq!(events_2.len(), 1);
3582 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3583 assert_eq!(payment_hash_1, *payment_hash);
3584 assert_eq!(amt, 1000000);
3586 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3587 assert!(payment_preimage.is_none());
3588 assert_eq!(payment_secret_1, *payment_secret);
3590 _ => panic!("expected PaymentPurpose::InvoicePayment")
3593 _ => panic!("Unexpected event"),
3596 nodes[1].node.claim_funds(payment_preimage_1);
3597 check_added_monitors!(nodes[1], 1);
3599 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3600 assert_eq!(events_3.len(), 1);
3601 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3602 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3603 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3604 assert!(updates.update_add_htlcs.is_empty());
3605 assert!(updates.update_fail_htlcs.is_empty());
3606 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3607 assert!(updates.update_fail_malformed_htlcs.is_empty());
3608 assert!(updates.update_fee.is_none());
3609 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3611 _ => panic!("Unexpected event"),
3614 if messages_delivered >= 1 {
3615 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3617 let events_4 = nodes[0].node.get_and_clear_pending_events();
3618 assert_eq!(events_4.len(), 1);
3620 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3621 assert_eq!(payment_preimage_1, *payment_preimage);
3622 assert_eq!(payment_hash_1, *payment_hash);
3624 _ => panic!("Unexpected event"),
3627 if messages_delivered >= 2 {
3628 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3629 check_added_monitors!(nodes[0], 1);
3630 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3632 if messages_delivered >= 3 {
3633 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3634 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3635 check_added_monitors!(nodes[1], 1);
3637 if messages_delivered >= 4 {
3638 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3639 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3640 // No commitment_signed so get_event_msg's assert(len == 1) passes
3641 check_added_monitors!(nodes[1], 1);
3643 if messages_delivered >= 5 {
3644 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3645 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3646 check_added_monitors!(nodes[0], 1);
3653 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3654 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3655 if messages_delivered < 2 {
3656 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3657 if messages_delivered < 1 {
3658 let events_4 = nodes[0].node.get_and_clear_pending_events();
3659 assert_eq!(events_4.len(), 1);
3661 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3662 assert_eq!(payment_preimage_1, *payment_preimage);
3663 assert_eq!(payment_hash_1, *payment_hash);
3665 _ => panic!("Unexpected event"),
3668 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3670 } else if messages_delivered == 2 {
3671 // nodes[0] still wants its RAA + commitment_signed
3672 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3673 } else if messages_delivered == 3 {
3674 // nodes[0] still wants its commitment_signed
3675 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3676 } else if messages_delivered == 4 {
3677 // nodes[1] still wants its final RAA
3678 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3679 } else if messages_delivered == 5 {
3680 // Everything was delivered...
3681 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3684 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3685 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3686 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3688 // Channel should still work fine...
3689 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3690 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3691 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3695 fn test_drop_messages_peer_disconnect_a() {
3696 do_test_drop_messages_peer_disconnect(0, true);
3697 do_test_drop_messages_peer_disconnect(0, false);
3698 do_test_drop_messages_peer_disconnect(1, false);
3699 do_test_drop_messages_peer_disconnect(2, false);
3703 fn test_drop_messages_peer_disconnect_b() {
3704 do_test_drop_messages_peer_disconnect(3, false);
3705 do_test_drop_messages_peer_disconnect(4, false);
3706 do_test_drop_messages_peer_disconnect(5, false);
3707 do_test_drop_messages_peer_disconnect(6, false);
3711 fn test_funding_peer_disconnect() {
3712 // Test that we can lock in our funding tx while disconnected
3713 let chanmon_cfgs = create_chanmon_cfgs(2);
3714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3716 let persister: test_utils::TestPersister;
3717 let new_chain_monitor: test_utils::TestChainMonitor;
3718 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3719 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3720 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3722 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3723 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3725 confirm_transaction(&nodes[0], &tx);
3726 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3728 assert_eq!(events_1.len(), 1);
3730 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3731 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3732 chan_id = msg.channel_id;
3734 _ => panic!("Unexpected event"),
3737 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3739 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3740 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3742 confirm_transaction(&nodes[1], &tx);
3743 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3744 assert_eq!(events_2.len(), 2);
3745 let funding_locked = match events_2[0] {
3746 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3747 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3750 _ => panic!("Unexpected event"),
3752 let bs_announcement_sigs = match events_2[1] {
3753 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3754 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3757 _ => panic!("Unexpected event"),
3760 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3762 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3763 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3764 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3765 assert_eq!(events_3.len(), 2);
3766 let as_announcement_sigs = match events_3[0] {
3767 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3768 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3771 _ => panic!("Unexpected event"),
3773 let (as_announcement, as_update) = match events_3[1] {
3774 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3775 (msg.clone(), update_msg.clone())
3777 _ => panic!("Unexpected event"),
3780 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3781 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3782 assert_eq!(events_4.len(), 1);
3783 let (_, bs_update) = match events_4[0] {
3784 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3785 (msg.clone(), update_msg.clone())
3787 _ => panic!("Unexpected event"),
3790 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3791 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3792 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3794 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3795 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3796 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3798 // Check that after deserialization and reconnection we can still generate an identical
3799 // channel_announcement from the cached signatures.
3800 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3802 let nodes_0_serialized = nodes[0].node.encode();
3803 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3804 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3806 persister = test_utils::TestPersister::new();
3807 let keys_manager = &chanmon_cfgs[0].keys_manager;
3808 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);
3809 nodes[0].chain_monitor = &new_chain_monitor;
3810 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3811 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3812 &mut chan_0_monitor_read, keys_manager).unwrap();
3813 assert!(chan_0_monitor_read.is_empty());
3815 let mut nodes_0_read = &nodes_0_serialized[..];
3816 let (_, nodes_0_deserialized_tmp) = {
3817 let mut channel_monitors = HashMap::new();
3818 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3819 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3820 default_config: UserConfig::default(),
3822 fee_estimator: node_cfgs[0].fee_estimator,
3823 chain_monitor: nodes[0].chain_monitor,
3824 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3825 logger: nodes[0].logger,
3829 nodes_0_deserialized = nodes_0_deserialized_tmp;
3830 assert!(nodes_0_read.is_empty());
3832 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3833 nodes[0].node = &nodes_0_deserialized;
3834 check_added_monitors!(nodes[0], 1);
3836 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3838 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3839 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3840 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3841 let mut found_announcement = false;
3842 for event in msgs.iter() {
3844 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3845 if *msg == as_announcement { found_announcement = true; }
3847 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3848 _ => panic!("Unexpected event"),
3851 assert!(found_announcement);
3855 fn test_drop_messages_peer_disconnect_dual_htlc() {
3856 // Test that we can handle reconnecting when both sides of a channel have pending
3857 // commitment_updates when we disconnect.
3858 let chanmon_cfgs = create_chanmon_cfgs(2);
3859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3861 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3862 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3864 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3866 // Now try to send a second payment which will fail to send
3867 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3868 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3869 check_added_monitors!(nodes[0], 1);
3871 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3872 assert_eq!(events_1.len(), 1);
3874 MessageSendEvent::UpdateHTLCs { .. } => {},
3875 _ => panic!("Unexpected event"),
3878 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3879 check_added_monitors!(nodes[1], 1);
3881 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3882 assert_eq!(events_2.len(), 1);
3884 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 } } => {
3885 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3886 assert!(update_add_htlcs.is_empty());
3887 assert_eq!(update_fulfill_htlcs.len(), 1);
3888 assert!(update_fail_htlcs.is_empty());
3889 assert!(update_fail_malformed_htlcs.is_empty());
3890 assert!(update_fee.is_none());
3892 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3893 let events_3 = nodes[0].node.get_and_clear_pending_events();
3894 assert_eq!(events_3.len(), 1);
3896 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3897 assert_eq!(*payment_preimage, payment_preimage_1);
3898 assert_eq!(*payment_hash, payment_hash_1);
3900 _ => panic!("Unexpected event"),
3903 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3904 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3905 // No commitment_signed so get_event_msg's assert(len == 1) passes
3906 check_added_monitors!(nodes[0], 1);
3908 _ => panic!("Unexpected event"),
3911 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3912 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3914 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3915 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3916 assert_eq!(reestablish_1.len(), 1);
3917 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3918 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3919 assert_eq!(reestablish_2.len(), 1);
3921 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3922 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3923 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3924 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3926 assert!(as_resp.0.is_none());
3927 assert!(bs_resp.0.is_none());
3929 assert!(bs_resp.1.is_none());
3930 assert!(bs_resp.2.is_none());
3932 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3934 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3935 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3936 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3937 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3938 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3939 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3940 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3941 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3942 // No commitment_signed so get_event_msg's assert(len == 1) passes
3943 check_added_monitors!(nodes[1], 1);
3945 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3946 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3947 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3948 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3949 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3950 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3951 assert!(bs_second_commitment_signed.update_fee.is_none());
3952 check_added_monitors!(nodes[1], 1);
3954 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3955 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3956 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3957 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3958 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3959 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3960 assert!(as_commitment_signed.update_fee.is_none());
3961 check_added_monitors!(nodes[0], 1);
3963 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3964 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3965 // No commitment_signed so get_event_msg's assert(len == 1) passes
3966 check_added_monitors!(nodes[0], 1);
3968 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3969 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3970 // No commitment_signed so get_event_msg's assert(len == 1) passes
3971 check_added_monitors!(nodes[1], 1);
3973 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3974 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3975 check_added_monitors!(nodes[1], 1);
3977 expect_pending_htlcs_forwardable!(nodes[1]);
3979 let events_5 = nodes[1].node.get_and_clear_pending_events();
3980 assert_eq!(events_5.len(), 1);
3982 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3983 assert_eq!(payment_hash_2, *payment_hash);
3985 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3986 assert!(payment_preimage.is_none());
3987 assert_eq!(payment_secret_2, *payment_secret);
3989 _ => panic!("expected PaymentPurpose::InvoicePayment")
3992 _ => panic!("Unexpected event"),
3995 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3996 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3997 check_added_monitors!(nodes[0], 1);
3999 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4002 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4003 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4004 // to avoid our counterparty failing the channel.
4005 let chanmon_cfgs = create_chanmon_cfgs(2);
4006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4008 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4010 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4012 let our_payment_hash = if send_partial_mpp {
4013 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4014 // Use the utility function send_payment_along_path to send the payment with MPP data which
4015 // indicates there are more HTLCs coming.
4016 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.
4017 let payment_id = PaymentId([42; 32]);
4018 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payee, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
4019 check_added_monitors!(nodes[0], 1);
4020 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4021 assert_eq!(events.len(), 1);
4022 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4023 // hop should *not* yet generate any PaymentReceived event(s).
4024 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4027 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4030 let mut block = Block {
4031 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4034 connect_block(&nodes[0], &block);
4035 connect_block(&nodes[1], &block);
4036 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4037 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4038 block.header.prev_blockhash = block.block_hash();
4039 connect_block(&nodes[0], &block);
4040 connect_block(&nodes[1], &block);
4043 expect_pending_htlcs_forwardable!(nodes[1]);
4045 check_added_monitors!(nodes[1], 1);
4046 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4047 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4048 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4049 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4050 assert!(htlc_timeout_updates.update_fee.is_none());
4052 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4053 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4054 // 100_000 msat as u64, followed by the height at which we failed back above
4055 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4056 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4057 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4061 fn test_htlc_timeout() {
4062 do_test_htlc_timeout(true);
4063 do_test_htlc_timeout(false);
4066 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4067 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4068 let chanmon_cfgs = create_chanmon_cfgs(3);
4069 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4070 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4071 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4072 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4073 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4075 // Make sure all nodes are at the same starting height
4076 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4077 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4078 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4080 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4081 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4083 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4085 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4086 check_added_monitors!(nodes[1], 1);
4088 // Now attempt to route a second payment, which should be placed in the holding cell
4089 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4090 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4091 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4093 check_added_monitors!(nodes[0], 1);
4094 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4095 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4096 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4097 expect_pending_htlcs_forwardable!(nodes[1]);
4099 check_added_monitors!(nodes[1], 0);
4101 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4102 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4103 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4104 connect_blocks(&nodes[1], 1);
4107 expect_pending_htlcs_forwardable!(nodes[1]);
4108 check_added_monitors!(nodes[1], 1);
4109 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4110 assert_eq!(fail_commit.len(), 1);
4111 match fail_commit[0] {
4112 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4113 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4114 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4116 _ => unreachable!(),
4118 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4120 expect_payment_failed!(nodes[1], second_payment_hash, true);
4125 fn test_holding_cell_htlc_add_timeouts() {
4126 do_test_holding_cell_htlc_add_timeouts(false);
4127 do_test_holding_cell_htlc_add_timeouts(true);
4131 fn test_no_txn_manager_serialize_deserialize() {
4132 let chanmon_cfgs = create_chanmon_cfgs(2);
4133 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4135 let logger: test_utils::TestLogger;
4136 let fee_estimator: test_utils::TestFeeEstimator;
4137 let persister: test_utils::TestPersister;
4138 let new_chain_monitor: test_utils::TestChainMonitor;
4139 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4140 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4142 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4144 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4146 let nodes_0_serialized = nodes[0].node.encode();
4147 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4148 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4149 .write(&mut chan_0_monitor_serialized).unwrap();
4151 logger = test_utils::TestLogger::new();
4152 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4153 persister = test_utils::TestPersister::new();
4154 let keys_manager = &chanmon_cfgs[0].keys_manager;
4155 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4156 nodes[0].chain_monitor = &new_chain_monitor;
4157 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4158 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4159 &mut chan_0_monitor_read, keys_manager).unwrap();
4160 assert!(chan_0_monitor_read.is_empty());
4162 let mut nodes_0_read = &nodes_0_serialized[..];
4163 let config = UserConfig::default();
4164 let (_, nodes_0_deserialized_tmp) = {
4165 let mut channel_monitors = HashMap::new();
4166 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4167 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4168 default_config: config,
4170 fee_estimator: &fee_estimator,
4171 chain_monitor: nodes[0].chain_monitor,
4172 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4177 nodes_0_deserialized = nodes_0_deserialized_tmp;
4178 assert!(nodes_0_read.is_empty());
4180 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4181 nodes[0].node = &nodes_0_deserialized;
4182 assert_eq!(nodes[0].node.list_channels().len(), 1);
4183 check_added_monitors!(nodes[0], 1);
4185 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4186 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4187 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4188 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4190 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4191 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4192 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4193 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4195 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4196 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4197 for node in nodes.iter() {
4198 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4199 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4200 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4203 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4207 fn test_manager_serialize_deserialize_events() {
4208 // This test makes sure the events field in ChannelManager survives de/serialization
4209 let chanmon_cfgs = create_chanmon_cfgs(2);
4210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4212 let fee_estimator: test_utils::TestFeeEstimator;
4213 let persister: test_utils::TestPersister;
4214 let logger: test_utils::TestLogger;
4215 let new_chain_monitor: test_utils::TestChainMonitor;
4216 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4217 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4219 // Start creating a channel, but stop right before broadcasting the funding transaction
4220 let channel_value = 100000;
4221 let push_msat = 10001;
4222 let a_flags = InitFeatures::known();
4223 let b_flags = InitFeatures::known();
4224 let node_a = nodes.remove(0);
4225 let node_b = nodes.remove(0);
4226 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4227 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()));
4228 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()));
4230 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4232 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4233 check_added_monitors!(node_a, 0);
4235 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()));
4237 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4238 assert_eq!(added_monitors.len(), 1);
4239 assert_eq!(added_monitors[0].0, funding_output);
4240 added_monitors.clear();
4243 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4244 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4246 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4247 assert_eq!(added_monitors.len(), 1);
4248 assert_eq!(added_monitors[0].0, funding_output);
4249 added_monitors.clear();
4251 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4256 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4257 let nodes_0_serialized = nodes[0].node.encode();
4258 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4259 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4261 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4262 logger = test_utils::TestLogger::new();
4263 persister = test_utils::TestPersister::new();
4264 let keys_manager = &chanmon_cfgs[0].keys_manager;
4265 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4266 nodes[0].chain_monitor = &new_chain_monitor;
4267 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4268 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4269 &mut chan_0_monitor_read, keys_manager).unwrap();
4270 assert!(chan_0_monitor_read.is_empty());
4272 let mut nodes_0_read = &nodes_0_serialized[..];
4273 let config = UserConfig::default();
4274 let (_, nodes_0_deserialized_tmp) = {
4275 let mut channel_monitors = HashMap::new();
4276 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4277 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4278 default_config: config,
4280 fee_estimator: &fee_estimator,
4281 chain_monitor: nodes[0].chain_monitor,
4282 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4287 nodes_0_deserialized = nodes_0_deserialized_tmp;
4288 assert!(nodes_0_read.is_empty());
4290 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4292 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4293 nodes[0].node = &nodes_0_deserialized;
4295 // After deserializing, make sure the funding_transaction is still held by the channel manager
4296 let events_4 = nodes[0].node.get_and_clear_pending_events();
4297 assert_eq!(events_4.len(), 0);
4298 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4299 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4301 // Make sure the channel is functioning as though the de/serialization never happened
4302 assert_eq!(nodes[0].node.list_channels().len(), 1);
4303 check_added_monitors!(nodes[0], 1);
4305 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4306 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4307 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4308 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4310 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4311 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4312 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4313 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4315 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4316 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4317 for node in nodes.iter() {
4318 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4319 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4320 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4323 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4327 fn test_simple_manager_serialize_deserialize() {
4328 let chanmon_cfgs = create_chanmon_cfgs(2);
4329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4331 let logger: test_utils::TestLogger;
4332 let fee_estimator: test_utils::TestFeeEstimator;
4333 let persister: test_utils::TestPersister;
4334 let new_chain_monitor: test_utils::TestChainMonitor;
4335 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4337 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4339 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4340 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4342 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4344 let nodes_0_serialized = nodes[0].node.encode();
4345 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4346 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4348 logger = test_utils::TestLogger::new();
4349 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4350 persister = test_utils::TestPersister::new();
4351 let keys_manager = &chanmon_cfgs[0].keys_manager;
4352 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4353 nodes[0].chain_monitor = &new_chain_monitor;
4354 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4355 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4356 &mut chan_0_monitor_read, keys_manager).unwrap();
4357 assert!(chan_0_monitor_read.is_empty());
4359 let mut nodes_0_read = &nodes_0_serialized[..];
4360 let (_, nodes_0_deserialized_tmp) = {
4361 let mut channel_monitors = HashMap::new();
4362 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4363 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4364 default_config: UserConfig::default(),
4366 fee_estimator: &fee_estimator,
4367 chain_monitor: nodes[0].chain_monitor,
4368 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4373 nodes_0_deserialized = nodes_0_deserialized_tmp;
4374 assert!(nodes_0_read.is_empty());
4376 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4377 nodes[0].node = &nodes_0_deserialized;
4378 check_added_monitors!(nodes[0], 1);
4380 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4382 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4383 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4387 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4388 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4389 let chanmon_cfgs = create_chanmon_cfgs(4);
4390 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4391 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4392 let logger: test_utils::TestLogger;
4393 let fee_estimator: test_utils::TestFeeEstimator;
4394 let persister: test_utils::TestPersister;
4395 let new_chain_monitor: test_utils::TestChainMonitor;
4396 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4397 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4398 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4399 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4400 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4402 let mut node_0_stale_monitors_serialized = Vec::new();
4403 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4404 let mut writer = test_utils::TestVecWriter(Vec::new());
4405 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4406 node_0_stale_monitors_serialized.push(writer.0);
4409 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4411 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4412 let nodes_0_serialized = nodes[0].node.encode();
4414 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4415 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4416 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4417 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4419 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4421 let mut node_0_monitors_serialized = Vec::new();
4422 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4423 let mut writer = test_utils::TestVecWriter(Vec::new());
4424 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4425 node_0_monitors_serialized.push(writer.0);
4428 logger = test_utils::TestLogger::new();
4429 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4430 persister = test_utils::TestPersister::new();
4431 let keys_manager = &chanmon_cfgs[0].keys_manager;
4432 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4433 nodes[0].chain_monitor = &new_chain_monitor;
4436 let mut node_0_stale_monitors = Vec::new();
4437 for serialized in node_0_stale_monitors_serialized.iter() {
4438 let mut read = &serialized[..];
4439 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4440 assert!(read.is_empty());
4441 node_0_stale_monitors.push(monitor);
4444 let mut node_0_monitors = Vec::new();
4445 for serialized in node_0_monitors_serialized.iter() {
4446 let mut read = &serialized[..];
4447 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4448 assert!(read.is_empty());
4449 node_0_monitors.push(monitor);
4452 let mut nodes_0_read = &nodes_0_serialized[..];
4453 if let Err(msgs::DecodeError::InvalidValue) =
4454 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4455 default_config: UserConfig::default(),
4457 fee_estimator: &fee_estimator,
4458 chain_monitor: nodes[0].chain_monitor,
4459 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4461 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4463 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4466 let mut nodes_0_read = &nodes_0_serialized[..];
4467 let (_, nodes_0_deserialized_tmp) =
4468 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4469 default_config: UserConfig::default(),
4471 fee_estimator: &fee_estimator,
4472 chain_monitor: nodes[0].chain_monitor,
4473 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4475 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4477 nodes_0_deserialized = nodes_0_deserialized_tmp;
4478 assert!(nodes_0_read.is_empty());
4480 { // Channel close should result in a commitment tx
4481 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4482 assert_eq!(txn.len(), 1);
4483 check_spends!(txn[0], funding_tx);
4484 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4487 for monitor in node_0_monitors.drain(..) {
4488 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4489 check_added_monitors!(nodes[0], 1);
4491 nodes[0].node = &nodes_0_deserialized;
4492 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4494 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4495 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4496 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4497 //... and we can even still claim the payment!
4498 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4500 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4501 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4502 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4503 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4504 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4505 assert_eq!(msg_events.len(), 1);
4506 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4508 &ErrorAction::SendErrorMessage { ref msg } => {
4509 assert_eq!(msg.channel_id, channel_id);
4511 _ => panic!("Unexpected event!"),
4516 macro_rules! check_spendable_outputs {
4517 ($node: expr, $keysinterface: expr) => {
4519 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4520 let mut txn = Vec::new();
4521 let mut all_outputs = Vec::new();
4522 let secp_ctx = Secp256k1::new();
4523 for event in events.drain(..) {
4525 Event::SpendableOutputs { mut outputs } => {
4526 for outp in outputs.drain(..) {
4527 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4528 all_outputs.push(outp);
4531 _ => panic!("Unexpected event"),
4534 if all_outputs.len() > 1 {
4535 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) {
4545 fn test_claim_sizeable_push_msat() {
4546 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4547 let chanmon_cfgs = create_chanmon_cfgs(2);
4548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4550 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4552 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4553 nodes[1].node.force_close_channel(&chan.2).unwrap();
4554 check_closed_broadcast!(nodes[1], true);
4555 check_added_monitors!(nodes[1], 1);
4556 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4557 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4558 assert_eq!(node_txn.len(), 1);
4559 check_spends!(node_txn[0], chan.3);
4560 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
4562 mine_transaction(&nodes[1], &node_txn[0]);
4563 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4565 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4566 assert_eq!(spend_txn.len(), 1);
4567 assert_eq!(spend_txn[0].input.len(), 1);
4568 check_spends!(spend_txn[0], node_txn[0]);
4569 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4573 fn test_claim_on_remote_sizeable_push_msat() {
4574 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4575 // to_remote output is encumbered by a P2WPKH
4576 let chanmon_cfgs = create_chanmon_cfgs(2);
4577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4581 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4582 nodes[0].node.force_close_channel(&chan.2).unwrap();
4583 check_closed_broadcast!(nodes[0], true);
4584 check_added_monitors!(nodes[0], 1);
4585 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4587 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4588 assert_eq!(node_txn.len(), 1);
4589 check_spends!(node_txn[0], chan.3);
4590 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
4592 mine_transaction(&nodes[1], &node_txn[0]);
4593 check_closed_broadcast!(nodes[1], true);
4594 check_added_monitors!(nodes[1], 1);
4595 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4596 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4598 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4599 assert_eq!(spend_txn.len(), 1);
4600 check_spends!(spend_txn[0], node_txn[0]);
4604 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4605 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4606 // to_remote output is encumbered by a P2WPKH
4608 let chanmon_cfgs = create_chanmon_cfgs(2);
4609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4613 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4614 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4615 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4616 assert_eq!(revoked_local_txn[0].input.len(), 1);
4617 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4619 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4620 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4621 check_closed_broadcast!(nodes[1], true);
4622 check_added_monitors!(nodes[1], 1);
4623 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4625 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4626 mine_transaction(&nodes[1], &node_txn[0]);
4627 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4629 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4630 assert_eq!(spend_txn.len(), 3);
4631 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4632 check_spends!(spend_txn[1], node_txn[0]);
4633 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4637 fn test_static_spendable_outputs_preimage_tx() {
4638 let chanmon_cfgs = create_chanmon_cfgs(2);
4639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4643 // Create some initial channels
4644 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4646 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4648 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4649 assert_eq!(commitment_tx[0].input.len(), 1);
4650 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4652 // Settle A's commitment tx on B's chain
4653 assert!(nodes[1].node.claim_funds(payment_preimage));
4654 check_added_monitors!(nodes[1], 1);
4655 mine_transaction(&nodes[1], &commitment_tx[0]);
4656 check_added_monitors!(nodes[1], 1);
4657 let events = nodes[1].node.get_and_clear_pending_msg_events();
4659 MessageSendEvent::UpdateHTLCs { .. } => {},
4660 _ => panic!("Unexpected event"),
4663 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4664 _ => panic!("Unexepected event"),
4667 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4668 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4669 assert_eq!(node_txn.len(), 3);
4670 check_spends!(node_txn[0], commitment_tx[0]);
4671 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4672 check_spends!(node_txn[1], chan_1.3);
4673 check_spends!(node_txn[2], node_txn[1]);
4675 mine_transaction(&nodes[1], &node_txn[0]);
4676 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4677 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4679 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4680 assert_eq!(spend_txn.len(), 1);
4681 check_spends!(spend_txn[0], node_txn[0]);
4685 fn test_static_spendable_outputs_timeout_tx() {
4686 let chanmon_cfgs = create_chanmon_cfgs(2);
4687 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4688 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4689 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4691 // Create some initial channels
4692 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4694 // Rebalance the network a bit by relaying one payment through all the channels ...
4695 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4697 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4699 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4700 assert_eq!(commitment_tx[0].input.len(), 1);
4701 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4703 // Settle A's commitment tx on B' chain
4704 mine_transaction(&nodes[1], &commitment_tx[0]);
4705 check_added_monitors!(nodes[1], 1);
4706 let events = nodes[1].node.get_and_clear_pending_msg_events();
4708 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4709 _ => panic!("Unexpected event"),
4711 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4713 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4714 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4715 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4716 check_spends!(node_txn[0], chan_1.3.clone());
4717 check_spends!(node_txn[1], commitment_tx[0].clone());
4718 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4720 mine_transaction(&nodes[1], &node_txn[1]);
4721 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4722 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4723 expect_payment_failed!(nodes[1], our_payment_hash, true);
4725 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4726 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4727 check_spends!(spend_txn[0], commitment_tx[0]);
4728 check_spends!(spend_txn[1], node_txn[1]);
4729 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4733 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4734 let chanmon_cfgs = create_chanmon_cfgs(2);
4735 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4736 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4737 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4739 // Create some initial channels
4740 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4742 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4743 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4744 assert_eq!(revoked_local_txn[0].input.len(), 1);
4745 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4747 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4749 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4750 check_closed_broadcast!(nodes[1], true);
4751 check_added_monitors!(nodes[1], 1);
4752 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4754 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4755 assert_eq!(node_txn.len(), 2);
4756 assert_eq!(node_txn[0].input.len(), 2);
4757 check_spends!(node_txn[0], revoked_local_txn[0]);
4759 mine_transaction(&nodes[1], &node_txn[0]);
4760 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4762 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4763 assert_eq!(spend_txn.len(), 1);
4764 check_spends!(spend_txn[0], node_txn[0]);
4768 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4769 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4770 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4775 // Create some initial channels
4776 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4778 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4779 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4780 assert_eq!(revoked_local_txn[0].input.len(), 1);
4781 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4783 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4785 // A will generate HTLC-Timeout from revoked commitment tx
4786 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4787 check_closed_broadcast!(nodes[0], true);
4788 check_added_monitors!(nodes[0], 1);
4789 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4790 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4792 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4793 assert_eq!(revoked_htlc_txn.len(), 2);
4794 check_spends!(revoked_htlc_txn[0], chan_1.3);
4795 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4796 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4797 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4798 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4800 // B will generate justice tx from A's revoked commitment/HTLC tx
4801 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4802 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4803 check_closed_broadcast!(nodes[1], true);
4804 check_added_monitors!(nodes[1], 1);
4805 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4807 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4808 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4809 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4810 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4811 // transactions next...
4812 assert_eq!(node_txn[0].input.len(), 3);
4813 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4815 assert_eq!(node_txn[1].input.len(), 2);
4816 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4817 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4818 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4820 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4821 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4824 assert_eq!(node_txn[2].input.len(), 1);
4825 check_spends!(node_txn[2], chan_1.3);
4827 mine_transaction(&nodes[1], &node_txn[1]);
4828 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4830 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4831 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4832 assert_eq!(spend_txn.len(), 1);
4833 assert_eq!(spend_txn[0].input.len(), 1);
4834 check_spends!(spend_txn[0], node_txn[1]);
4838 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4839 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4840 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4841 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4842 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4843 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4845 // Create some initial channels
4846 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4848 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4849 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4850 assert_eq!(revoked_local_txn[0].input.len(), 1);
4851 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4853 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4854 assert_eq!(revoked_local_txn[0].output.len(), 2);
4856 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4858 // B will generate HTLC-Success from revoked commitment tx
4859 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4860 check_closed_broadcast!(nodes[1], true);
4861 check_added_monitors!(nodes[1], 1);
4862 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4863 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4865 assert_eq!(revoked_htlc_txn.len(), 2);
4866 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4867 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4868 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4870 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4871 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4872 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4874 // A will generate justice tx from B's revoked commitment/HTLC tx
4875 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4876 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4877 check_closed_broadcast!(nodes[0], true);
4878 check_added_monitors!(nodes[0], 1);
4879 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4881 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4882 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4884 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4885 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4886 // transactions next...
4887 assert_eq!(node_txn[0].input.len(), 2);
4888 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4889 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4890 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4892 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4893 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4896 assert_eq!(node_txn[1].input.len(), 1);
4897 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4899 check_spends!(node_txn[2], chan_1.3);
4901 mine_transaction(&nodes[0], &node_txn[1]);
4902 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4904 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4905 // didn't try to generate any new transactions.
4907 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4908 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4909 assert_eq!(spend_txn.len(), 3);
4910 assert_eq!(spend_txn[0].input.len(), 1);
4911 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4912 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4913 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4914 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4918 fn test_onchain_to_onchain_claim() {
4919 // Test that in case of channel closure, we detect the state of output and claim HTLC
4920 // on downstream peer's remote commitment tx.
4921 // First, have C claim an HTLC against its own latest commitment transaction.
4922 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4924 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4927 let chanmon_cfgs = create_chanmon_cfgs(3);
4928 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4929 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4930 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4932 // Create some initial channels
4933 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4934 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4936 // Ensure all nodes are at the same height
4937 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4938 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4939 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4940 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4942 // Rebalance the network a bit by relaying one payment through all the channels ...
4943 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4944 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4946 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4947 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4948 check_spends!(commitment_tx[0], chan_2.3);
4949 nodes[2].node.claim_funds(payment_preimage);
4950 check_added_monitors!(nodes[2], 1);
4951 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4952 assert!(updates.update_add_htlcs.is_empty());
4953 assert!(updates.update_fail_htlcs.is_empty());
4954 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4955 assert!(updates.update_fail_malformed_htlcs.is_empty());
4957 mine_transaction(&nodes[2], &commitment_tx[0]);
4958 check_closed_broadcast!(nodes[2], true);
4959 check_added_monitors!(nodes[2], 1);
4960 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4962 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4963 assert_eq!(c_txn.len(), 3);
4964 assert_eq!(c_txn[0], c_txn[2]);
4965 assert_eq!(commitment_tx[0], c_txn[1]);
4966 check_spends!(c_txn[1], chan_2.3);
4967 check_spends!(c_txn[2], c_txn[1]);
4968 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4969 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4970 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4971 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4973 // 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
4974 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4975 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4976 check_added_monitors!(nodes[1], 1);
4977 let events = nodes[1].node.get_and_clear_pending_events();
4978 assert_eq!(events.len(), 2);
4980 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4981 _ => panic!("Unexpected event"),
4984 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
4985 assert_eq!(fee_earned_msat, Some(1000));
4986 assert_eq!(claim_from_onchain_tx, true);
4988 _ => panic!("Unexpected event"),
4991 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4992 // ChannelMonitor: claim tx
4993 assert_eq!(b_txn.len(), 1);
4994 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4997 check_added_monitors!(nodes[1], 1);
4998 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4999 assert_eq!(msg_events.len(), 3);
5000 match msg_events[0] {
5001 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5002 _ => panic!("Unexpected event"),
5004 match msg_events[1] {
5005 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5006 _ => panic!("Unexpected event"),
5008 match msg_events[2] {
5009 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, .. } } => {
5010 assert!(update_add_htlcs.is_empty());
5011 assert!(update_fail_htlcs.is_empty());
5012 assert_eq!(update_fulfill_htlcs.len(), 1);
5013 assert!(update_fail_malformed_htlcs.is_empty());
5014 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5016 _ => panic!("Unexpected event"),
5018 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5019 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5020 mine_transaction(&nodes[1], &commitment_tx[0]);
5021 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5022 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5023 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5024 assert_eq!(b_txn.len(), 3);
5025 check_spends!(b_txn[1], chan_1.3);
5026 check_spends!(b_txn[2], b_txn[1]);
5027 check_spends!(b_txn[0], commitment_tx[0]);
5028 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5029 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5030 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5032 check_closed_broadcast!(nodes[1], true);
5033 check_added_monitors!(nodes[1], 1);
5037 fn test_duplicate_payment_hash_one_failure_one_success() {
5038 // Topology : A --> B --> C --> D
5039 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5040 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5041 // we forward one of the payments onwards to D.
5042 let chanmon_cfgs = create_chanmon_cfgs(4);
5043 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5044 // When this test was written, the default base fee floated based on the HTLC count.
5045 // It is now fixed, so we simply set the fee to the expected value here.
5046 let mut config = test_default_channel_config();
5047 config.channel_options.forwarding_fee_base_msat = 196;
5048 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5049 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5050 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5052 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5053 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5054 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5056 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5057 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5058 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5059 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5060 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5062 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5064 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5065 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5066 // script push size limit so that the below script length checks match
5067 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5068 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5069 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5071 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5072 assert_eq!(commitment_txn[0].input.len(), 1);
5073 check_spends!(commitment_txn[0], chan_2.3);
5075 mine_transaction(&nodes[1], &commitment_txn[0]);
5076 check_closed_broadcast!(nodes[1], true);
5077 check_added_monitors!(nodes[1], 1);
5078 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5079 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5081 let htlc_timeout_tx;
5082 { // Extract one of the two HTLC-Timeout transaction
5083 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5084 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5085 assert_eq!(node_txn.len(), 4);
5086 check_spends!(node_txn[0], chan_2.3);
5088 check_spends!(node_txn[1], commitment_txn[0]);
5089 assert_eq!(node_txn[1].input.len(), 1);
5090 check_spends!(node_txn[2], commitment_txn[0]);
5091 assert_eq!(node_txn[2].input.len(), 1);
5092 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5093 check_spends!(node_txn[3], commitment_txn[0]);
5094 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5096 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5097 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5098 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5099 htlc_timeout_tx = node_txn[1].clone();
5102 nodes[2].node.claim_funds(our_payment_preimage);
5103 mine_transaction(&nodes[2], &commitment_txn[0]);
5104 check_added_monitors!(nodes[2], 2);
5105 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5106 let events = nodes[2].node.get_and_clear_pending_msg_events();
5108 MessageSendEvent::UpdateHTLCs { .. } => {},
5109 _ => panic!("Unexpected event"),
5112 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5113 _ => panic!("Unexepected event"),
5115 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5116 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)
5117 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5118 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5119 assert_eq!(htlc_success_txn[0].input.len(), 1);
5120 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5121 assert_eq!(htlc_success_txn[1].input.len(), 1);
5122 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5123 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5124 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5125 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5126 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5127 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5129 mine_transaction(&nodes[1], &htlc_timeout_tx);
5130 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5131 expect_pending_htlcs_forwardable!(nodes[1]);
5132 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5133 assert!(htlc_updates.update_add_htlcs.is_empty());
5134 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5135 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5136 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5137 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5138 check_added_monitors!(nodes[1], 1);
5140 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5141 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5143 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5145 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5147 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5148 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5149 // and nodes[2] fee) is rounded down and then claimed in full.
5150 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5151 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5152 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5153 assert!(updates.update_add_htlcs.is_empty());
5154 assert!(updates.update_fail_htlcs.is_empty());
5155 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5156 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5157 assert!(updates.update_fail_malformed_htlcs.is_empty());
5158 check_added_monitors!(nodes[1], 1);
5160 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5161 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5163 let events = nodes[0].node.get_and_clear_pending_events();
5165 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5166 assert_eq!(*payment_preimage, our_payment_preimage);
5167 assert_eq!(*payment_hash, duplicate_payment_hash);
5169 _ => panic!("Unexpected event"),
5174 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5175 let chanmon_cfgs = create_chanmon_cfgs(2);
5176 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5177 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5178 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5180 // Create some initial channels
5181 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5183 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5184 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5185 assert_eq!(local_txn.len(), 1);
5186 assert_eq!(local_txn[0].input.len(), 1);
5187 check_spends!(local_txn[0], chan_1.3);
5189 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5190 nodes[1].node.claim_funds(payment_preimage);
5191 check_added_monitors!(nodes[1], 1);
5192 mine_transaction(&nodes[1], &local_txn[0]);
5193 check_added_monitors!(nodes[1], 1);
5194 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5195 let events = nodes[1].node.get_and_clear_pending_msg_events();
5197 MessageSendEvent::UpdateHTLCs { .. } => {},
5198 _ => panic!("Unexpected event"),
5201 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5202 _ => panic!("Unexepected event"),
5205 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5206 assert_eq!(node_txn.len(), 3);
5207 assert_eq!(node_txn[0], node_txn[2]);
5208 assert_eq!(node_txn[1], local_txn[0]);
5209 assert_eq!(node_txn[0].input.len(), 1);
5210 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5211 check_spends!(node_txn[0], local_txn[0]);
5215 mine_transaction(&nodes[1], &node_tx);
5216 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5218 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5219 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5220 assert_eq!(spend_txn.len(), 1);
5221 assert_eq!(spend_txn[0].input.len(), 1);
5222 check_spends!(spend_txn[0], node_tx);
5223 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5226 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5227 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5228 // unrevoked commitment transaction.
5229 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5230 // a remote RAA before they could be failed backwards (and combinations thereof).
5231 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5232 // use the same payment hashes.
5233 // Thus, we use a six-node network:
5238 // And test where C fails back to A/B when D announces its latest commitment transaction
5239 let chanmon_cfgs = create_chanmon_cfgs(6);
5240 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5241 // When this test was written, the default base fee floated based on the HTLC count.
5242 // It is now fixed, so we simply set the fee to the expected value here.
5243 let mut config = test_default_channel_config();
5244 config.channel_options.forwarding_fee_base_msat = 196;
5245 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5246 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5247 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5249 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5250 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5251 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5252 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5253 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5255 // Rebalance and check output sanity...
5256 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5257 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5258 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5260 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5262 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
5264 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
5265 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5267 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
5269 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
5271 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5273 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5274 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5276 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());
5278 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());
5281 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5283 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5284 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
5287 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
5289 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5290 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());
5292 // Double-check that six of the new HTLC were added
5293 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5294 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5295 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5296 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5298 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5299 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5300 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5301 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5302 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5303 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5304 check_added_monitors!(nodes[4], 0);
5305 expect_pending_htlcs_forwardable!(nodes[4]);
5306 check_added_monitors!(nodes[4], 1);
5308 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5309 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5310 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5311 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5312 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5313 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5315 // Fail 3rd below-dust and 7th above-dust HTLCs
5316 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5317 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5318 check_added_monitors!(nodes[5], 0);
5319 expect_pending_htlcs_forwardable!(nodes[5]);
5320 check_added_monitors!(nodes[5], 1);
5322 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5323 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5324 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5325 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5327 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5329 expect_pending_htlcs_forwardable!(nodes[3]);
5330 check_added_monitors!(nodes[3], 1);
5331 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5332 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5333 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5334 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5335 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5336 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5337 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5338 if deliver_last_raa {
5339 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5341 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5344 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5345 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5346 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5347 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5349 // We now broadcast the latest commitment transaction, which *should* result in failures for
5350 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5351 // the non-broadcast above-dust HTLCs.
5353 // Alternatively, we may broadcast the previous commitment transaction, which should only
5354 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5355 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5357 if announce_latest {
5358 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5360 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5362 let events = nodes[2].node.get_and_clear_pending_events();
5363 let close_event = if deliver_last_raa {
5364 assert_eq!(events.len(), 2);
5367 assert_eq!(events.len(), 1);
5371 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5372 _ => panic!("Unexpected event"),
5375 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5376 check_closed_broadcast!(nodes[2], true);
5377 if deliver_last_raa {
5378 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5380 expect_pending_htlcs_forwardable!(nodes[2]);
5382 check_added_monitors!(nodes[2], 3);
5384 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5385 assert_eq!(cs_msgs.len(), 2);
5386 let mut a_done = false;
5387 for msg in cs_msgs {
5389 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5390 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5391 // should be failed-backwards here.
5392 let target = if *node_id == nodes[0].node.get_our_node_id() {
5393 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5394 for htlc in &updates.update_fail_htlcs {
5395 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 });
5397 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5402 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5403 for htlc in &updates.update_fail_htlcs {
5404 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5406 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5407 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5410 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5411 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5412 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5413 if announce_latest {
5414 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5415 if *node_id == nodes[0].node.get_our_node_id() {
5416 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5419 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5421 _ => panic!("Unexpected event"),
5425 let as_events = nodes[0].node.get_and_clear_pending_events();
5426 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5427 let mut as_failds = HashSet::new();
5428 let mut as_updates = 0;
5429 for event in as_events.iter() {
5430 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5431 assert!(as_failds.insert(*payment_hash));
5432 if *payment_hash != payment_hash_2 {
5433 assert_eq!(*rejected_by_dest, deliver_last_raa);
5435 assert!(!rejected_by_dest);
5437 if network_update.is_some() {
5440 } else { panic!("Unexpected event"); }
5442 assert!(as_failds.contains(&payment_hash_1));
5443 assert!(as_failds.contains(&payment_hash_2));
5444 if announce_latest {
5445 assert!(as_failds.contains(&payment_hash_3));
5446 assert!(as_failds.contains(&payment_hash_5));
5448 assert!(as_failds.contains(&payment_hash_6));
5450 let bs_events = nodes[1].node.get_and_clear_pending_events();
5451 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5452 let mut bs_failds = HashSet::new();
5453 let mut bs_updates = 0;
5454 for event in bs_events.iter() {
5455 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5456 assert!(bs_failds.insert(*payment_hash));
5457 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5458 assert_eq!(*rejected_by_dest, deliver_last_raa);
5460 assert!(!rejected_by_dest);
5462 if network_update.is_some() {
5465 } else { panic!("Unexpected event"); }
5467 assert!(bs_failds.contains(&payment_hash_1));
5468 assert!(bs_failds.contains(&payment_hash_2));
5469 if announce_latest {
5470 assert!(bs_failds.contains(&payment_hash_4));
5472 assert!(bs_failds.contains(&payment_hash_5));
5474 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5475 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5476 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5477 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5478 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5479 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5483 fn test_fail_backwards_latest_remote_announce_a() {
5484 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5488 fn test_fail_backwards_latest_remote_announce_b() {
5489 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5493 fn test_fail_backwards_previous_remote_announce() {
5494 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5495 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5496 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5500 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5501 let chanmon_cfgs = create_chanmon_cfgs(2);
5502 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5503 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5504 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5506 // Create some initial channels
5507 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5509 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5510 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5511 assert_eq!(local_txn[0].input.len(), 1);
5512 check_spends!(local_txn[0], chan_1.3);
5514 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5515 mine_transaction(&nodes[0], &local_txn[0]);
5516 check_closed_broadcast!(nodes[0], true);
5517 check_added_monitors!(nodes[0], 1);
5518 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5519 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5521 let htlc_timeout = {
5522 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5523 assert_eq!(node_txn.len(), 2);
5524 check_spends!(node_txn[0], chan_1.3);
5525 assert_eq!(node_txn[1].input.len(), 1);
5526 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5527 check_spends!(node_txn[1], local_txn[0]);
5531 mine_transaction(&nodes[0], &htlc_timeout);
5532 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5533 expect_payment_failed!(nodes[0], our_payment_hash, true);
5535 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5536 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5537 assert_eq!(spend_txn.len(), 3);
5538 check_spends!(spend_txn[0], local_txn[0]);
5539 assert_eq!(spend_txn[1].input.len(), 1);
5540 check_spends!(spend_txn[1], htlc_timeout);
5541 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5542 assert_eq!(spend_txn[2].input.len(), 2);
5543 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5544 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5545 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5549 fn test_key_derivation_params() {
5550 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5551 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5552 // let us re-derive the channel key set to then derive a delayed_payment_key.
5554 let chanmon_cfgs = create_chanmon_cfgs(3);
5556 // We manually create the node configuration to backup the seed.
5557 let seed = [42; 32];
5558 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5559 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);
5560 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() };
5561 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5562 node_cfgs.remove(0);
5563 node_cfgs.insert(0, node);
5565 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5566 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5568 // Create some initial channels
5569 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5571 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5572 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5573 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5575 // Ensure all nodes are at the same height
5576 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5577 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5578 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5579 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5581 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5582 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5583 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5584 assert_eq!(local_txn_1[0].input.len(), 1);
5585 check_spends!(local_txn_1[0], chan_1.3);
5587 // We check funding pubkey are unique
5588 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]));
5589 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]));
5590 if from_0_funding_key_0 == from_1_funding_key_0
5591 || from_0_funding_key_0 == from_1_funding_key_1
5592 || from_0_funding_key_1 == from_1_funding_key_0
5593 || from_0_funding_key_1 == from_1_funding_key_1 {
5594 panic!("Funding pubkeys aren't unique");
5597 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5598 mine_transaction(&nodes[0], &local_txn_1[0]);
5599 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5600 check_closed_broadcast!(nodes[0], true);
5601 check_added_monitors!(nodes[0], 1);
5602 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5604 let htlc_timeout = {
5605 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5606 assert_eq!(node_txn[1].input.len(), 1);
5607 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5608 check_spends!(node_txn[1], local_txn_1[0]);
5612 mine_transaction(&nodes[0], &htlc_timeout);
5613 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5614 expect_payment_failed!(nodes[0], our_payment_hash, true);
5616 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5617 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5618 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5619 assert_eq!(spend_txn.len(), 3);
5620 check_spends!(spend_txn[0], local_txn_1[0]);
5621 assert_eq!(spend_txn[1].input.len(), 1);
5622 check_spends!(spend_txn[1], htlc_timeout);
5623 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5624 assert_eq!(spend_txn[2].input.len(), 2);
5625 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5626 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5627 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5631 fn test_static_output_closing_tx() {
5632 let chanmon_cfgs = create_chanmon_cfgs(2);
5633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5637 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5639 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5640 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5642 mine_transaction(&nodes[0], &closing_tx);
5643 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5644 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5646 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5647 assert_eq!(spend_txn.len(), 1);
5648 check_spends!(spend_txn[0], closing_tx);
5650 mine_transaction(&nodes[1], &closing_tx);
5651 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5652 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5654 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5655 assert_eq!(spend_txn.len(), 1);
5656 check_spends!(spend_txn[0], closing_tx);
5659 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5660 let chanmon_cfgs = create_chanmon_cfgs(2);
5661 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5662 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5663 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5664 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5666 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5668 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5669 // present in B's local commitment transaction, but none of A's commitment transactions.
5670 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5671 check_added_monitors!(nodes[1], 1);
5673 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5674 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5675 let events = nodes[0].node.get_and_clear_pending_events();
5676 assert_eq!(events.len(), 1);
5678 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
5679 assert_eq!(payment_preimage, our_payment_preimage);
5680 assert_eq!(payment_hash, our_payment_hash);
5682 _ => panic!("Unexpected event"),
5685 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5686 check_added_monitors!(nodes[0], 1);
5687 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5688 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5689 check_added_monitors!(nodes[1], 1);
5691 let starting_block = nodes[1].best_block_info();
5692 let mut block = Block {
5693 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5696 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5697 connect_block(&nodes[1], &block);
5698 block.header.prev_blockhash = block.block_hash();
5700 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5701 check_closed_broadcast!(nodes[1], true);
5702 check_added_monitors!(nodes[1], 1);
5703 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5706 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5707 let chanmon_cfgs = create_chanmon_cfgs(2);
5708 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5709 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5710 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5711 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5713 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5714 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5715 check_added_monitors!(nodes[0], 1);
5717 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5719 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5720 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5721 // to "time out" the HTLC.
5723 let starting_block = nodes[1].best_block_info();
5724 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5726 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5727 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5728 header.prev_blockhash = header.block_hash();
5730 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5731 check_closed_broadcast!(nodes[0], true);
5732 check_added_monitors!(nodes[0], 1);
5733 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5736 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5737 let chanmon_cfgs = create_chanmon_cfgs(3);
5738 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5739 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5740 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5741 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5743 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5744 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5745 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5746 // actually revoked.
5747 let htlc_value = if use_dust { 50000 } else { 3000000 };
5748 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5749 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5750 expect_pending_htlcs_forwardable!(nodes[1]);
5751 check_added_monitors!(nodes[1], 1);
5753 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5754 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5755 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5756 check_added_monitors!(nodes[0], 1);
5757 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5758 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5759 check_added_monitors!(nodes[1], 1);
5760 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5761 check_added_monitors!(nodes[1], 1);
5762 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5764 if check_revoke_no_close {
5765 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5766 check_added_monitors!(nodes[0], 1);
5769 let starting_block = nodes[1].best_block_info();
5770 let mut block = Block {
5771 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5774 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5775 connect_block(&nodes[0], &block);
5776 block.header.prev_blockhash = block.block_hash();
5778 if !check_revoke_no_close {
5779 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5780 check_closed_broadcast!(nodes[0], true);
5781 check_added_monitors!(nodes[0], 1);
5782 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5784 expect_payment_failed!(nodes[0], our_payment_hash, true);
5788 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5789 // There are only a few cases to test here:
5790 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5791 // broadcastable commitment transactions result in channel closure,
5792 // * its included in an unrevoked-but-previous remote commitment transaction,
5793 // * its included in the latest remote or local commitment transactions.
5794 // We test each of the three possible commitment transactions individually and use both dust and
5796 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5797 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5798 // tested for at least one of the cases in other tests.
5800 fn htlc_claim_single_commitment_only_a() {
5801 do_htlc_claim_local_commitment_only(true);
5802 do_htlc_claim_local_commitment_only(false);
5804 do_htlc_claim_current_remote_commitment_only(true);
5805 do_htlc_claim_current_remote_commitment_only(false);
5809 fn htlc_claim_single_commitment_only_b() {
5810 do_htlc_claim_previous_remote_commitment_only(true, false);
5811 do_htlc_claim_previous_remote_commitment_only(false, false);
5812 do_htlc_claim_previous_remote_commitment_only(true, true);
5813 do_htlc_claim_previous_remote_commitment_only(false, true);
5818 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5819 let chanmon_cfgs = create_chanmon_cfgs(2);
5820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5823 //Force duplicate channel ids
5824 for node in nodes.iter() {
5825 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5828 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5829 let channel_value_satoshis=10000;
5830 let push_msat=10001;
5831 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5832 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5833 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5835 //Create a second channel with a channel_id collision
5836 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5840 fn bolt2_open_channel_sending_node_checks_part2() {
5841 let chanmon_cfgs = create_chanmon_cfgs(2);
5842 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5843 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5844 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5846 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5847 let channel_value_satoshis=2^24;
5848 let push_msat=10001;
5849 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5851 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5852 let channel_value_satoshis=10000;
5853 // Test when push_msat is equal to 1000 * funding_satoshis.
5854 let push_msat=1000*channel_value_satoshis+1;
5855 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5857 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5858 let channel_value_satoshis=10000;
5859 let push_msat=10001;
5860 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
5861 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5862 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5864 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5865 // 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
5866 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5868 // 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.
5869 assert!(BREAKDOWN_TIMEOUT>0);
5870 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5872 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5873 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5874 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5876 // 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.
5877 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5878 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5879 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5880 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5881 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5885 fn bolt2_open_channel_sane_dust_limit() {
5886 let chanmon_cfgs = create_chanmon_cfgs(2);
5887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5889 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891 let channel_value_satoshis=1000000;
5892 let push_msat=10001;
5893 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5894 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5895 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5896 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5898 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5899 let events = nodes[1].node.get_and_clear_pending_msg_events();
5900 let err_msg = match events[0] {
5901 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5904 _ => panic!("Unexpected event"),
5906 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5909 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5910 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5911 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5912 // is no longer affordable once it's freed.
5914 fn test_fail_holding_cell_htlc_upon_free() {
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5919 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5921 // First nodes[0] generates an update_fee, setting the channel's
5922 // pending_update_fee.
5924 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5925 *feerate_lock += 20;
5927 nodes[0].node.timer_tick_occurred();
5928 check_added_monitors!(nodes[0], 1);
5930 let events = nodes[0].node.get_and_clear_pending_msg_events();
5931 assert_eq!(events.len(), 1);
5932 let (update_msg, commitment_signed) = match events[0] {
5933 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5934 (update_fee.as_ref(), commitment_signed)
5936 _ => panic!("Unexpected event"),
5939 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5941 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5942 let channel_reserve = chan_stat.channel_reserve_msat;
5943 let feerate = get_feerate!(nodes[0], chan.2);
5945 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5946 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5947 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5949 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5950 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5951 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5952 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5954 // Flush the pending fee update.
5955 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5956 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5957 check_added_monitors!(nodes[1], 1);
5958 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5959 check_added_monitors!(nodes[0], 1);
5961 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5962 // HTLC, but now that the fee has been raised the payment will now fail, causing
5963 // us to surface its failure to the user.
5964 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5965 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5966 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);
5967 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 {}",
5968 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5969 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5971 // Check that the payment failed to be sent out.
5972 let events = nodes[0].node.get_and_clear_pending_events();
5973 assert_eq!(events.len(), 1);
5975 &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, .. } => {
5976 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
5977 assert_eq!(our_payment_hash.clone(), *payment_hash);
5978 assert_eq!(*rejected_by_dest, false);
5979 assert_eq!(*all_paths_failed, true);
5980 assert_eq!(*network_update, None);
5981 assert_eq!(*short_channel_id, None);
5982 assert_eq!(*error_code, None);
5983 assert_eq!(*error_data, None);
5985 _ => panic!("Unexpected event"),
5989 // Test that if multiple HTLCs are released from the holding cell and one is
5990 // valid but the other is no longer valid upon release, the valid HTLC can be
5991 // successfully completed while the other one fails as expected.
5993 fn test_free_and_fail_holding_cell_htlcs() {
5994 let chanmon_cfgs = create_chanmon_cfgs(2);
5995 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5996 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5997 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5998 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6000 // First nodes[0] generates an update_fee, setting the channel's
6001 // pending_update_fee.
6003 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6004 *feerate_lock += 200;
6006 nodes[0].node.timer_tick_occurred();
6007 check_added_monitors!(nodes[0], 1);
6009 let events = nodes[0].node.get_and_clear_pending_msg_events();
6010 assert_eq!(events.len(), 1);
6011 let (update_msg, commitment_signed) = match events[0] {
6012 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6013 (update_fee.as_ref(), commitment_signed)
6015 _ => panic!("Unexpected event"),
6018 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6020 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6021 let channel_reserve = chan_stat.channel_reserve_msat;
6022 let feerate = get_feerate!(nodes[0], chan.2);
6024 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6026 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6027 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6028 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6030 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6031 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6032 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6033 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6034 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6035 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6036 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6038 // Flush the pending fee update.
6039 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6040 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6041 check_added_monitors!(nodes[1], 1);
6042 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6043 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6044 check_added_monitors!(nodes[0], 2);
6046 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6047 // but now that the fee has been raised the second payment will now fail, causing us
6048 // to surface its failure to the user. The first payment should succeed.
6049 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6050 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6051 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);
6052 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 {}",
6053 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6054 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6056 // Check that the second payment failed to be sent out.
6057 let events = nodes[0].node.get_and_clear_pending_events();
6058 assert_eq!(events.len(), 1);
6060 &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, .. } => {
6061 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6062 assert_eq!(payment_hash_2.clone(), *payment_hash);
6063 assert_eq!(*rejected_by_dest, false);
6064 assert_eq!(*all_paths_failed, true);
6065 assert_eq!(*network_update, None);
6066 assert_eq!(*short_channel_id, None);
6067 assert_eq!(*error_code, None);
6068 assert_eq!(*error_data, None);
6070 _ => panic!("Unexpected event"),
6073 // Complete the first payment and the RAA from the fee update.
6074 let (payment_event, send_raa_event) = {
6075 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6076 assert_eq!(msgs.len(), 2);
6077 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6079 let raa = match send_raa_event {
6080 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6081 _ => panic!("Unexpected event"),
6083 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6084 check_added_monitors!(nodes[1], 1);
6085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6086 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6087 let events = nodes[1].node.get_and_clear_pending_events();
6088 assert_eq!(events.len(), 1);
6090 Event::PendingHTLCsForwardable { .. } => {},
6091 _ => panic!("Unexpected event"),
6093 nodes[1].node.process_pending_htlc_forwards();
6094 let events = nodes[1].node.get_and_clear_pending_events();
6095 assert_eq!(events.len(), 1);
6097 Event::PaymentReceived { .. } => {},
6098 _ => panic!("Unexpected event"),
6100 nodes[1].node.claim_funds(payment_preimage_1);
6101 check_added_monitors!(nodes[1], 1);
6102 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6103 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6104 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6105 let events = nodes[0].node.get_and_clear_pending_events();
6106 assert_eq!(events.len(), 1);
6108 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
6109 assert_eq!(*payment_preimage, payment_preimage_1);
6110 assert_eq!(*payment_hash, payment_hash_1);
6112 _ => panic!("Unexpected event"),
6116 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6117 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6118 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6121 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6122 let chanmon_cfgs = create_chanmon_cfgs(3);
6123 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6124 // When this test was written, the default base fee floated based on the HTLC count.
6125 // It is now fixed, so we simply set the fee to the expected value here.
6126 let mut config = test_default_channel_config();
6127 config.channel_options.forwarding_fee_base_msat = 196;
6128 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6129 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6130 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6131 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6133 // First nodes[1] generates an update_fee, setting the channel's
6134 // pending_update_fee.
6136 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6137 *feerate_lock += 20;
6139 nodes[1].node.timer_tick_occurred();
6140 check_added_monitors!(nodes[1], 1);
6142 let events = nodes[1].node.get_and_clear_pending_msg_events();
6143 assert_eq!(events.len(), 1);
6144 let (update_msg, commitment_signed) = match events[0] {
6145 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6146 (update_fee.as_ref(), commitment_signed)
6148 _ => panic!("Unexpected event"),
6151 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6153 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6154 let channel_reserve = chan_stat.channel_reserve_msat;
6155 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6157 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6159 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6160 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6161 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6162 let payment_event = {
6163 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6164 check_added_monitors!(nodes[0], 1);
6166 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6167 assert_eq!(events.len(), 1);
6169 SendEvent::from_event(events.remove(0))
6171 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6172 check_added_monitors!(nodes[1], 0);
6173 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6174 expect_pending_htlcs_forwardable!(nodes[1]);
6176 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6177 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6179 // Flush the pending fee update.
6180 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6181 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6182 check_added_monitors!(nodes[2], 1);
6183 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6185 check_added_monitors!(nodes[1], 2);
6187 // A final RAA message is generated to finalize the fee update.
6188 let events = nodes[1].node.get_and_clear_pending_msg_events();
6189 assert_eq!(events.len(), 1);
6191 let raa_msg = match &events[0] {
6192 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6195 _ => panic!("Unexpected event"),
6198 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6199 check_added_monitors!(nodes[2], 1);
6200 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6202 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6203 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6204 assert_eq!(process_htlc_forwards_event.len(), 1);
6205 match &process_htlc_forwards_event[0] {
6206 &Event::PendingHTLCsForwardable { .. } => {},
6207 _ => panic!("Unexpected event"),
6210 // In response, we call ChannelManager's process_pending_htlc_forwards
6211 nodes[1].node.process_pending_htlc_forwards();
6212 check_added_monitors!(nodes[1], 1);
6214 // This causes the HTLC to be failed backwards.
6215 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6216 assert_eq!(fail_event.len(), 1);
6217 let (fail_msg, commitment_signed) = match &fail_event[0] {
6218 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6219 assert_eq!(updates.update_add_htlcs.len(), 0);
6220 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6221 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6222 assert_eq!(updates.update_fail_htlcs.len(), 1);
6223 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6225 _ => panic!("Unexpected event"),
6228 // Pass the failure messages back to nodes[0].
6229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6230 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6232 // Complete the HTLC failure+removal process.
6233 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6234 check_added_monitors!(nodes[0], 1);
6235 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6236 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6237 check_added_monitors!(nodes[1], 2);
6238 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6239 assert_eq!(final_raa_event.len(), 1);
6240 let raa = match &final_raa_event[0] {
6241 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6242 _ => panic!("Unexpected event"),
6244 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6245 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6246 check_added_monitors!(nodes[0], 1);
6249 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6250 // 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.
6251 //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.
6254 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6255 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6256 let chanmon_cfgs = create_chanmon_cfgs(2);
6257 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6258 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6259 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6260 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6262 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6263 route.paths[0][0].fee_msat = 100;
6265 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6266 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6267 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6268 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6272 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6273 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6274 let chanmon_cfgs = create_chanmon_cfgs(2);
6275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6277 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6278 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6280 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6281 route.paths[0][0].fee_msat = 0;
6282 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6283 assert_eq!(err, "Cannot send 0-msat HTLC"));
6285 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6286 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6290 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6291 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6292 let chanmon_cfgs = create_chanmon_cfgs(2);
6293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6296 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6299 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6300 check_added_monitors!(nodes[0], 1);
6301 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6302 updates.update_add_htlcs[0].amount_msat = 0;
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6305 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6306 check_closed_broadcast!(nodes[1], true).unwrap();
6307 check_added_monitors!(nodes[1], 1);
6308 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6312 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6313 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6314 //It is enforced when constructing a route.
6315 let chanmon_cfgs = create_chanmon_cfgs(2);
6316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6318 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6321 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6322 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6323 assert_eq!(err, &"Channel CLTV overflowed?"));
6327 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6328 //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.
6329 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6330 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6331 let chanmon_cfgs = create_chanmon_cfgs(2);
6332 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6333 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6334 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6335 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6336 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6338 for i in 0..max_accepted_htlcs {
6339 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6340 let payment_event = {
6341 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6342 check_added_monitors!(nodes[0], 1);
6344 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6345 assert_eq!(events.len(), 1);
6346 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6347 assert_eq!(htlcs[0].htlc_id, i);
6351 SendEvent::from_event(events.remove(0))
6353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6354 check_added_monitors!(nodes[1], 0);
6355 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6357 expect_pending_htlcs_forwardable!(nodes[1]);
6358 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6360 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6361 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6362 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6364 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6365 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6369 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6370 //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.
6371 let chanmon_cfgs = create_chanmon_cfgs(2);
6372 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6373 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6374 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6375 let channel_value = 100000;
6376 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6377 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6379 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6381 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6382 // Manually create a route over our max in flight (which our router normally automatically
6384 route.paths[0][0].fee_msat = max_in_flight + 1;
6385 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6386 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)));
6388 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6389 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6391 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6394 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6396 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6397 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6398 let chanmon_cfgs = create_chanmon_cfgs(2);
6399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6401 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6402 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6403 let htlc_minimum_msat: u64;
6405 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6406 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6407 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6410 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6411 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6412 check_added_monitors!(nodes[0], 1);
6413 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6414 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6415 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6416 assert!(nodes[1].node.list_channels().is_empty());
6417 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6418 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()));
6419 check_added_monitors!(nodes[1], 1);
6420 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6424 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6425 //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
6426 let chanmon_cfgs = create_chanmon_cfgs(2);
6427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6433 let channel_reserve = chan_stat.channel_reserve_msat;
6434 let feerate = get_feerate!(nodes[0], chan.2);
6435 // The 2* and +1 are for the fee spike reserve.
6436 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6438 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6439 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6440 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6441 check_added_monitors!(nodes[0], 1);
6442 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6444 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6445 // at this time channel-initiatee receivers are not required to enforce that senders
6446 // respect the fee_spike_reserve.
6447 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6448 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6450 assert!(nodes[1].node.list_channels().is_empty());
6451 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6452 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6453 check_added_monitors!(nodes[1], 1);
6454 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6458 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6459 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6460 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6461 let chanmon_cfgs = create_chanmon_cfgs(2);
6462 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6463 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6464 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6465 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6467 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6468 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6469 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6470 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6471 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6472 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6474 let mut msg = msgs::UpdateAddHTLC {
6478 payment_hash: our_payment_hash,
6479 cltv_expiry: htlc_cltv,
6480 onion_routing_packet: onion_packet.clone(),
6483 for i in 0..super::channel::OUR_MAX_HTLCS {
6484 msg.htlc_id = i as u64;
6485 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6487 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6488 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6490 assert!(nodes[1].node.list_channels().is_empty());
6491 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6492 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6493 check_added_monitors!(nodes[1], 1);
6494 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6498 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6499 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6500 let chanmon_cfgs = create_chanmon_cfgs(2);
6501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6503 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6504 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6506 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6507 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6508 check_added_monitors!(nodes[0], 1);
6509 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6510 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6511 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6513 assert!(nodes[1].node.list_channels().is_empty());
6514 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6515 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6516 check_added_monitors!(nodes[1], 1);
6517 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6521 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6522 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6523 let chanmon_cfgs = create_chanmon_cfgs(2);
6524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6526 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6528 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6529 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6530 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6531 check_added_monitors!(nodes[0], 1);
6532 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6533 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6534 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6536 assert!(nodes[1].node.list_channels().is_empty());
6537 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6538 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6539 check_added_monitors!(nodes[1], 1);
6540 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6544 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6545 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6546 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6547 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6548 let chanmon_cfgs = create_chanmon_cfgs(2);
6549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6551 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6554 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6555 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6556 check_added_monitors!(nodes[0], 1);
6557 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6558 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6560 //Disconnect and Reconnect
6561 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6562 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6563 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6564 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6565 assert_eq!(reestablish_1.len(), 1);
6566 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6567 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6568 assert_eq!(reestablish_2.len(), 1);
6569 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6570 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6571 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6572 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6575 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6576 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6577 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6578 check_added_monitors!(nodes[1], 1);
6579 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6583 assert!(nodes[1].node.list_channels().is_empty());
6584 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6585 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6586 check_added_monitors!(nodes[1], 1);
6587 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6591 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6592 //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.
6594 let chanmon_cfgs = create_chanmon_cfgs(2);
6595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6598 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6599 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6600 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6602 check_added_monitors!(nodes[0], 1);
6603 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6604 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6606 let update_msg = msgs::UpdateFulfillHTLC{
6609 payment_preimage: our_payment_preimage,
6612 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6614 assert!(nodes[0].node.list_channels().is_empty());
6615 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6616 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()));
6617 check_added_monitors!(nodes[0], 1);
6618 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6622 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6623 //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.
6625 let chanmon_cfgs = create_chanmon_cfgs(2);
6626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6629 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6631 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6632 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6633 check_added_monitors!(nodes[0], 1);
6634 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6635 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6637 let update_msg = msgs::UpdateFailHTLC{
6640 reason: msgs::OnionErrorPacket { data: Vec::new()},
6643 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6645 assert!(nodes[0].node.list_channels().is_empty());
6646 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6647 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()));
6648 check_added_monitors!(nodes[0], 1);
6649 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6653 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6654 //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.
6656 let chanmon_cfgs = create_chanmon_cfgs(2);
6657 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6658 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6659 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6660 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6662 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6663 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6664 check_added_monitors!(nodes[0], 1);
6665 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6666 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6667 let update_msg = msgs::UpdateFailMalformedHTLC{
6670 sha256_of_onion: [1; 32],
6671 failure_code: 0x8000,
6674 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6676 assert!(nodes[0].node.list_channels().is_empty());
6677 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6678 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()));
6679 check_added_monitors!(nodes[0], 1);
6680 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6684 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6685 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6687 let chanmon_cfgs = create_chanmon_cfgs(2);
6688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6693 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6695 nodes[1].node.claim_funds(our_payment_preimage);
6696 check_added_monitors!(nodes[1], 1);
6698 let events = nodes[1].node.get_and_clear_pending_msg_events();
6699 assert_eq!(events.len(), 1);
6700 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6702 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, .. } } => {
6703 assert!(update_add_htlcs.is_empty());
6704 assert_eq!(update_fulfill_htlcs.len(), 1);
6705 assert!(update_fail_htlcs.is_empty());
6706 assert!(update_fail_malformed_htlcs.is_empty());
6707 assert!(update_fee.is_none());
6708 update_fulfill_htlcs[0].clone()
6710 _ => panic!("Unexpected event"),
6714 update_fulfill_msg.htlc_id = 1;
6716 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6718 assert!(nodes[0].node.list_channels().is_empty());
6719 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6720 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6721 check_added_monitors!(nodes[0], 1);
6722 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6726 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6727 //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.
6729 let chanmon_cfgs = create_chanmon_cfgs(2);
6730 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6731 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6732 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6733 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6735 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6737 nodes[1].node.claim_funds(our_payment_preimage);
6738 check_added_monitors!(nodes[1], 1);
6740 let events = nodes[1].node.get_and_clear_pending_msg_events();
6741 assert_eq!(events.len(), 1);
6742 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6744 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, .. } } => {
6745 assert!(update_add_htlcs.is_empty());
6746 assert_eq!(update_fulfill_htlcs.len(), 1);
6747 assert!(update_fail_htlcs.is_empty());
6748 assert!(update_fail_malformed_htlcs.is_empty());
6749 assert!(update_fee.is_none());
6750 update_fulfill_htlcs[0].clone()
6752 _ => panic!("Unexpected event"),
6756 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6758 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6760 assert!(nodes[0].node.list_channels().is_empty());
6761 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6762 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6763 check_added_monitors!(nodes[0], 1);
6764 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6768 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6769 //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.
6771 let chanmon_cfgs = create_chanmon_cfgs(2);
6772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6777 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6778 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6779 check_added_monitors!(nodes[0], 1);
6781 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6782 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785 check_added_monitors!(nodes[1], 0);
6786 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6788 let events = nodes[1].node.get_and_clear_pending_msg_events();
6790 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6792 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, .. } } => {
6793 assert!(update_add_htlcs.is_empty());
6794 assert!(update_fulfill_htlcs.is_empty());
6795 assert!(update_fail_htlcs.is_empty());
6796 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6797 assert!(update_fee.is_none());
6798 update_fail_malformed_htlcs[0].clone()
6800 _ => panic!("Unexpected event"),
6803 update_msg.failure_code &= !0x8000;
6804 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6806 assert!(nodes[0].node.list_channels().is_empty());
6807 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6808 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6809 check_added_monitors!(nodes[0], 1);
6810 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6814 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6815 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6816 // * 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.
6818 let chanmon_cfgs = create_chanmon_cfgs(3);
6819 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6820 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6821 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6822 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6823 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6825 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6828 let mut payment_event = {
6829 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6830 check_added_monitors!(nodes[0], 1);
6831 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6832 assert_eq!(events.len(), 1);
6833 SendEvent::from_event(events.remove(0))
6835 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6836 check_added_monitors!(nodes[1], 0);
6837 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6838 expect_pending_htlcs_forwardable!(nodes[1]);
6839 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6840 assert_eq!(events_2.len(), 1);
6841 check_added_monitors!(nodes[1], 1);
6842 payment_event = SendEvent::from_event(events_2.remove(0));
6843 assert_eq!(payment_event.msgs.len(), 1);
6846 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6847 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6848 check_added_monitors!(nodes[2], 0);
6849 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6851 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6852 assert_eq!(events_3.len(), 1);
6853 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6855 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 } } => {
6856 assert!(update_add_htlcs.is_empty());
6857 assert!(update_fulfill_htlcs.is_empty());
6858 assert!(update_fail_htlcs.is_empty());
6859 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6860 assert!(update_fee.is_none());
6861 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6863 _ => panic!("Unexpected event"),
6867 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6869 check_added_monitors!(nodes[1], 0);
6870 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6871 expect_pending_htlcs_forwardable!(nodes[1]);
6872 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6873 assert_eq!(events_4.len(), 1);
6875 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6877 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, .. } } => {
6878 assert!(update_add_htlcs.is_empty());
6879 assert!(update_fulfill_htlcs.is_empty());
6880 assert_eq!(update_fail_htlcs.len(), 1);
6881 assert!(update_fail_malformed_htlcs.is_empty());
6882 assert!(update_fee.is_none());
6884 _ => panic!("Unexpected event"),
6887 check_added_monitors!(nodes[1], 1);
6890 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6891 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6892 // 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
6893 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6895 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6896 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6897 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6898 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6899 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6900 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6902 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6904 // We route 2 dust-HTLCs between A and B
6905 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6906 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6907 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6909 // Cache one local commitment tx as previous
6910 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6912 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6913 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6914 check_added_monitors!(nodes[1], 0);
6915 expect_pending_htlcs_forwardable!(nodes[1]);
6916 check_added_monitors!(nodes[1], 1);
6918 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6919 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6920 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6921 check_added_monitors!(nodes[0], 1);
6923 // Cache one local commitment tx as lastest
6924 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6926 let events = nodes[0].node.get_and_clear_pending_msg_events();
6928 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6929 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6931 _ => panic!("Unexpected event"),
6934 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6935 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6937 _ => panic!("Unexpected event"),
6940 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6941 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6942 if announce_latest {
6943 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6945 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6948 check_closed_broadcast!(nodes[0], true);
6949 check_added_monitors!(nodes[0], 1);
6950 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6952 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6953 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6954 let events = nodes[0].node.get_and_clear_pending_events();
6955 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6956 assert_eq!(events.len(), 2);
6957 let mut first_failed = false;
6958 for event in events {
6960 Event::PaymentPathFailed { payment_hash, .. } => {
6961 if payment_hash == payment_hash_1 {
6962 assert!(!first_failed);
6963 first_failed = true;
6965 assert_eq!(payment_hash, payment_hash_2);
6968 _ => panic!("Unexpected event"),
6974 fn test_failure_delay_dust_htlc_local_commitment() {
6975 do_test_failure_delay_dust_htlc_local_commitment(true);
6976 do_test_failure_delay_dust_htlc_local_commitment(false);
6979 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6980 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6981 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6982 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6983 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6984 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6985 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6987 let chanmon_cfgs = create_chanmon_cfgs(3);
6988 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6989 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6990 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6991 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6993 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6995 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6996 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6998 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6999 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7001 // We revoked bs_commitment_tx
7003 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7004 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7007 let mut timeout_tx = Vec::new();
7009 // We fail dust-HTLC 1 by broadcast of local commitment tx
7010 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7011 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7012 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7013 expect_payment_failed!(nodes[0], dust_hash, true);
7015 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7016 check_closed_broadcast!(nodes[0], true);
7017 check_added_monitors!(nodes[0], 1);
7018 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7019 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7020 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7021 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7022 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7023 mine_transaction(&nodes[0], &timeout_tx[0]);
7024 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7025 expect_payment_failed!(nodes[0], non_dust_hash, true);
7027 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7028 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7029 check_closed_broadcast!(nodes[0], true);
7030 check_added_monitors!(nodes[0], 1);
7031 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7032 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7033 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7034 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7036 expect_payment_failed!(nodes[0], dust_hash, true);
7037 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7038 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7039 mine_transaction(&nodes[0], &timeout_tx[0]);
7040 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7041 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7042 expect_payment_failed!(nodes[0], non_dust_hash, true);
7044 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7046 let events = nodes[0].node.get_and_clear_pending_events();
7047 assert_eq!(events.len(), 2);
7050 Event::PaymentPathFailed { payment_hash, .. } => {
7051 if payment_hash == dust_hash { first = true; }
7052 else { first = false; }
7054 _ => panic!("Unexpected event"),
7057 Event::PaymentPathFailed { payment_hash, .. } => {
7058 if first { assert_eq!(payment_hash, non_dust_hash); }
7059 else { assert_eq!(payment_hash, dust_hash); }
7061 _ => panic!("Unexpected event"),
7068 fn test_sweep_outbound_htlc_failure_update() {
7069 do_test_sweep_outbound_htlc_failure_update(false, true);
7070 do_test_sweep_outbound_htlc_failure_update(false, false);
7071 do_test_sweep_outbound_htlc_failure_update(true, false);
7075 fn test_user_configurable_csv_delay() {
7076 // We test our channel constructors yield errors when we pass them absurd csv delay
7078 let mut low_our_to_self_config = UserConfig::default();
7079 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7080 let mut high_their_to_self_config = UserConfig::default();
7081 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7082 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7083 let chanmon_cfgs = create_chanmon_cfgs(2);
7084 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7085 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7086 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7088 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7089 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), 1000000, 1000000, 0, &low_our_to_self_config, 0) {
7091 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())); },
7092 _ => panic!("Unexpected event"),
7094 } else { assert!(false) }
7096 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7097 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7098 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7099 open_channel.to_self_delay = 200;
7100 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &low_our_to_self_config, 0) {
7102 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())); },
7103 _ => panic!("Unexpected event"),
7105 } else { assert!(false); }
7107 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7108 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7109 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()));
7110 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7111 accept_channel.to_self_delay = 200;
7112 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7114 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7116 &ErrorAction::SendErrorMessage { ref msg } => {
7117 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()));
7118 reason_msg = msg.data.clone();
7122 } else { panic!(); }
7123 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7125 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7126 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7127 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7128 open_channel.to_self_delay = 200;
7129 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &InitFeatures::known(), &open_channel, 0, &high_their_to_self_config, 0) {
7131 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())); },
7132 _ => panic!("Unexpected event"),
7134 } else { assert!(false); }
7138 fn test_data_loss_protect() {
7139 // We want to be sure that :
7140 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7141 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7142 // * we close channel in case of detecting other being fallen behind
7143 // * we are able to claim our own outputs thanks to to_remote being static
7144 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7150 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7151 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7152 // during signing due to revoked tx
7153 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7154 let keys_manager = &chanmon_cfgs[0].keys_manager;
7157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7159 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7161 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7163 // Cache node A state before any channel update
7164 let previous_node_state = nodes[0].node.encode();
7165 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7166 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7168 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7169 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7171 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7172 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7174 // Restore node A from previous state
7175 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7176 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7177 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7178 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7179 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7180 persister = test_utils::TestPersister::new();
7181 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7183 let mut channel_monitors = HashMap::new();
7184 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7185 <(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 {
7186 keys_manager: keys_manager,
7187 fee_estimator: &fee_estimator,
7188 chain_monitor: &monitor,
7190 tx_broadcaster: &tx_broadcaster,
7191 default_config: UserConfig::default(),
7195 nodes[0].node = &node_state_0;
7196 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7197 nodes[0].chain_monitor = &monitor;
7198 nodes[0].chain_source = &chain_source;
7200 check_added_monitors!(nodes[0], 1);
7202 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7203 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7205 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7207 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7208 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7209 check_added_monitors!(nodes[0], 1);
7212 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7213 assert_eq!(node_txn.len(), 0);
7216 let mut reestablish_1 = Vec::with_capacity(1);
7217 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7218 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7219 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7220 reestablish_1.push(msg.clone());
7221 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7222 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7224 &ErrorAction::SendErrorMessage { ref msg } => {
7225 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");
7227 _ => panic!("Unexpected event!"),
7230 panic!("Unexpected event")
7234 // Check we close channel detecting A is fallen-behind
7235 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7236 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7237 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7238 check_added_monitors!(nodes[1], 1);
7240 // Check A is able to claim to_remote output
7241 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7242 assert_eq!(node_txn.len(), 1);
7243 check_spends!(node_txn[0], chan.3);
7244 assert_eq!(node_txn[0].output.len(), 2);
7245 mine_transaction(&nodes[0], &node_txn[0]);
7246 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7247 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() });
7248 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7249 assert_eq!(spend_txn.len(), 1);
7250 check_spends!(spend_txn[0], node_txn[0]);
7254 fn test_check_htlc_underpaying() {
7255 // Send payment through A -> B but A is maliciously
7256 // sending a probe payment (i.e less than expected value0
7257 // to B, B should refuse payment.
7259 let chanmon_cfgs = create_chanmon_cfgs(2);
7260 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7261 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7262 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7264 // Create some initial channels
7265 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7267 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7268 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7269 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, nodes[0].network_graph, None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer).unwrap();
7270 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7271 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7272 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7273 check_added_monitors!(nodes[0], 1);
7275 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7276 assert_eq!(events.len(), 1);
7277 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7279 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7281 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7282 // and then will wait a second random delay before failing the HTLC back:
7283 expect_pending_htlcs_forwardable!(nodes[1]);
7284 expect_pending_htlcs_forwardable!(nodes[1]);
7286 // Node 3 is expecting payment of 100_000 but received 10_000,
7287 // it should fail htlc like we didn't know the preimage.
7288 nodes[1].node.process_pending_htlc_forwards();
7290 let events = nodes[1].node.get_and_clear_pending_msg_events();
7291 assert_eq!(events.len(), 1);
7292 let (update_fail_htlc, commitment_signed) = match events[0] {
7293 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 } } => {
7294 assert!(update_add_htlcs.is_empty());
7295 assert!(update_fulfill_htlcs.is_empty());
7296 assert_eq!(update_fail_htlcs.len(), 1);
7297 assert!(update_fail_malformed_htlcs.is_empty());
7298 assert!(update_fee.is_none());
7299 (update_fail_htlcs[0].clone(), commitment_signed)
7301 _ => panic!("Unexpected event"),
7303 check_added_monitors!(nodes[1], 1);
7305 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7306 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7308 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7309 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7310 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7311 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7315 fn test_announce_disable_channels() {
7316 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7317 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7319 let chanmon_cfgs = create_chanmon_cfgs(2);
7320 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7321 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7322 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7324 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7325 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7326 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7329 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7330 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7332 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7333 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7334 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7335 assert_eq!(msg_events.len(), 3);
7336 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7337 for e in msg_events {
7339 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7340 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7341 // Check that each channel gets updated exactly once
7342 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7343 panic!("Generated ChannelUpdate for wrong chan!");
7346 _ => panic!("Unexpected event"),
7350 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7351 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7352 assert_eq!(reestablish_1.len(), 3);
7353 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7354 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7355 assert_eq!(reestablish_2.len(), 3);
7357 // Reestablish chan_1
7358 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7359 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7360 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7361 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7362 // Reestablish chan_2
7363 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7364 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7365 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7366 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7367 // Reestablish chan_3
7368 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7369 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7370 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7371 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7373 nodes[0].node.timer_tick_occurred();
7374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7375 nodes[0].node.timer_tick_occurred();
7376 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7377 assert_eq!(msg_events.len(), 3);
7378 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7379 for e in msg_events {
7381 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7382 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7383 // Check that each channel gets updated exactly once
7384 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7385 panic!("Generated ChannelUpdate for wrong chan!");
7388 _ => panic!("Unexpected event"),
7394 fn test_priv_forwarding_rejection() {
7395 // If we have a private channel with outbound liquidity, and
7396 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7397 // to forward through that channel.
7398 let chanmon_cfgs = create_chanmon_cfgs(3);
7399 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7400 let mut no_announce_cfg = test_default_channel_config();
7401 no_announce_cfg.channel_options.announced_channel = false;
7402 no_announce_cfg.accept_forwards_to_priv_channels = false;
7403 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7404 let persister: test_utils::TestPersister;
7405 let new_chain_monitor: test_utils::TestChainMonitor;
7406 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7407 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7409 let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known()).2;
7411 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7412 // not send for private channels.
7413 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7414 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7415 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7416 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7417 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7419 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7420 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7421 nodes[2].node.handle_funding_created(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingCreated, nodes[2].node.get_our_node_id()));
7422 check_added_monitors!(nodes[2], 1);
7424 let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7425 nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7426 check_added_monitors!(nodes[1], 1);
7428 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7429 confirm_transaction_at(&nodes[1], &tx, conf_height);
7430 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7431 confirm_transaction_at(&nodes[2], &tx, conf_height);
7432 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7433 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7434 nodes[1].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[1].node.get_our_node_id()));
7435 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7436 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7437 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7439 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7440 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7441 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7443 // We should always be able to forward through nodes[1] as long as its out through a public
7445 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7447 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7448 // to nodes[2], which should be rejected:
7449 let route_hint = RouteHint(vec![RouteHintHop {
7450 src_node_id: nodes[1].node.get_our_node_id(),
7451 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7452 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7453 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7454 htlc_minimum_msat: None,
7455 htlc_maximum_msat: None,
7457 let last_hops = vec![route_hint];
7458 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], last_hops, 10_000, TEST_FINAL_CLTV);
7460 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7461 check_added_monitors!(nodes[0], 1);
7462 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7463 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7464 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7466 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7467 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7468 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7469 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7470 assert!(htlc_fail_updates.update_fee.is_none());
7472 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7473 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7474 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7476 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7477 // to true. Sadly there is currently no way to change it at runtime.
7479 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7480 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7482 let nodes_1_serialized = nodes[1].node.encode();
7483 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7484 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7485 get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7486 get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7488 persister = test_utils::TestPersister::new();
7489 let keys_manager = &chanmon_cfgs[1].keys_manager;
7490 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);
7491 nodes[1].chain_monitor = &new_chain_monitor;
7493 let mut monitor_a_read = &monitor_a_serialized.0[..];
7494 let mut monitor_b_read = &monitor_b_serialized.0[..];
7495 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7496 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7497 assert!(monitor_a_read.is_empty());
7498 assert!(monitor_b_read.is_empty());
7500 no_announce_cfg.accept_forwards_to_priv_channels = true;
7502 let mut nodes_1_read = &nodes_1_serialized[..];
7503 let (_, nodes_1_deserialized_tmp) = {
7504 let mut channel_monitors = HashMap::new();
7505 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7506 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7507 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7508 default_config: no_announce_cfg,
7510 fee_estimator: node_cfgs[1].fee_estimator,
7511 chain_monitor: nodes[1].chain_monitor,
7512 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7513 logger: nodes[1].logger,
7517 assert!(nodes_1_read.is_empty());
7518 nodes_1_deserialized = nodes_1_deserialized_tmp;
7520 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7521 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7522 check_added_monitors!(nodes[1], 2);
7523 nodes[1].node = &nodes_1_deserialized;
7525 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7526 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7527 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7528 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7529 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7530 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7531 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7532 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7534 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7535 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7536 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7537 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7538 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7539 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7540 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7541 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7543 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7544 check_added_monitors!(nodes[0], 1);
7545 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7546 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7550 fn test_bump_penalty_txn_on_revoked_commitment() {
7551 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7552 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7554 let chanmon_cfgs = create_chanmon_cfgs(2);
7555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7557 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7559 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7561 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7562 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7563 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7565 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7566 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7567 assert_eq!(revoked_txn[0].output.len(), 4);
7568 assert_eq!(revoked_txn[0].input.len(), 1);
7569 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7570 let revoked_txid = revoked_txn[0].txid();
7572 let mut penalty_sum = 0;
7573 for outp in revoked_txn[0].output.iter() {
7574 if outp.script_pubkey.is_v0_p2wsh() {
7575 penalty_sum += outp.value;
7579 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7580 let header_114 = connect_blocks(&nodes[1], 14);
7582 // Actually revoke tx by claiming a HTLC
7583 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7584 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7585 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7586 check_added_monitors!(nodes[1], 1);
7588 // One or more justice tx should have been broadcast, check it
7592 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7593 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7594 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7595 assert_eq!(node_txn[0].output.len(), 1);
7596 check_spends!(node_txn[0], revoked_txn[0]);
7597 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7598 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7599 penalty_1 = node_txn[0].txid();
7603 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7604 connect_blocks(&nodes[1], 15);
7605 let mut penalty_2 = penalty_1;
7606 let mut feerate_2 = 0;
7608 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7609 assert_eq!(node_txn.len(), 1);
7610 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7611 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7612 assert_eq!(node_txn[0].output.len(), 1);
7613 check_spends!(node_txn[0], revoked_txn[0]);
7614 penalty_2 = node_txn[0].txid();
7615 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7616 assert_ne!(penalty_2, penalty_1);
7617 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7618 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7619 // Verify 25% bump heuristic
7620 assert!(feerate_2 * 100 >= feerate_1 * 125);
7624 assert_ne!(feerate_2, 0);
7626 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7627 connect_blocks(&nodes[1], 1);
7629 let mut feerate_3 = 0;
7631 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7632 assert_eq!(node_txn.len(), 1);
7633 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7634 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7635 assert_eq!(node_txn[0].output.len(), 1);
7636 check_spends!(node_txn[0], revoked_txn[0]);
7637 penalty_3 = node_txn[0].txid();
7638 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7639 assert_ne!(penalty_3, penalty_2);
7640 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7641 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7642 // Verify 25% bump heuristic
7643 assert!(feerate_3 * 100 >= feerate_2 * 125);
7647 assert_ne!(feerate_3, 0);
7649 nodes[1].node.get_and_clear_pending_events();
7650 nodes[1].node.get_and_clear_pending_msg_events();
7654 fn test_bump_penalty_txn_on_revoked_htlcs() {
7655 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7656 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7658 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7659 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7662 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7664 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7665 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7666 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7667 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7668 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, &nodes[0].network_graph, None,
7669 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7670 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7671 let payee = Payee::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7672 let route = get_route(&nodes[1].node.get_our_node_id(), &payee, nodes[1].network_graph, None,
7673 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7674 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7676 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7677 assert_eq!(revoked_local_txn[0].input.len(), 1);
7678 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7680 // Revoke local commitment tx
7681 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7683 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7684 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7685 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7686 check_closed_broadcast!(nodes[1], true);
7687 check_added_monitors!(nodes[1], 1);
7688 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7689 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7691 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7692 assert_eq!(revoked_htlc_txn.len(), 3);
7693 check_spends!(revoked_htlc_txn[1], chan.3);
7695 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7696 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7697 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7699 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7700 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7701 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7702 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7704 // Broadcast set of revoked txn on A
7705 let hash_128 = connect_blocks(&nodes[0], 40);
7706 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7707 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7708 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7709 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7710 let events = nodes[0].node.get_and_clear_pending_events();
7711 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7713 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7714 _ => panic!("Unexpected event"),
7720 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7721 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7722 // Verify claim tx are spending revoked HTLC txn
7724 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7725 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7726 // which are included in the same block (they are broadcasted because we scan the
7727 // transactions linearly and generate claims as we go, they likely should be removed in the
7729 assert_eq!(node_txn[0].input.len(), 1);
7730 check_spends!(node_txn[0], revoked_local_txn[0]);
7731 assert_eq!(node_txn[1].input.len(), 1);
7732 check_spends!(node_txn[1], revoked_local_txn[0]);
7733 assert_eq!(node_txn[2].input.len(), 1);
7734 check_spends!(node_txn[2], revoked_local_txn[0]);
7736 // Each of the three justice transactions claim a separate (single) output of the three
7737 // available, which we check here:
7738 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7739 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7740 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7742 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7743 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7745 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7746 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7747 // a remote commitment tx has already been confirmed).
7748 check_spends!(node_txn[3], chan.3);
7750 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7751 // output, checked above).
7752 assert_eq!(node_txn[4].input.len(), 2);
7753 assert_eq!(node_txn[4].output.len(), 1);
7754 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7756 first = node_txn[4].txid();
7757 // Store both feerates for later comparison
7758 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7759 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7760 penalty_txn = vec![node_txn[2].clone()];
7764 // Connect one more block to see if bumped penalty are issued for HTLC txn
7765 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7766 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7767 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7768 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7770 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7771 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7773 check_spends!(node_txn[0], revoked_local_txn[0]);
7774 check_spends!(node_txn[1], revoked_local_txn[0]);
7775 // Note that these are both bogus - they spend outputs already claimed in block 129:
7776 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7777 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7779 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7780 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7786 // Few more blocks to confirm penalty txn
7787 connect_blocks(&nodes[0], 4);
7788 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7789 let header_144 = connect_blocks(&nodes[0], 9);
7791 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7792 assert_eq!(node_txn.len(), 1);
7794 assert_eq!(node_txn[0].input.len(), 2);
7795 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7796 // Verify bumped tx is different and 25% bump heuristic
7797 assert_ne!(first, node_txn[0].txid());
7798 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7799 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7800 assert!(feerate_2 * 100 > feerate_1 * 125);
7801 let txn = vec![node_txn[0].clone()];
7805 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7806 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7807 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7808 connect_blocks(&nodes[0], 20);
7810 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7811 // We verify than no new transaction has been broadcast because previously
7812 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7813 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7814 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7815 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7816 // up bumped justice generation.
7817 assert_eq!(node_txn.len(), 0);
7820 check_closed_broadcast!(nodes[0], true);
7821 check_added_monitors!(nodes[0], 1);
7825 fn test_bump_penalty_txn_on_remote_commitment() {
7826 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7827 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7830 // Provide preimage for one
7831 // Check aggregation
7833 let chanmon_cfgs = create_chanmon_cfgs(2);
7834 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7835 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7836 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7838 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7839 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7840 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7842 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7843 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7844 assert_eq!(remote_txn[0].output.len(), 4);
7845 assert_eq!(remote_txn[0].input.len(), 1);
7846 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7848 // Claim a HTLC without revocation (provide B monitor with preimage)
7849 nodes[1].node.claim_funds(payment_preimage);
7850 mine_transaction(&nodes[1], &remote_txn[0]);
7851 check_added_monitors!(nodes[1], 2);
7852 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7854 // One or more claim tx should have been broadcast, check it
7858 let feerate_timeout;
7859 let feerate_preimage;
7861 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7862 // 9 transactions including:
7863 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7864 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7865 // 2 * HTLC-Success (one RBF bump we'll check later)
7867 assert_eq!(node_txn.len(), 8);
7868 assert_eq!(node_txn[0].input.len(), 1);
7869 assert_eq!(node_txn[6].input.len(), 1);
7870 check_spends!(node_txn[0], remote_txn[0]);
7871 check_spends!(node_txn[6], remote_txn[0]);
7872 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7873 preimage_bump = node_txn[3].clone();
7875 check_spends!(node_txn[1], chan.3);
7876 check_spends!(node_txn[2], node_txn[1]);
7877 assert_eq!(node_txn[1], node_txn[4]);
7878 assert_eq!(node_txn[2], node_txn[5]);
7880 timeout = node_txn[6].txid();
7881 let index = node_txn[6].input[0].previous_output.vout;
7882 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7883 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7885 preimage = node_txn[0].txid();
7886 let index = node_txn[0].input[0].previous_output.vout;
7887 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7888 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7892 assert_ne!(feerate_timeout, 0);
7893 assert_ne!(feerate_preimage, 0);
7895 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7896 connect_blocks(&nodes[1], 15);
7898 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7899 assert_eq!(node_txn.len(), 1);
7900 assert_eq!(node_txn[0].input.len(), 1);
7901 assert_eq!(preimage_bump.input.len(), 1);
7902 check_spends!(node_txn[0], remote_txn[0]);
7903 check_spends!(preimage_bump, remote_txn[0]);
7905 let index = preimage_bump.input[0].previous_output.vout;
7906 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7907 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7908 assert!(new_feerate * 100 > feerate_timeout * 125);
7909 assert_ne!(timeout, preimage_bump.txid());
7911 let index = node_txn[0].input[0].previous_output.vout;
7912 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7913 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7914 assert!(new_feerate * 100 > feerate_preimage * 125);
7915 assert_ne!(preimage, node_txn[0].txid());
7920 nodes[1].node.get_and_clear_pending_events();
7921 nodes[1].node.get_and_clear_pending_msg_events();
7925 fn test_counterparty_raa_skip_no_crash() {
7926 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7927 // commitment transaction, we would have happily carried on and provided them the next
7928 // commitment transaction based on one RAA forward. This would probably eventually have led to
7929 // channel closure, but it would not have resulted in funds loss. Still, our
7930 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7931 // check simply that the channel is closed in response to such an RAA, but don't check whether
7932 // we decide to punish our counterparty for revoking their funds (as we don't currently
7934 let chanmon_cfgs = create_chanmon_cfgs(2);
7935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7938 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7940 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7941 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7943 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7945 // Make signer believe we got a counterparty signature, so that it allows the revocation
7946 keys.get_enforcement_state().last_holder_commitment -= 1;
7947 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7949 // Must revoke without gaps
7950 keys.get_enforcement_state().last_holder_commitment -= 1;
7951 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7953 keys.get_enforcement_state().last_holder_commitment -= 1;
7954 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7955 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7957 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7958 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7959 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7960 check_added_monitors!(nodes[1], 1);
7961 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7965 fn test_bump_txn_sanitize_tracking_maps() {
7966 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7967 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7969 let chanmon_cfgs = create_chanmon_cfgs(2);
7970 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7971 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7972 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7974 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7975 // Lock HTLC in both directions
7976 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7977 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7979 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7980 assert_eq!(revoked_local_txn[0].input.len(), 1);
7981 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7983 // Revoke local commitment tx
7984 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7986 // Broadcast set of revoked txn on A
7987 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7988 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7989 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7991 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7992 check_closed_broadcast!(nodes[0], true);
7993 check_added_monitors!(nodes[0], 1);
7994 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7996 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7997 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7998 check_spends!(node_txn[0], revoked_local_txn[0]);
7999 check_spends!(node_txn[1], revoked_local_txn[0]);
8000 check_spends!(node_txn[2], revoked_local_txn[0]);
8001 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8005 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8006 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8007 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8009 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
8010 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8011 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8016 fn test_channel_conf_timeout() {
8017 // Tests that, for inbound channels, we give up on them if the funding transaction does not
8018 // confirm within 2016 blocks, as recommended by BOLT 2.
8019 let chanmon_cfgs = create_chanmon_cfgs(2);
8020 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8021 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8022 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8024 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
8026 // The outbound node should wait forever for confirmation:
8027 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
8028 // copied here instead of directly referencing the constant.
8029 connect_blocks(&nodes[0], 2016);
8030 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8032 // The inbound node should fail the channel after exactly 2016 blocks
8033 connect_blocks(&nodes[1], 2015);
8034 check_added_monitors!(nodes[1], 0);
8035 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8037 connect_blocks(&nodes[1], 1);
8038 check_added_monitors!(nodes[1], 1);
8039 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8040 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8041 assert_eq!(close_ev.len(), 1);
8043 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8044 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8045 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8047 _ => panic!("Unexpected event"),
8052 fn test_override_channel_config() {
8053 let chanmon_cfgs = create_chanmon_cfgs(2);
8054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8056 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8058 // Node0 initiates a channel to node1 using the override config.
8059 let mut override_config = UserConfig::default();
8060 override_config.own_channel_config.our_to_self_delay = 200;
8062 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8064 // Assert the channel created by node0 is using the override config.
8065 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8066 assert_eq!(res.channel_flags, 0);
8067 assert_eq!(res.to_self_delay, 200);
8071 fn test_override_0msat_htlc_minimum() {
8072 let mut zero_config = UserConfig::default();
8073 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8074 let chanmon_cfgs = create_chanmon_cfgs(2);
8075 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8076 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8077 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8079 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8080 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8081 assert_eq!(res.htlc_minimum_msat, 1);
8083 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8084 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8085 assert_eq!(res.htlc_minimum_msat, 1);
8089 fn test_simple_mpp() {
8090 // Simple test of sending a multi-path payment.
8091 let chanmon_cfgs = create_chanmon_cfgs(4);
8092 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8093 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8094 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8096 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8097 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8098 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8099 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8101 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8102 let path = route.paths[0].clone();
8103 route.paths.push(path);
8104 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8105 route.paths[0][0].short_channel_id = chan_1_id;
8106 route.paths[0][1].short_channel_id = chan_3_id;
8107 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8108 route.paths[1][0].short_channel_id = chan_2_id;
8109 route.paths[1][1].short_channel_id = chan_4_id;
8110 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8111 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8115 fn test_preimage_storage() {
8116 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8117 let chanmon_cfgs = create_chanmon_cfgs(2);
8118 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8120 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8122 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8125 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200);
8126 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8127 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8128 check_added_monitors!(nodes[0], 1);
8129 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8130 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8131 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8132 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8134 // Note that after leaving the above scope we have no knowledge of any arguments or return
8135 // values from previous calls.
8136 expect_pending_htlcs_forwardable!(nodes[1]);
8137 let events = nodes[1].node.get_and_clear_pending_events();
8138 assert_eq!(events.len(), 1);
8140 Event::PaymentReceived { ref purpose, .. } => {
8142 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8143 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8145 _ => panic!("expected PaymentPurpose::InvoicePayment")
8148 _ => panic!("Unexpected event"),
8153 fn test_secret_timeout() {
8154 // Simple test of payment secret storage time outs
8155 let chanmon_cfgs = create_chanmon_cfgs(2);
8156 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8157 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8158 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8160 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8162 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2);
8164 // We should fail to register the same payment hash twice, at least until we've connected a
8165 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8166 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2) {
8167 assert_eq!(err, "Duplicate payment hash");
8168 } else { panic!(); }
8170 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8172 header: BlockHeader {
8174 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8175 merkle_root: Default::default(),
8176 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8180 connect_block(&nodes[1], &block);
8181 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2) {
8182 assert_eq!(err, "Duplicate payment hash");
8183 } else { panic!(); }
8185 // If we then connect the second block, we should be able to register the same payment hash
8186 // again (this time getting a new payment secret).
8187 block.header.prev_blockhash = block.header.block_hash();
8188 block.header.time += 1;
8189 connect_block(&nodes[1], &block);
8190 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2).unwrap();
8191 assert_ne!(payment_secret_1, our_payment_secret);
8194 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8195 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8196 check_added_monitors!(nodes[0], 1);
8197 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8198 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8199 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8200 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8202 // Note that after leaving the above scope we have no knowledge of any arguments or return
8203 // values from previous calls.
8204 expect_pending_htlcs_forwardable!(nodes[1]);
8205 let events = nodes[1].node.get_and_clear_pending_events();
8206 assert_eq!(events.len(), 1);
8208 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8209 assert!(payment_preimage.is_none());
8210 assert_eq!(payment_secret, our_payment_secret);
8211 // We don't actually have the payment preimage with which to claim this payment!
8213 _ => panic!("Unexpected event"),
8218 fn test_bad_secret_hash() {
8219 // Simple test of unregistered payment hash/invalid payment secret handling
8220 let chanmon_cfgs = create_chanmon_cfgs(2);
8221 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8222 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8223 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8225 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8227 let random_payment_hash = PaymentHash([42; 32]);
8228 let random_payment_secret = PaymentSecret([43; 32]);
8229 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2);
8230 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8232 // All the below cases should end up being handled exactly identically, so we macro the
8233 // resulting events.
8234 macro_rules! handle_unknown_invalid_payment_data {
8236 check_added_monitors!(nodes[0], 1);
8237 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8238 let payment_event = SendEvent::from_event(events.pop().unwrap());
8239 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8240 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8242 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8243 // again to process the pending backwards-failure of the HTLC
8244 expect_pending_htlcs_forwardable!(nodes[1]);
8245 expect_pending_htlcs_forwardable!(nodes[1]);
8246 check_added_monitors!(nodes[1], 1);
8248 // We should fail the payment back
8249 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8250 match events.pop().unwrap() {
8251 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8252 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8253 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8255 _ => panic!("Unexpected event"),
8260 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8261 // Error data is the HTLC value (100,000) and current block height
8262 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8264 // Send a payment with the right payment hash but the wrong payment secret
8265 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8266 handle_unknown_invalid_payment_data!();
8267 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8269 // Send a payment with a random payment hash, but the right payment secret
8270 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8271 handle_unknown_invalid_payment_data!();
8272 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8274 // Send a payment with a random payment hash and random payment secret
8275 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8276 handle_unknown_invalid_payment_data!();
8277 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8281 fn test_update_err_monitor_lockdown() {
8282 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8283 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8284 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8286 // This scenario may happen in a watchtower setup, where watchtower process a block height
8287 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8288 // commitment at same time.
8290 let chanmon_cfgs = create_chanmon_cfgs(2);
8291 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8292 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8293 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8295 // Create some initial channel
8296 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8297 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8299 // Rebalance the network to generate htlc in the two directions
8300 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8302 // Route a HTLC from node 0 to node 1 (but don't settle)
8303 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8305 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8306 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8307 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8308 let persister = test_utils::TestPersister::new();
8310 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8311 let mut w = test_utils::TestVecWriter(Vec::new());
8312 monitor.write(&mut w).unwrap();
8313 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8314 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8315 assert!(new_monitor == *monitor);
8316 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);
8317 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8320 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8321 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8322 // transaction lock time requirements here.
8323 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8324 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8326 // Try to update ChannelMonitor
8327 assert!(nodes[1].node.claim_funds(preimage));
8328 check_added_monitors!(nodes[1], 1);
8329 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8330 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8331 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8332 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8333 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8334 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8335 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8336 } else { assert!(false); }
8337 } else { assert!(false); };
8338 // Our local monitor is in-sync and hasn't processed yet timeout
8339 check_added_monitors!(nodes[0], 1);
8340 let events = nodes[0].node.get_and_clear_pending_events();
8341 assert_eq!(events.len(), 1);
8345 fn test_concurrent_monitor_claim() {
8346 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8347 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8348 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8349 // state N+1 confirms. Alice claims output from state N+1.
8351 let chanmon_cfgs = create_chanmon_cfgs(2);
8352 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8353 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8354 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8356 // Create some initial channel
8357 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8358 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8360 // Rebalance the network to generate htlc in the two directions
8361 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8363 // Route a HTLC from node 0 to node 1 (but don't settle)
8364 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8366 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8367 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8368 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8369 let persister = test_utils::TestPersister::new();
8370 let watchtower_alice = {
8371 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8372 let mut w = test_utils::TestVecWriter(Vec::new());
8373 monitor.write(&mut w).unwrap();
8374 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8375 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8376 assert!(new_monitor == *monitor);
8377 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);
8378 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8381 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8382 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8383 // transaction lock time requirements here.
8384 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8385 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8387 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8389 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8390 assert_eq!(txn.len(), 2);
8394 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8395 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8396 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8397 let persister = test_utils::TestPersister::new();
8398 let watchtower_bob = {
8399 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8400 let mut w = test_utils::TestVecWriter(Vec::new());
8401 monitor.write(&mut w).unwrap();
8402 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8403 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8404 assert!(new_monitor == *monitor);
8405 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);
8406 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8409 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8410 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8412 // Route another payment to generate another update with still previous HTLC pending
8413 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8415 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8417 check_added_monitors!(nodes[1], 1);
8419 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8420 assert_eq!(updates.update_add_htlcs.len(), 1);
8421 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8422 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8423 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8424 // Watchtower Alice should already have seen the block and reject the update
8425 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8426 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8427 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8428 } else { assert!(false); }
8429 } else { assert!(false); };
8430 // Our local monitor is in-sync and hasn't processed yet timeout
8431 check_added_monitors!(nodes[0], 1);
8433 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8434 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8435 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8437 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8440 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8441 assert_eq!(txn.len(), 2);
8442 bob_state_y = txn[0].clone();
8446 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8447 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8448 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);
8450 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8451 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8452 // the onchain detection of the HTLC output
8453 assert_eq!(htlc_txn.len(), 2);
8454 check_spends!(htlc_txn[0], bob_state_y);
8455 check_spends!(htlc_txn[1], bob_state_y);
8460 fn test_pre_lockin_no_chan_closed_update() {
8461 // Test that if a peer closes a channel in response to a funding_created message we don't
8462 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8465 // Doing so would imply a channel monitor update before the initial channel monitor
8466 // registration, violating our API guarantees.
8468 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8469 // then opening a second channel with the same funding output as the first (which is not
8470 // rejected because the first channel does not exist in the ChannelManager) and closing it
8471 // before receiving funding_signed.
8472 let chanmon_cfgs = create_chanmon_cfgs(2);
8473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8477 // Create an initial channel
8478 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8479 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8480 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8481 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8482 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8484 // Move the first channel through the funding flow...
8485 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8487 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8488 check_added_monitors!(nodes[0], 0);
8490 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8491 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8492 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8493 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8494 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8498 fn test_htlc_no_detection() {
8499 // This test is a mutation to underscore the detection logic bug we had
8500 // before #653. HTLC value routed is above the remaining balance, thus
8501 // inverting HTLC and `to_remote` output. HTLC will come second and
8502 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8503 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8504 // outputs order detection for correct spending children filtring.
8506 let chanmon_cfgs = create_chanmon_cfgs(2);
8507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8511 // Create some initial channels
8512 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8514 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8515 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8516 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8517 assert_eq!(local_txn[0].input.len(), 1);
8518 assert_eq!(local_txn[0].output.len(), 3);
8519 check_spends!(local_txn[0], chan_1.3);
8521 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8522 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8523 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8524 // We deliberately connect the local tx twice as this should provoke a failure calling
8525 // this test before #653 fix.
8526 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);
8527 check_closed_broadcast!(nodes[0], true);
8528 check_added_monitors!(nodes[0], 1);
8529 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8530 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8532 let htlc_timeout = {
8533 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8534 assert_eq!(node_txn[1].input.len(), 1);
8535 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8536 check_spends!(node_txn[1], local_txn[0]);
8540 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8541 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8542 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8543 expect_payment_failed!(nodes[0], our_payment_hash, true);
8546 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8547 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8548 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8549 // Carol, Alice would be the upstream node, and Carol the downstream.)
8551 // Steps of the test:
8552 // 1) Alice sends a HTLC to Carol through Bob.
8553 // 2) Carol doesn't settle the HTLC.
8554 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8555 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8556 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8557 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8558 // 5) Carol release the preimage to Bob off-chain.
8559 // 6) Bob claims the offered output on the broadcasted commitment.
8560 let chanmon_cfgs = create_chanmon_cfgs(3);
8561 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8562 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8563 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8565 // Create some initial channels
8566 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8567 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8569 // Steps (1) and (2):
8570 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8571 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8573 // Check that Alice's commitment transaction now contains an output for this HTLC.
8574 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8575 check_spends!(alice_txn[0], chan_ab.3);
8576 assert_eq!(alice_txn[0].output.len(), 2);
8577 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8578 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8579 assert_eq!(alice_txn.len(), 2);
8581 // Steps (3) and (4):
8582 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8583 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8584 let mut force_closing_node = 0; // Alice force-closes
8585 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8586 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8587 check_closed_broadcast!(nodes[force_closing_node], true);
8588 check_added_monitors!(nodes[force_closing_node], 1);
8589 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8590 if go_onchain_before_fulfill {
8591 let txn_to_broadcast = match broadcast_alice {
8592 true => alice_txn.clone(),
8593 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8595 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8596 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8597 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8598 if broadcast_alice {
8599 check_closed_broadcast!(nodes[1], true);
8600 check_added_monitors!(nodes[1], 1);
8601 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8603 assert_eq!(bob_txn.len(), 1);
8604 check_spends!(bob_txn[0], chan_ab.3);
8608 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8609 // process of removing the HTLC from their commitment transactions.
8610 assert!(nodes[2].node.claim_funds(payment_preimage));
8611 check_added_monitors!(nodes[2], 1);
8612 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8613 assert!(carol_updates.update_add_htlcs.is_empty());
8614 assert!(carol_updates.update_fail_htlcs.is_empty());
8615 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8616 assert!(carol_updates.update_fee.is_none());
8617 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8619 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8620 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8621 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8622 if !go_onchain_before_fulfill && broadcast_alice {
8623 let events = nodes[1].node.get_and_clear_pending_msg_events();
8624 assert_eq!(events.len(), 1);
8626 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8627 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8629 _ => panic!("Unexpected event"),
8632 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8633 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8634 // Carol<->Bob's updated commitment transaction info.
8635 check_added_monitors!(nodes[1], 2);
8637 let events = nodes[1].node.get_and_clear_pending_msg_events();
8638 assert_eq!(events.len(), 2);
8639 let bob_revocation = match events[0] {
8640 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8641 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8644 _ => panic!("Unexpected event"),
8646 let bob_updates = match events[1] {
8647 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8648 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8651 _ => panic!("Unexpected event"),
8654 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8655 check_added_monitors!(nodes[2], 1);
8656 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8657 check_added_monitors!(nodes[2], 1);
8659 let events = nodes[2].node.get_and_clear_pending_msg_events();
8660 assert_eq!(events.len(), 1);
8661 let carol_revocation = match events[0] {
8662 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8663 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8666 _ => panic!("Unexpected event"),
8668 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8669 check_added_monitors!(nodes[1], 1);
8671 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8672 // here's where we put said channel's commitment tx on-chain.
8673 let mut txn_to_broadcast = alice_txn.clone();
8674 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8675 if !go_onchain_before_fulfill {
8676 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8677 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8678 // If Bob was the one to force-close, he will have already passed these checks earlier.
8679 if broadcast_alice {
8680 check_closed_broadcast!(nodes[1], true);
8681 check_added_monitors!(nodes[1], 1);
8682 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8684 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8685 if broadcast_alice {
8686 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8687 // new block being connected. The ChannelManager being notified triggers a monitor update,
8688 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8689 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8691 assert_eq!(bob_txn.len(), 3);
8692 check_spends!(bob_txn[1], chan_ab.3);
8694 assert_eq!(bob_txn.len(), 2);
8695 check_spends!(bob_txn[0], chan_ab.3);
8700 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8701 // broadcasted commitment transaction.
8703 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8704 if go_onchain_before_fulfill {
8705 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8706 assert_eq!(bob_txn.len(), 2);
8708 let script_weight = match broadcast_alice {
8709 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8710 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8712 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8713 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8714 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8715 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8716 if broadcast_alice && !go_onchain_before_fulfill {
8717 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8718 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8720 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8721 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8727 fn test_onchain_htlc_settlement_after_close() {
8728 do_test_onchain_htlc_settlement_after_close(true, true);
8729 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8730 do_test_onchain_htlc_settlement_after_close(true, false);
8731 do_test_onchain_htlc_settlement_after_close(false, false);
8735 fn test_duplicate_chan_id() {
8736 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8737 // already open we reject it and keep the old channel.
8739 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8740 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8741 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8742 // updating logic for the existing channel.
8743 let chanmon_cfgs = create_chanmon_cfgs(2);
8744 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8745 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8746 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8748 // Create an initial channel
8749 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8750 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8751 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8752 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()));
8754 // Try to create a second channel with the same temporary_channel_id as the first and check
8755 // that it is rejected.
8756 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8758 let events = nodes[1].node.get_and_clear_pending_msg_events();
8759 assert_eq!(events.len(), 1);
8761 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8762 // Technically, at this point, nodes[1] would be justified in thinking both the
8763 // first (valid) and second (invalid) channels are closed, given they both have
8764 // the same non-temporary channel_id. However, currently we do not, so we just
8765 // move forward with it.
8766 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8767 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8769 _ => panic!("Unexpected event"),
8773 // Move the first channel through the funding flow...
8774 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8776 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8777 check_added_monitors!(nodes[0], 0);
8779 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8780 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8782 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8783 assert_eq!(added_monitors.len(), 1);
8784 assert_eq!(added_monitors[0].0, funding_output);
8785 added_monitors.clear();
8787 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8789 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8790 let channel_id = funding_outpoint.to_channel_id();
8792 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8795 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8796 // Technically this is allowed by the spec, but we don't support it and there's little reason
8797 // to. Still, it shouldn't cause any other issues.
8798 open_chan_msg.temporary_channel_id = channel_id;
8799 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8801 let events = nodes[1].node.get_and_clear_pending_msg_events();
8802 assert_eq!(events.len(), 1);
8804 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8805 // Technically, at this point, nodes[1] would be justified in thinking both
8806 // channels are closed, but currently we do not, so we just move forward with it.
8807 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8808 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8810 _ => panic!("Unexpected event"),
8814 // Now try to create a second channel which has a duplicate funding output.
8815 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8816 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8817 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8818 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()));
8819 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8821 let funding_created = {
8822 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8823 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8824 let logger = test_utils::TestLogger::new();
8825 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8827 check_added_monitors!(nodes[0], 0);
8828 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8829 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8830 // still needs to be cleared here.
8831 check_added_monitors!(nodes[1], 1);
8833 // ...still, nodes[1] will reject the duplicate channel.
8835 let events = nodes[1].node.get_and_clear_pending_msg_events();
8836 assert_eq!(events.len(), 1);
8838 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8839 // Technically, at this point, nodes[1] would be justified in thinking both
8840 // channels are closed, but currently we do not, so we just move forward with it.
8841 assert_eq!(msg.channel_id, channel_id);
8842 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8844 _ => panic!("Unexpected event"),
8848 // finally, finish creating the original channel and send a payment over it to make sure
8849 // everything is functional.
8850 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8852 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8853 assert_eq!(added_monitors.len(), 1);
8854 assert_eq!(added_monitors[0].0, funding_output);
8855 added_monitors.clear();
8858 let events_4 = nodes[0].node.get_and_clear_pending_events();
8859 assert_eq!(events_4.len(), 0);
8860 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8861 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8863 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8864 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8865 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8866 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8870 fn test_error_chans_closed() {
8871 // Test that we properly handle error messages, closing appropriate channels.
8873 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8874 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8875 // we can test various edge cases around it to ensure we don't regress.
8876 let chanmon_cfgs = create_chanmon_cfgs(3);
8877 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8878 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8879 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8881 // Create some initial channels
8882 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8883 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8884 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8886 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8887 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8888 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8890 // Closing a channel from a different peer has no effect
8891 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8892 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8894 // Closing one channel doesn't impact others
8895 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8896 check_added_monitors!(nodes[0], 1);
8897 check_closed_broadcast!(nodes[0], false);
8898 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8899 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8900 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8901 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);
8902 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);
8904 // A null channel ID should close all channels
8905 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8906 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8907 check_added_monitors!(nodes[0], 2);
8908 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8909 let events = nodes[0].node.get_and_clear_pending_msg_events();
8910 assert_eq!(events.len(), 2);
8912 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8913 assert_eq!(msg.contents.flags & 2, 2);
8915 _ => panic!("Unexpected event"),
8918 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8919 assert_eq!(msg.contents.flags & 2, 2);
8921 _ => panic!("Unexpected event"),
8923 // Note that at this point users of a standard PeerHandler will end up calling
8924 // peer_disconnected with no_connection_possible set to false, duplicating the
8925 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8926 // users with their own peer handling logic. We duplicate the call here, however.
8927 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8928 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8930 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8931 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8932 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8936 fn test_invalid_funding_tx() {
8937 // Test that we properly handle invalid funding transactions sent to us from a peer.
8939 // Previously, all other major lightning implementations had failed to properly sanitize
8940 // funding transactions from their counterparties, leading to a multi-implementation critical
8941 // security vulnerability (though we always sanitized properly, we've previously had
8942 // un-released crashes in the sanitization process).
8943 let chanmon_cfgs = create_chanmon_cfgs(2);
8944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8946 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8948 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8949 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()));
8950 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()));
8952 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8953 for output in tx.output.iter_mut() {
8954 // Make the confirmed funding transaction have a bogus script_pubkey
8955 output.script_pubkey = bitcoin::Script::new();
8958 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8959 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()));
8960 check_added_monitors!(nodes[1], 1);
8962 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()));
8963 check_added_monitors!(nodes[0], 1);
8965 let events_1 = nodes[0].node.get_and_clear_pending_events();
8966 assert_eq!(events_1.len(), 0);
8968 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8969 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8970 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8972 let expected_err = "funding tx had wrong script/value or output index";
8973 confirm_transaction_at(&nodes[1], &tx, 1);
8974 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8975 check_added_monitors!(nodes[1], 1);
8976 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8977 assert_eq!(events_2.len(), 1);
8978 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8979 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8980 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8981 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8982 } else { panic!(); }
8983 } else { panic!(); }
8984 assert_eq!(nodes[1].node.list_channels().len(), 0);
8987 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8988 // In the first version of the chain::Confirm interface, after a refactor was made to not
8989 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8990 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8991 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8992 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8993 // spending transaction until height N+1 (or greater). This was due to the way
8994 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8995 // spending transaction at the height the input transaction was confirmed at, not whether we
8996 // should broadcast a spending transaction at the current height.
8997 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8998 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8999 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9000 // until we learned about an additional block.
9002 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9003 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9004 let chanmon_cfgs = create_chanmon_cfgs(3);
9005 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9006 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9007 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9008 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9010 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9011 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9012 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9013 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9014 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9016 nodes[1].node.force_close_channel(&channel_id).unwrap();
9017 check_closed_broadcast!(nodes[1], true);
9018 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9019 check_added_monitors!(nodes[1], 1);
9020 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9021 assert_eq!(node_txn.len(), 1);
9023 let conf_height = nodes[1].best_block_info().1;
9024 if !test_height_before_timelock {
9025 connect_blocks(&nodes[1], 24 * 6);
9027 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9028 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9029 if test_height_before_timelock {
9030 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9031 // generate any events or broadcast any transactions
9032 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9033 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9035 // We should broadcast an HTLC transaction spending our funding transaction first
9036 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9037 assert_eq!(spending_txn.len(), 2);
9038 assert_eq!(spending_txn[0], node_txn[0]);
9039 check_spends!(spending_txn[1], node_txn[0]);
9040 // We should also generate a SpendableOutputs event with the to_self output (as its
9042 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9043 assert_eq!(descriptor_spend_txn.len(), 1);
9045 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9046 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9047 // additional block built on top of the current chain.
9048 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9049 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9050 expect_pending_htlcs_forwardable!(nodes[1]);
9051 check_added_monitors!(nodes[1], 1);
9053 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9054 assert!(updates.update_add_htlcs.is_empty());
9055 assert!(updates.update_fulfill_htlcs.is_empty());
9056 assert_eq!(updates.update_fail_htlcs.len(), 1);
9057 assert!(updates.update_fail_malformed_htlcs.is_empty());
9058 assert!(updates.update_fee.is_none());
9059 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9060 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9061 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9066 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9067 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9068 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9072 fn test_forwardable_regen() {
9073 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9074 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9076 // We test it for both payment receipt and payment forwarding.
9078 let chanmon_cfgs = create_chanmon_cfgs(3);
9079 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9080 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9081 let persister: test_utils::TestPersister;
9082 let new_chain_monitor: test_utils::TestChainMonitor;
9083 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9084 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9085 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9086 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9088 // First send a payment to nodes[1]
9089 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9090 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9091 check_added_monitors!(nodes[0], 1);
9093 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9094 assert_eq!(events.len(), 1);
9095 let payment_event = SendEvent::from_event(events.pop().unwrap());
9096 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9097 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9099 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9101 // Next send a payment which is forwarded by nodes[1]
9102 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9103 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9104 check_added_monitors!(nodes[0], 1);
9106 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9107 assert_eq!(events.len(), 1);
9108 let payment_event = SendEvent::from_event(events.pop().unwrap());
9109 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9110 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9112 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9114 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9116 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9117 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9118 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9120 let nodes_1_serialized = nodes[1].node.encode();
9121 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9122 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9123 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9124 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9126 persister = test_utils::TestPersister::new();
9127 let keys_manager = &chanmon_cfgs[1].keys_manager;
9128 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);
9129 nodes[1].chain_monitor = &new_chain_monitor;
9131 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9132 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9133 &mut chan_0_monitor_read, keys_manager).unwrap();
9134 assert!(chan_0_monitor_read.is_empty());
9135 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9136 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9137 &mut chan_1_monitor_read, keys_manager).unwrap();
9138 assert!(chan_1_monitor_read.is_empty());
9140 let mut nodes_1_read = &nodes_1_serialized[..];
9141 let (_, nodes_1_deserialized_tmp) = {
9142 let mut channel_monitors = HashMap::new();
9143 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9144 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9145 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9146 default_config: UserConfig::default(),
9148 fee_estimator: node_cfgs[1].fee_estimator,
9149 chain_monitor: nodes[1].chain_monitor,
9150 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9151 logger: nodes[1].logger,
9155 nodes_1_deserialized = nodes_1_deserialized_tmp;
9156 assert!(nodes_1_read.is_empty());
9158 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9159 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9160 nodes[1].node = &nodes_1_deserialized;
9161 check_added_monitors!(nodes[1], 2);
9163 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9164 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9165 // the commitment state.
9166 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9168 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9170 expect_pending_htlcs_forwardable!(nodes[1]);
9171 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9172 check_added_monitors!(nodes[1], 1);
9174 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9175 assert_eq!(events.len(), 1);
9176 let payment_event = SendEvent::from_event(events.pop().unwrap());
9177 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9178 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9179 expect_pending_htlcs_forwardable!(nodes[2]);
9180 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9182 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9183 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9187 fn test_keysend_payments_to_public_node() {
9188 let chanmon_cfgs = create_chanmon_cfgs(2);
9189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9190 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9191 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9193 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9194 let network_graph = nodes[0].network_graph;
9195 let payer_pubkey = nodes[0].node.get_our_node_id();
9196 let payee_pubkey = nodes[1].node.get_our_node_id();
9197 let params = RouteParameters {
9198 payee: Payee::for_keysend(payee_pubkey),
9199 final_value_msat: 10000,
9200 final_cltv_expiry_delta: 40,
9202 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9203 let route = find_route(&payer_pubkey, ¶ms, network_graph, None, nodes[0].logger, &scorer).unwrap();
9205 let test_preimage = PaymentPreimage([42; 32]);
9206 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9207 check_added_monitors!(nodes[0], 1);
9208 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9209 assert_eq!(events.len(), 1);
9210 let event = events.pop().unwrap();
9211 let path = vec![&nodes[1]];
9212 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9213 claim_payment(&nodes[0], &path, test_preimage);
9217 fn test_keysend_payments_to_private_node() {
9218 let chanmon_cfgs = create_chanmon_cfgs(2);
9219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9221 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9223 let payer_pubkey = nodes[0].node.get_our_node_id();
9224 let payee_pubkey = nodes[1].node.get_our_node_id();
9225 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9226 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9228 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9229 let params = RouteParameters {
9230 payee: Payee::for_keysend(payee_pubkey),
9231 final_value_msat: 10000,
9232 final_cltv_expiry_delta: 40,
9234 let network_graph = nodes[0].network_graph;
9235 let first_hops = nodes[0].node.list_usable_channels();
9236 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9237 let route = find_route(
9238 &payer_pubkey, ¶ms, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9239 nodes[0].logger, &scorer
9242 let test_preimage = PaymentPreimage([42; 32]);
9243 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9244 check_added_monitors!(nodes[0], 1);
9245 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9246 assert_eq!(events.len(), 1);
9247 let event = events.pop().unwrap();
9248 let path = vec![&nodes[1]];
9249 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9250 claim_payment(&nodes[0], &path, test_preimage);
9253 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9254 #[derive(Clone, Copy, PartialEq)]
9255 enum ExposureEvent {
9256 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9258 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9260 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9261 AtUpdateFeeOutbound,
9264 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9265 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9268 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9269 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9270 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9271 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9272 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9273 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9274 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9275 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9277 let chanmon_cfgs = create_chanmon_cfgs(2);
9278 let mut config = test_default_channel_config();
9279 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9280 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9281 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9282 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9284 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9285 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9286 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9287 open_channel.max_accepted_htlcs = 60;
9289 open_channel.dust_limit_satoshis = 546;
9291 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9292 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9293 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9295 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9298 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9299 chan.holder_dust_limit_satoshis = 546;
9303 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9304 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()));
9305 check_added_monitors!(nodes[1], 1);
9307 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()));
9308 check_added_monitors!(nodes[0], 1);
9310 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9311 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9312 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9314 let dust_buffer_feerate = {
9315 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9316 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9317 chan.get_dust_buffer_feerate(None) as u64
9319 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_TIMEOUT_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9320 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9322 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_SUCCESS_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9323 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9325 let dust_htlc_on_counterparty_tx: u64 = 25;
9326 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9329 if dust_outbound_balance {
9330 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9331 // Outbound dust balance: 4372 sats
9332 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9333 for i in 0..dust_outbound_htlc_on_holder_tx {
9334 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9335 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9338 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9339 // Inbound dust balance: 4372 sats
9340 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9341 for _ in 0..dust_inbound_htlc_on_holder_tx {
9342 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9346 if dust_outbound_balance {
9347 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9348 // Outbound dust balance: 5000 sats
9349 for i in 0..dust_htlc_on_counterparty_tx {
9350 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9351 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9354 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9355 // Inbound dust balance: 5000 sats
9356 for _ in 0..dust_htlc_on_counterparty_tx {
9357 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9362 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9363 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9364 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 });
9365 let mut config = UserConfig::default();
9366 // With default dust exposure: 5000 sats
9368 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9369 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9370 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)));
9372 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)));
9374 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9375 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 });
9376 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9377 check_added_monitors!(nodes[1], 1);
9378 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9379 assert_eq!(events.len(), 1);
9380 let payment_event = SendEvent::from_event(events.remove(0));
9381 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9382 // With default dust exposure: 5000 sats
9384 // Outbound dust balance: 6399 sats
9385 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9386 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9387 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);
9389 // Outbound dust balance: 5200 sats
9390 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);
9392 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9393 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9394 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9396 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9397 *feerate_lock = *feerate_lock * 10;
9399 nodes[0].node.timer_tick_occurred();
9400 check_added_monitors!(nodes[0], 1);
9401 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);
9404 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9405 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9406 added_monitors.clear();
9410 fn test_max_dust_htlc_exposure() {
9411 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9412 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9413 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9414 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9415 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9416 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9417 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9418 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9419 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9420 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9421 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9422 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);