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};
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 = 253;
1455 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1456 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1457 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1458 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1459 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1461 let mut push_amt = 100_000_000;
1462 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1463 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1465 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1467 // Sending exactly enough to hit the reserve amount should be accepted
1468 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 // Set the fee rate for the channel very high, to the point where the funder
1482 // receiving 1 update_add_htlc would result in them closing the channel due
1483 // to channel reserve violation. This close could also happen if the fee went
1484 // up a more realistic amount, but many HTLCs were outstanding at the time of
1485 // the update_add_htlc.
1486 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1487 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1490 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1491 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1493 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1494 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1495 let secp_ctx = Secp256k1::new();
1496 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1497 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1498 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1499 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1500 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1501 let msg = msgs::UpdateAddHTLC {
1504 amount_msat: htlc_msat + 1,
1505 payment_hash: payment_hash,
1506 cltv_expiry: htlc_cltv,
1507 onion_routing_packet: onion_packet,
1510 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1511 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1512 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);
1513 assert_eq!(nodes[0].node.list_channels().len(), 0);
1514 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1515 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1516 check_added_monitors!(nodes[0], 1);
1517 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() });
1521 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1522 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1523 // calculating our commitment transaction fee (this was previously broken).
1524 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1525 let feerate_per_kw = 253;
1526 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1527 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1531 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1533 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1534 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1535 // transaction fee with 0 HTLCs (183 sats)).
1536 let mut push_amt = 100_000_000;
1537 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1538 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1539 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1541 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1542 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1543 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1544 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1545 // commitment transaction fee.
1546 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1548 // One more than the dust amt should fail, however.
1549 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1550 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1551 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1555 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1556 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1557 // calculating our counterparty's commitment transaction fee (this was previously broken).
1558 let chanmon_cfgs = create_chanmon_cfgs(2);
1559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1561 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1562 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1564 let payment_amt = 46000; // Dust amount
1565 // In the previous code, these first four payments would succeed.
1566 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1567 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1568 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1569 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1571 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1572 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1573 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1574 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1575 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1576 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1578 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1579 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1580 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1581 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1585 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1586 let chanmon_cfgs = create_chanmon_cfgs(3);
1587 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1589 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1590 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1591 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1594 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1595 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1596 let feerate = get_feerate!(nodes[0], chan.2);
1598 // Add a 2* and +1 for the fee spike reserve.
1599 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1600 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;
1601 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1603 // Add a pending HTLC.
1604 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1605 let payment_event_1 = {
1606 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1607 check_added_monitors!(nodes[0], 1);
1609 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1610 assert_eq!(events.len(), 1);
1611 SendEvent::from_event(events.remove(0))
1613 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1615 // Attempt to trigger a channel reserve violation --> payment failure.
1616 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1617 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;
1618 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1619 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1621 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1622 let secp_ctx = Secp256k1::new();
1623 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1624 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1625 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1626 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1627 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1628 let msg = msgs::UpdateAddHTLC {
1631 amount_msat: htlc_msat + 1,
1632 payment_hash: our_payment_hash_1,
1633 cltv_expiry: htlc_cltv,
1634 onion_routing_packet: onion_packet,
1637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1638 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1639 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1640 assert_eq!(nodes[1].node.list_channels().len(), 1);
1641 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1642 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1643 check_added_monitors!(nodes[1], 1);
1644 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1648 fn test_inbound_outbound_capacity_is_not_zero() {
1649 let chanmon_cfgs = create_chanmon_cfgs(2);
1650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1652 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1653 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1654 let channels0 = node_chanmgrs[0].list_channels();
1655 let channels1 = node_chanmgrs[1].list_channels();
1656 assert_eq!(channels0.len(), 1);
1657 assert_eq!(channels1.len(), 1);
1659 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1660 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1661 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1663 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1664 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1667 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1668 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1672 fn test_channel_reserve_holding_cell_htlcs() {
1673 let chanmon_cfgs = create_chanmon_cfgs(3);
1674 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1675 // When this test was written, the default base fee floated based on the HTLC count.
1676 // It is now fixed, so we simply set the fee to the expected value here.
1677 let mut config = test_default_channel_config();
1678 config.channel_options.forwarding_fee_base_msat = 239;
1679 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1680 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1681 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1682 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1684 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1685 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1687 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1688 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1690 macro_rules! expect_forward {
1692 let mut events = $node.node.get_and_clear_pending_msg_events();
1693 assert_eq!(events.len(), 1);
1694 check_added_monitors!($node, 1);
1695 let payment_event = SendEvent::from_event(events.remove(0));
1700 let feemsat = 239; // set above
1701 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1702 let feerate = get_feerate!(nodes[0], chan_1.2);
1704 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1706 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1708 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1709 route.paths[0].last_mut().unwrap().fee_msat += 1;
1710 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1711 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1712 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)));
1713 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1714 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);
1717 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1718 // nodes[0]'s wealth
1720 let amt_msat = recv_value_0 + total_fee_msat;
1721 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1722 // Also, ensure that each payment has enough to be over the dust limit to
1723 // ensure it'll be included in each commit tx fee calculation.
1724 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1725 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1726 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1729 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1731 let (stat01_, stat11_, stat12_, stat22_) = (
1732 get_channel_value_stat!(nodes[0], chan_1.2),
1733 get_channel_value_stat!(nodes[1], chan_1.2),
1734 get_channel_value_stat!(nodes[1], chan_2.2),
1735 get_channel_value_stat!(nodes[2], chan_2.2),
1738 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1739 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1740 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1741 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1742 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1745 // adding pending output.
1746 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1747 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1748 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1749 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1750 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1751 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1752 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1753 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1754 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1756 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1757 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1758 let amt_msat_1 = recv_value_1 + total_fee_msat;
1760 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);
1761 let payment_event_1 = {
1762 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1763 check_added_monitors!(nodes[0], 1);
1765 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1766 assert_eq!(events.len(), 1);
1767 SendEvent::from_event(events.remove(0))
1769 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1771 // channel reserve test with htlc pending output > 0
1772 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1774 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1775 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1776 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1777 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1780 // split the rest to test holding cell
1781 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1782 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1783 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1784 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1786 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1787 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);
1790 // now see if they go through on both sides
1791 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);
1792 // but this will stuck in the holding cell
1793 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1794 check_added_monitors!(nodes[0], 0);
1795 let events = nodes[0].node.get_and_clear_pending_events();
1796 assert_eq!(events.len(), 0);
1798 // test with outbound holding cell amount > 0
1800 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1801 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1802 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1804 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);
1807 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);
1808 // this will also stuck in the holding cell
1809 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1810 check_added_monitors!(nodes[0], 0);
1811 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1812 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1814 // flush the pending htlc
1815 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1816 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1817 check_added_monitors!(nodes[1], 1);
1819 // the pending htlc should be promoted to committed
1820 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1821 check_added_monitors!(nodes[0], 1);
1822 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1824 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1825 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1826 // No commitment_signed so get_event_msg's assert(len == 1) passes
1827 check_added_monitors!(nodes[0], 1);
1829 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1830 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1831 check_added_monitors!(nodes[1], 1);
1833 expect_pending_htlcs_forwardable!(nodes[1]);
1835 let ref payment_event_11 = expect_forward!(nodes[1]);
1836 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1837 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1839 expect_pending_htlcs_forwardable!(nodes[2]);
1840 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1842 // flush the htlcs in the holding cell
1843 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1844 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1845 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1846 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1847 expect_pending_htlcs_forwardable!(nodes[1]);
1849 let ref payment_event_3 = expect_forward!(nodes[1]);
1850 assert_eq!(payment_event_3.msgs.len(), 2);
1851 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1852 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1854 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1855 expect_pending_htlcs_forwardable!(nodes[2]);
1857 let events = nodes[2].node.get_and_clear_pending_events();
1858 assert_eq!(events.len(), 2);
1860 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1861 assert_eq!(our_payment_hash_21, *payment_hash);
1862 assert_eq!(recv_value_21, amt);
1864 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1865 assert!(payment_preimage.is_none());
1866 assert_eq!(our_payment_secret_21, *payment_secret);
1868 _ => panic!("expected PaymentPurpose::InvoicePayment")
1871 _ => panic!("Unexpected event"),
1874 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1875 assert_eq!(our_payment_hash_22, *payment_hash);
1876 assert_eq!(recv_value_22, amt);
1878 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1879 assert!(payment_preimage.is_none());
1880 assert_eq!(our_payment_secret_22, *payment_secret);
1882 _ => panic!("expected PaymentPurpose::InvoicePayment")
1885 _ => panic!("Unexpected event"),
1888 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1889 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1890 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1892 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1893 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1894 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1896 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1897 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);
1898 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1899 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1900 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1902 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1903 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1907 fn channel_reserve_in_flight_removes() {
1908 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1909 // can send to its counterparty, but due to update ordering, the other side may not yet have
1910 // considered those HTLCs fully removed.
1911 // This tests that we don't count HTLCs which will not be included in the next remote
1912 // commitment transaction towards the reserve value (as it implies no commitment transaction
1913 // will be generated which violates the remote reserve value).
1914 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1916 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1917 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1918 // you only consider the value of the first HTLC, it may not),
1919 // * start routing a third HTLC from A to B,
1920 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1921 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1922 // * deliver the first fulfill from B
1923 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1925 // * deliver A's response CS and RAA.
1926 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1927 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1928 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1929 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1930 let chanmon_cfgs = create_chanmon_cfgs(2);
1931 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1932 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1933 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1934 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1936 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1937 // Route the first two HTLCs.
1938 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1939 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1941 // Start routing the third HTLC (this is just used to get everyone in the right state).
1942 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1944 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1945 check_added_monitors!(nodes[0], 1);
1946 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1947 assert_eq!(events.len(), 1);
1948 SendEvent::from_event(events.remove(0))
1951 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1952 // initial fulfill/CS.
1953 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1954 check_added_monitors!(nodes[1], 1);
1955 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1957 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1958 // remove the second HTLC when we send the HTLC back from B to A.
1959 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1960 check_added_monitors!(nodes[1], 1);
1961 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1963 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1964 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1965 check_added_monitors!(nodes[0], 1);
1966 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1967 expect_payment_sent!(nodes[0], payment_preimage_1);
1969 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1970 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1971 check_added_monitors!(nodes[1], 1);
1972 // B is already AwaitingRAA, so cant generate a CS here
1973 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1975 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1976 check_added_monitors!(nodes[1], 1);
1977 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1979 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1980 check_added_monitors!(nodes[0], 1);
1981 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1983 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1984 check_added_monitors!(nodes[1], 1);
1985 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1987 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1988 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1989 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1990 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1991 // on-chain as necessary).
1992 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1993 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1994 check_added_monitors!(nodes[0], 1);
1995 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1996 expect_payment_sent!(nodes[0], payment_preimage_2);
1998 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1999 check_added_monitors!(nodes[1], 1);
2000 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2002 expect_pending_htlcs_forwardable!(nodes[1]);
2003 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2005 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2006 // resolve the second HTLC from A's point of view.
2007 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2008 check_added_monitors!(nodes[0], 1);
2009 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2011 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2012 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2013 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2015 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2016 check_added_monitors!(nodes[1], 1);
2017 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2018 assert_eq!(events.len(), 1);
2019 SendEvent::from_event(events.remove(0))
2022 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2023 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2024 check_added_monitors!(nodes[0], 1);
2025 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2027 // Now just resolve all the outstanding messages/HTLCs for completeness...
2029 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2030 check_added_monitors!(nodes[1], 1);
2031 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2033 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2034 check_added_monitors!(nodes[1], 1);
2036 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2037 check_added_monitors!(nodes[0], 1);
2038 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2040 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2041 check_added_monitors!(nodes[1], 1);
2042 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2044 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2045 check_added_monitors!(nodes[0], 1);
2047 expect_pending_htlcs_forwardable!(nodes[0]);
2048 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2050 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2051 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2055 fn channel_monitor_network_test() {
2056 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2057 // tests that ChannelMonitor is able to recover from various states.
2058 let chanmon_cfgs = create_chanmon_cfgs(5);
2059 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2060 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2061 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2063 // Create some initial channels
2064 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2065 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2066 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2067 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2069 // Make sure all nodes are at the same starting height
2070 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2071 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2072 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2073 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2074 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2076 // Rebalance the network a bit by relaying one payment through all the channels...
2077 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2078 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2079 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2080 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2082 // Simple case with no pending HTLCs:
2083 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2084 check_added_monitors!(nodes[1], 1);
2085 check_closed_broadcast!(nodes[1], false);
2087 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2088 assert_eq!(node_txn.len(), 1);
2089 mine_transaction(&nodes[0], &node_txn[0]);
2090 check_added_monitors!(nodes[0], 1);
2091 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2093 check_closed_broadcast!(nodes[0], true);
2094 assert_eq!(nodes[0].node.list_channels().len(), 0);
2095 assert_eq!(nodes[1].node.list_channels().len(), 1);
2096 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2097 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2099 // One pending HTLC is discarded by the force-close:
2100 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2102 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2103 // broadcasted until we reach the timelock time).
2104 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2105 check_closed_broadcast!(nodes[1], false);
2106 check_added_monitors!(nodes[1], 1);
2108 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2109 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2110 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2111 mine_transaction(&nodes[2], &node_txn[0]);
2112 check_added_monitors!(nodes[2], 1);
2113 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2115 check_closed_broadcast!(nodes[2], true);
2116 assert_eq!(nodes[1].node.list_channels().len(), 0);
2117 assert_eq!(nodes[2].node.list_channels().len(), 1);
2118 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2119 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2121 macro_rules! claim_funds {
2122 ($node: expr, $prev_node: expr, $preimage: expr) => {
2124 assert!($node.node.claim_funds($preimage));
2125 check_added_monitors!($node, 1);
2127 let events = $node.node.get_and_clear_pending_msg_events();
2128 assert_eq!(events.len(), 1);
2130 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2131 assert!(update_add_htlcs.is_empty());
2132 assert!(update_fail_htlcs.is_empty());
2133 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2135 _ => panic!("Unexpected event"),
2141 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2142 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2143 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2144 check_added_monitors!(nodes[2], 1);
2145 check_closed_broadcast!(nodes[2], false);
2146 let node2_commitment_txid;
2148 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2149 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2150 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2151 node2_commitment_txid = node_txn[0].txid();
2153 // Claim the payment on nodes[3], giving it knowledge of the preimage
2154 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2155 mine_transaction(&nodes[3], &node_txn[0]);
2156 check_added_monitors!(nodes[3], 1);
2157 check_preimage_claim(&nodes[3], &node_txn);
2159 check_closed_broadcast!(nodes[3], true);
2160 assert_eq!(nodes[2].node.list_channels().len(), 0);
2161 assert_eq!(nodes[3].node.list_channels().len(), 1);
2162 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2163 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2165 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2166 // confusing us in the following tests.
2167 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2169 // One pending HTLC to time out:
2170 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2171 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2174 let (close_chan_update_1, close_chan_update_2) = {
2175 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2176 let events = nodes[3].node.get_and_clear_pending_msg_events();
2177 assert_eq!(events.len(), 2);
2178 let close_chan_update_1 = match events[0] {
2179 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2182 _ => panic!("Unexpected event"),
2185 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2186 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2188 _ => panic!("Unexpected event"),
2190 check_added_monitors!(nodes[3], 1);
2192 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2194 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2195 node_txn.retain(|tx| {
2196 if tx.input[0].previous_output.txid == node2_commitment_txid {
2202 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2204 // Claim the payment on nodes[4], giving it knowledge of the preimage
2205 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2207 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2208 let events = nodes[4].node.get_and_clear_pending_msg_events();
2209 assert_eq!(events.len(), 2);
2210 let close_chan_update_2 = match events[0] {
2211 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2214 _ => panic!("Unexpected event"),
2217 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2218 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2220 _ => panic!("Unexpected event"),
2222 check_added_monitors!(nodes[4], 1);
2223 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2225 mine_transaction(&nodes[4], &node_txn[0]);
2226 check_preimage_claim(&nodes[4], &node_txn);
2227 (close_chan_update_1, close_chan_update_2)
2229 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2230 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2231 assert_eq!(nodes[3].node.list_channels().len(), 0);
2232 assert_eq!(nodes[4].node.list_channels().len(), 0);
2234 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2235 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2236 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2240 fn test_justice_tx() {
2241 // Test justice txn built on revoked HTLC-Success tx, against both sides
2242 let mut alice_config = UserConfig::default();
2243 alice_config.channel_options.announced_channel = true;
2244 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2245 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2246 let mut bob_config = UserConfig::default();
2247 bob_config.channel_options.announced_channel = true;
2248 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2249 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2250 let user_cfgs = [Some(alice_config), Some(bob_config)];
2251 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2252 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2253 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2254 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2255 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2256 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2257 // Create some new channels:
2258 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2260 // A pending HTLC which will be revoked:
2261 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2262 // Get the will-be-revoked local txn from nodes[0]
2263 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2264 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2265 assert_eq!(revoked_local_txn[0].input.len(), 1);
2266 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2267 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2268 assert_eq!(revoked_local_txn[1].input.len(), 1);
2269 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2270 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2271 // Revoke the old state
2272 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2275 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2277 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2278 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2279 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2281 check_spends!(node_txn[0], revoked_local_txn[0]);
2282 node_txn.swap_remove(0);
2283 node_txn.truncate(1);
2285 check_added_monitors!(nodes[1], 1);
2286 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2287 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2289 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2290 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2291 // Verify broadcast of revoked HTLC-timeout
2292 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2293 check_added_monitors!(nodes[0], 1);
2294 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2295 // Broadcast revoked HTLC-timeout on node 1
2296 mine_transaction(&nodes[1], &node_txn[1]);
2297 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2299 get_announce_close_broadcast_events(&nodes, 0, 1);
2301 assert_eq!(nodes[0].node.list_channels().len(), 0);
2302 assert_eq!(nodes[1].node.list_channels().len(), 0);
2304 // We test justice_tx build by A on B's revoked HTLC-Success tx
2305 // Create some new channels:
2306 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2308 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2312 // A pending HTLC which will be revoked:
2313 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2314 // Get the will-be-revoked local txn from B
2315 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2316 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2317 assert_eq!(revoked_local_txn[0].input.len(), 1);
2318 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2319 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2320 // Revoke the old state
2321 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2323 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2325 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2326 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2327 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2329 check_spends!(node_txn[0], revoked_local_txn[0]);
2330 node_txn.swap_remove(0);
2332 check_added_monitors!(nodes[0], 1);
2333 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2335 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2336 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2337 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2338 check_added_monitors!(nodes[1], 1);
2339 mine_transaction(&nodes[0], &node_txn[1]);
2340 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2341 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2343 get_announce_close_broadcast_events(&nodes, 0, 1);
2344 assert_eq!(nodes[0].node.list_channels().len(), 0);
2345 assert_eq!(nodes[1].node.list_channels().len(), 0);
2349 fn revoked_output_claim() {
2350 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2351 // transaction is broadcast by its counterparty
2352 let chanmon_cfgs = create_chanmon_cfgs(2);
2353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2356 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2357 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2358 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2359 assert_eq!(revoked_local_txn.len(), 1);
2360 // Only output is the full channel value back to nodes[0]:
2361 assert_eq!(revoked_local_txn[0].output.len(), 1);
2362 // Send a payment through, updating everyone's latest commitment txn
2363 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2365 // Inform nodes[1] that nodes[0] broadcast a stale tx
2366 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2367 check_added_monitors!(nodes[1], 1);
2368 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2369 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2370 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2372 check_spends!(node_txn[0], revoked_local_txn[0]);
2373 check_spends!(node_txn[1], chan_1.3);
2375 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2376 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2377 get_announce_close_broadcast_events(&nodes, 0, 1);
2378 check_added_monitors!(nodes[0], 1);
2379 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2383 fn claim_htlc_outputs_shared_tx() {
2384 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2385 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2386 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2391 // Create some new channel:
2392 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2394 // Rebalance the network to generate htlc in the two directions
2395 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2396 // 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
2397 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2398 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2400 // Get the will-be-revoked local txn from node[0]
2401 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2402 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2403 assert_eq!(revoked_local_txn[0].input.len(), 1);
2404 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2405 assert_eq!(revoked_local_txn[1].input.len(), 1);
2406 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2407 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2408 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2410 //Revoke the old state
2411 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2414 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2415 check_added_monitors!(nodes[0], 1);
2416 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2417 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2418 check_added_monitors!(nodes[1], 1);
2419 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2420 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2421 expect_payment_failed!(nodes[1], payment_hash_2, true);
2423 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2424 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2426 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2427 check_spends!(node_txn[0], revoked_local_txn[0]);
2429 let mut witness_lens = BTreeSet::new();
2430 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2431 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2432 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2433 assert_eq!(witness_lens.len(), 3);
2434 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2435 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2436 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2438 // Next nodes[1] broadcasts its current local tx state:
2439 assert_eq!(node_txn[1].input.len(), 1);
2440 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2442 get_announce_close_broadcast_events(&nodes, 0, 1);
2443 assert_eq!(nodes[0].node.list_channels().len(), 0);
2444 assert_eq!(nodes[1].node.list_channels().len(), 0);
2448 fn claim_htlc_outputs_single_tx() {
2449 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2450 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2451 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2452 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2453 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2454 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2456 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2458 // Rebalance the network to generate htlc in the two directions
2459 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2460 // 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
2461 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2462 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2463 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2465 // Get the will-be-revoked local txn from node[0]
2466 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2468 //Revoke the old state
2469 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2472 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2473 check_added_monitors!(nodes[0], 1);
2474 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2475 check_added_monitors!(nodes[1], 1);
2476 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2477 let mut events = nodes[0].node.get_and_clear_pending_events();
2478 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2480 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2481 _ => panic!("Unexpected event"),
2484 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2485 expect_payment_failed!(nodes[1], payment_hash_2, true);
2487 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2488 assert_eq!(node_txn.len(), 9);
2489 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2490 // ChannelManager: local commmitment + local HTLC-timeout (2)
2491 // 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)
2492 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2494 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2495 assert_eq!(node_txn[0].input.len(), 1);
2496 check_spends!(node_txn[0], chan_1.3);
2497 assert_eq!(node_txn[1].input.len(), 1);
2498 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2499 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2500 check_spends!(node_txn[1], node_txn[0]);
2502 // Justice transactions are indices 1-2-4
2503 assert_eq!(node_txn[2].input.len(), 1);
2504 assert_eq!(node_txn[3].input.len(), 1);
2505 assert_eq!(node_txn[4].input.len(), 1);
2507 check_spends!(node_txn[2], revoked_local_txn[0]);
2508 check_spends!(node_txn[3], revoked_local_txn[0]);
2509 check_spends!(node_txn[4], revoked_local_txn[0]);
2511 let mut witness_lens = BTreeSet::new();
2512 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2513 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2514 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2515 assert_eq!(witness_lens.len(), 3);
2516 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2517 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2518 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2520 get_announce_close_broadcast_events(&nodes, 0, 1);
2521 assert_eq!(nodes[0].node.list_channels().len(), 0);
2522 assert_eq!(nodes[1].node.list_channels().len(), 0);
2526 fn test_htlc_on_chain_success() {
2527 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2528 // the preimage backward accordingly. So here we test that ChannelManager is
2529 // broadcasting the right event to other nodes in payment path.
2530 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2531 // A --------------------> B ----------------------> C (preimage)
2532 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2533 // commitment transaction was broadcast.
2534 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2536 // B should be able to claim via preimage if A then broadcasts its local tx.
2537 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2538 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2539 // PaymentSent event).
2541 let chanmon_cfgs = create_chanmon_cfgs(3);
2542 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2543 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2544 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2546 // Create some initial channels
2547 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2548 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2550 // Ensure all nodes are at the same height
2551 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2552 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2553 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2554 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2556 // Rebalance the network a bit by relaying one payment through all the channels...
2557 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2558 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2560 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2561 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2563 // Broadcast legit commitment tx from C on B's chain
2564 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2565 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2566 assert_eq!(commitment_tx.len(), 1);
2567 check_spends!(commitment_tx[0], chan_2.3);
2568 nodes[2].node.claim_funds(our_payment_preimage);
2569 nodes[2].node.claim_funds(our_payment_preimage_2);
2570 check_added_monitors!(nodes[2], 2);
2571 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2572 assert!(updates.update_add_htlcs.is_empty());
2573 assert!(updates.update_fail_htlcs.is_empty());
2574 assert!(updates.update_fail_malformed_htlcs.is_empty());
2575 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2577 mine_transaction(&nodes[2], &commitment_tx[0]);
2578 check_closed_broadcast!(nodes[2], true);
2579 check_added_monitors!(nodes[2], 1);
2580 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2581 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)
2582 assert_eq!(node_txn.len(), 5);
2583 assert_eq!(node_txn[0], node_txn[3]);
2584 assert_eq!(node_txn[1], node_txn[4]);
2585 assert_eq!(node_txn[2], commitment_tx[0]);
2586 check_spends!(node_txn[0], commitment_tx[0]);
2587 check_spends!(node_txn[1], commitment_tx[0]);
2588 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2589 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2590 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2591 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2592 assert_eq!(node_txn[0].lock_time, 0);
2593 assert_eq!(node_txn[1].lock_time, 0);
2595 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2596 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2597 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2598 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2600 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2601 assert_eq!(added_monitors.len(), 1);
2602 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2603 added_monitors.clear();
2605 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2606 assert_eq!(forwarded_events.len(), 3);
2607 match forwarded_events[0] {
2608 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2609 _ => panic!("Unexpected event"),
2611 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2612 } else { panic!(); }
2613 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2614 } else { panic!(); }
2615 let events = nodes[1].node.get_and_clear_pending_msg_events();
2617 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2618 assert_eq!(added_monitors.len(), 2);
2619 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2620 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2621 added_monitors.clear();
2623 assert_eq!(events.len(), 3);
2625 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2626 _ => panic!("Unexpected event"),
2629 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2630 _ => panic!("Unexpected event"),
2634 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, .. } } => {
2635 assert!(update_add_htlcs.is_empty());
2636 assert!(update_fail_htlcs.is_empty());
2637 assert_eq!(update_fulfill_htlcs.len(), 1);
2638 assert!(update_fail_malformed_htlcs.is_empty());
2639 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2641 _ => panic!("Unexpected event"),
2643 macro_rules! check_tx_local_broadcast {
2644 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2645 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2646 assert_eq!(node_txn.len(), 3);
2647 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2648 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2649 check_spends!(node_txn[1], $commitment_tx);
2650 check_spends!(node_txn[2], $commitment_tx);
2651 assert_ne!(node_txn[1].lock_time, 0);
2652 assert_ne!(node_txn[2].lock_time, 0);
2654 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2655 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2656 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2657 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2659 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2660 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2661 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2662 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2664 check_spends!(node_txn[0], $chan_tx);
2665 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2669 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2670 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2671 // timeout-claim of the output that nodes[2] just claimed via success.
2672 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2674 // Broadcast legit commitment tx from A on B's chain
2675 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2676 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2677 check_spends!(node_a_commitment_tx[0], chan_1.3);
2678 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2679 check_closed_broadcast!(nodes[1], true);
2680 check_added_monitors!(nodes[1], 1);
2681 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2682 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2683 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2684 let commitment_spend =
2685 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2686 check_spends!(node_txn[1], commitment_tx[0]);
2687 check_spends!(node_txn[2], commitment_tx[0]);
2688 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2691 check_spends!(node_txn[0], commitment_tx[0]);
2692 check_spends!(node_txn[1], commitment_tx[0]);
2693 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2697 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2698 assert_eq!(commitment_spend.input.len(), 2);
2699 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2700 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2701 assert_eq!(commitment_spend.lock_time, 0);
2702 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2703 check_spends!(node_txn[3], chan_1.3);
2704 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2705 check_spends!(node_txn[4], node_txn[3]);
2706 check_spends!(node_txn[5], node_txn[3]);
2707 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2708 // we already checked the same situation with A.
2710 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2711 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2712 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2713 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2714 check_closed_broadcast!(nodes[0], true);
2715 check_added_monitors!(nodes[0], 1);
2716 let events = nodes[0].node.get_and_clear_pending_events();
2717 assert_eq!(events.len(), 3);
2718 let mut first_claimed = false;
2719 for event in events {
2721 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2722 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2723 assert!(!first_claimed);
2724 first_claimed = true;
2726 assert_eq!(payment_preimage, our_payment_preimage_2);
2727 assert_eq!(payment_hash, payment_hash_2);
2730 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2731 _ => panic!("Unexpected event"),
2734 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2737 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2738 // Test that in case of a unilateral close onchain, we detect the state of output and
2739 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2740 // broadcasting the right event to other nodes in payment path.
2741 // A ------------------> B ----------------------> C (timeout)
2742 // B's commitment tx C's commitment tx
2744 // B's HTLC timeout tx B's timeout tx
2746 let chanmon_cfgs = create_chanmon_cfgs(3);
2747 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2748 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2749 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2750 *nodes[0].connect_style.borrow_mut() = connect_style;
2751 *nodes[1].connect_style.borrow_mut() = connect_style;
2752 *nodes[2].connect_style.borrow_mut() = connect_style;
2754 // Create some intial channels
2755 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2756 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2758 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2759 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2760 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2762 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2764 // Broadcast legit commitment tx from C on B's chain
2765 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2766 check_spends!(commitment_tx[0], chan_2.3);
2767 nodes[2].node.fail_htlc_backwards(&payment_hash);
2768 check_added_monitors!(nodes[2], 0);
2769 expect_pending_htlcs_forwardable!(nodes[2]);
2770 check_added_monitors!(nodes[2], 1);
2772 let events = nodes[2].node.get_and_clear_pending_msg_events();
2773 assert_eq!(events.len(), 1);
2775 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, .. } } => {
2776 assert!(update_add_htlcs.is_empty());
2777 assert!(!update_fail_htlcs.is_empty());
2778 assert!(update_fulfill_htlcs.is_empty());
2779 assert!(update_fail_malformed_htlcs.is_empty());
2780 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2782 _ => panic!("Unexpected event"),
2784 mine_transaction(&nodes[2], &commitment_tx[0]);
2785 check_closed_broadcast!(nodes[2], true);
2786 check_added_monitors!(nodes[2], 1);
2787 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2788 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2789 assert_eq!(node_txn.len(), 1);
2790 check_spends!(node_txn[0], chan_2.3);
2791 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2793 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2794 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2795 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2796 mine_transaction(&nodes[1], &commitment_tx[0]);
2797 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2800 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2801 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2802 assert_eq!(node_txn[0], node_txn[3]);
2803 assert_eq!(node_txn[1], node_txn[4]);
2805 check_spends!(node_txn[2], commitment_tx[0]);
2806 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2808 check_spends!(node_txn[0], chan_2.3);
2809 check_spends!(node_txn[1], node_txn[0]);
2810 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2811 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2813 timeout_tx = node_txn[2].clone();
2817 mine_transaction(&nodes[1], &timeout_tx);
2818 check_added_monitors!(nodes[1], 1);
2819 check_closed_broadcast!(nodes[1], true);
2821 // B will rebroadcast a fee-bumped timeout transaction here.
2822 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2823 assert_eq!(node_txn.len(), 1);
2824 check_spends!(node_txn[0], commitment_tx[0]);
2827 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2829 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2830 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2831 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2832 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2833 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2834 if node_txn.len() == 1 {
2835 check_spends!(node_txn[0], chan_2.3);
2837 assert_eq!(node_txn.len(), 0);
2841 expect_pending_htlcs_forwardable!(nodes[1]);
2842 check_added_monitors!(nodes[1], 1);
2843 let events = nodes[1].node.get_and_clear_pending_msg_events();
2844 assert_eq!(events.len(), 1);
2846 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, .. } } => {
2847 assert!(update_add_htlcs.is_empty());
2848 assert!(!update_fail_htlcs.is_empty());
2849 assert!(update_fulfill_htlcs.is_empty());
2850 assert!(update_fail_malformed_htlcs.is_empty());
2851 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2853 _ => panic!("Unexpected event"),
2856 // Broadcast legit commitment tx from B on A's chain
2857 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2858 check_spends!(commitment_tx[0], chan_1.3);
2860 mine_transaction(&nodes[0], &commitment_tx[0]);
2861 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2863 check_closed_broadcast!(nodes[0], true);
2864 check_added_monitors!(nodes[0], 1);
2865 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2866 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2867 assert_eq!(node_txn.len(), 2);
2868 check_spends!(node_txn[0], chan_1.3);
2869 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2870 check_spends!(node_txn[1], commitment_tx[0]);
2871 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2875 fn test_htlc_on_chain_timeout() {
2876 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2877 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2878 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2882 fn test_simple_commitment_revoked_fail_backward() {
2883 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2884 // and fail backward accordingly.
2886 let chanmon_cfgs = create_chanmon_cfgs(3);
2887 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2888 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2889 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2891 // Create some initial channels
2892 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2893 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2895 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2896 // Get the will-be-revoked local txn from nodes[2]
2897 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2898 // Revoke the old state
2899 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2901 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2903 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2904 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2905 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2906 check_added_monitors!(nodes[1], 1);
2907 check_closed_broadcast!(nodes[1], true);
2909 expect_pending_htlcs_forwardable!(nodes[1]);
2910 check_added_monitors!(nodes[1], 1);
2911 let events = nodes[1].node.get_and_clear_pending_msg_events();
2912 assert_eq!(events.len(), 1);
2914 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, .. } } => {
2915 assert!(update_add_htlcs.is_empty());
2916 assert_eq!(update_fail_htlcs.len(), 1);
2917 assert!(update_fulfill_htlcs.is_empty());
2918 assert!(update_fail_malformed_htlcs.is_empty());
2919 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2921 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2922 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2923 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2925 _ => panic!("Unexpected event"),
2929 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2930 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2931 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2932 // commitment transaction anymore.
2933 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2934 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2935 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2936 // technically disallowed and we should probably handle it reasonably.
2937 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2938 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2940 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2941 // commitment_signed (implying it will be in the latest remote commitment transaction).
2942 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2943 // and once they revoke the previous commitment transaction (allowing us to send a new
2944 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2945 let chanmon_cfgs = create_chanmon_cfgs(3);
2946 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2947 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2948 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2950 // Create some initial channels
2951 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2952 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2954 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 });
2955 // Get the will-be-revoked local txn from nodes[2]
2956 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2957 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2958 // Revoke the old state
2959 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2961 let value = if use_dust {
2962 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2963 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2964 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2967 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2968 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2969 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2971 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2972 expect_pending_htlcs_forwardable!(nodes[2]);
2973 check_added_monitors!(nodes[2], 1);
2974 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2975 assert!(updates.update_add_htlcs.is_empty());
2976 assert!(updates.update_fulfill_htlcs.is_empty());
2977 assert!(updates.update_fail_malformed_htlcs.is_empty());
2978 assert_eq!(updates.update_fail_htlcs.len(), 1);
2979 assert!(updates.update_fee.is_none());
2980 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2981 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2982 // Drop the last RAA from 3 -> 2
2984 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2985 expect_pending_htlcs_forwardable!(nodes[2]);
2986 check_added_monitors!(nodes[2], 1);
2987 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2988 assert!(updates.update_add_htlcs.is_empty());
2989 assert!(updates.update_fulfill_htlcs.is_empty());
2990 assert!(updates.update_fail_malformed_htlcs.is_empty());
2991 assert_eq!(updates.update_fail_htlcs.len(), 1);
2992 assert!(updates.update_fee.is_none());
2993 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2994 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2995 check_added_monitors!(nodes[1], 1);
2996 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2997 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2998 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2999 check_added_monitors!(nodes[2], 1);
3001 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3002 expect_pending_htlcs_forwardable!(nodes[2]);
3003 check_added_monitors!(nodes[2], 1);
3004 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3005 assert!(updates.update_add_htlcs.is_empty());
3006 assert!(updates.update_fulfill_htlcs.is_empty());
3007 assert!(updates.update_fail_malformed_htlcs.is_empty());
3008 assert_eq!(updates.update_fail_htlcs.len(), 1);
3009 assert!(updates.update_fee.is_none());
3010 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3011 // At this point first_payment_hash has dropped out of the latest two commitment
3012 // transactions that nodes[1] is tracking...
3013 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3014 check_added_monitors!(nodes[1], 1);
3015 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3016 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3017 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3018 check_added_monitors!(nodes[2], 1);
3020 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3021 // on nodes[2]'s RAA.
3022 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3023 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3024 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3025 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3026 check_added_monitors!(nodes[1], 0);
3029 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3030 // One monitor for the new revocation preimage, no second on as we won't generate a new
3031 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3032 check_added_monitors!(nodes[1], 1);
3033 let events = nodes[1].node.get_and_clear_pending_events();
3034 assert_eq!(events.len(), 1);
3036 Event::PendingHTLCsForwardable { .. } => { },
3037 _ => panic!("Unexpected event"),
3039 // Deliberately don't process the pending fail-back so they all fail back at once after
3040 // block connection just like the !deliver_bs_raa case
3043 let mut failed_htlcs = HashSet::new();
3044 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3046 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3047 check_added_monitors!(nodes[1], 1);
3048 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3050 let events = nodes[1].node.get_and_clear_pending_events();
3051 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3053 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3054 _ => panic!("Unexepected event"),
3057 Event::PaymentPathFailed { ref payment_hash, .. } => {
3058 assert_eq!(*payment_hash, fourth_payment_hash);
3060 _ => panic!("Unexpected event"),
3062 if !deliver_bs_raa {
3064 Event::PendingHTLCsForwardable { .. } => { },
3065 _ => panic!("Unexpected event"),
3068 nodes[1].node.process_pending_htlc_forwards();
3069 check_added_monitors!(nodes[1], 1);
3071 let events = nodes[1].node.get_and_clear_pending_msg_events();
3072 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3073 match events[if deliver_bs_raa { 1 } else { 0 }] {
3074 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3075 _ => panic!("Unexpected event"),
3077 match events[if deliver_bs_raa { 2 } else { 1 }] {
3078 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3079 assert_eq!(channel_id, chan_2.2);
3080 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3082 _ => panic!("Unexpected event"),
3086 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, .. } } => {
3087 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3088 assert_eq!(update_add_htlcs.len(), 1);
3089 assert!(update_fulfill_htlcs.is_empty());
3090 assert!(update_fail_htlcs.is_empty());
3091 assert!(update_fail_malformed_htlcs.is_empty());
3093 _ => panic!("Unexpected event"),
3096 match events[if deliver_bs_raa { 3 } else { 2 }] {
3097 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, .. } } => {
3098 assert!(update_add_htlcs.is_empty());
3099 assert_eq!(update_fail_htlcs.len(), 3);
3100 assert!(update_fulfill_htlcs.is_empty());
3101 assert!(update_fail_malformed_htlcs.is_empty());
3102 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3104 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3105 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3106 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3108 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3110 let events = nodes[0].node.get_and_clear_pending_events();
3111 assert_eq!(events.len(), 3);
3113 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3114 assert!(failed_htlcs.insert(payment_hash.0));
3115 // If we delivered B's RAA we got an unknown preimage error, not something
3116 // that we should update our routing table for.
3117 if !deliver_bs_raa {
3118 assert!(network_update.is_some());
3121 _ => panic!("Unexpected event"),
3124 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3125 assert!(failed_htlcs.insert(payment_hash.0));
3126 assert!(network_update.is_some());
3128 _ => panic!("Unexpected event"),
3131 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3132 assert!(failed_htlcs.insert(payment_hash.0));
3133 assert!(network_update.is_some());
3135 _ => panic!("Unexpected event"),
3138 _ => panic!("Unexpected event"),
3141 assert!(failed_htlcs.contains(&first_payment_hash.0));
3142 assert!(failed_htlcs.contains(&second_payment_hash.0));
3143 assert!(failed_htlcs.contains(&third_payment_hash.0));
3147 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3148 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3149 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3150 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3151 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3155 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3156 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3157 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3158 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3159 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3163 fn fail_backward_pending_htlc_upon_channel_failure() {
3164 let chanmon_cfgs = create_chanmon_cfgs(2);
3165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3167 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3168 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3170 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3172 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3173 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3174 check_added_monitors!(nodes[0], 1);
3176 let payment_event = {
3177 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3178 assert_eq!(events.len(), 1);
3179 SendEvent::from_event(events.remove(0))
3181 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3182 assert_eq!(payment_event.msgs.len(), 1);
3185 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3186 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3188 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3189 check_added_monitors!(nodes[0], 0);
3191 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3194 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3196 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3198 let secp_ctx = Secp256k1::new();
3199 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3200 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3201 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3202 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3203 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3205 // Send a 0-msat update_add_htlc to fail the channel.
3206 let update_add_htlc = msgs::UpdateAddHTLC {
3212 onion_routing_packet,
3214 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3216 let events = nodes[0].node.get_and_clear_pending_events();
3217 assert_eq!(events.len(), 2);
3218 // Check that Alice fails backward the pending HTLC from the second payment.
3220 Event::PaymentPathFailed { payment_hash, .. } => {
3221 assert_eq!(payment_hash, failed_payment_hash);
3223 _ => panic!("Unexpected event"),
3226 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3227 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3229 _ => panic!("Unexpected event {:?}", events[1]),
3231 check_closed_broadcast!(nodes[0], true);
3232 check_added_monitors!(nodes[0], 1);
3236 fn test_htlc_ignore_latest_remote_commitment() {
3237 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3238 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3239 let chanmon_cfgs = create_chanmon_cfgs(2);
3240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3242 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3243 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3245 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3246 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3247 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3248 check_closed_broadcast!(nodes[0], true);
3249 check_added_monitors!(nodes[0], 1);
3250 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3252 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3253 assert_eq!(node_txn.len(), 3);
3254 assert_eq!(node_txn[0], node_txn[1]);
3256 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3257 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3258 check_closed_broadcast!(nodes[1], true);
3259 check_added_monitors!(nodes[1], 1);
3260 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3262 // Duplicate the connect_block call since this may happen due to other listeners
3263 // registering new transactions
3264 header.prev_blockhash = header.block_hash();
3265 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3269 fn test_force_close_fail_back() {
3270 // Check which HTLCs are failed-backwards on channel force-closure
3271 let chanmon_cfgs = create_chanmon_cfgs(3);
3272 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3273 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3274 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3275 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3276 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3278 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3280 let mut payment_event = {
3281 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3282 check_added_monitors!(nodes[0], 1);
3284 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3285 assert_eq!(events.len(), 1);
3286 SendEvent::from_event(events.remove(0))
3289 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3290 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3292 expect_pending_htlcs_forwardable!(nodes[1]);
3294 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3295 assert_eq!(events_2.len(), 1);
3296 payment_event = SendEvent::from_event(events_2.remove(0));
3297 assert_eq!(payment_event.msgs.len(), 1);
3299 check_added_monitors!(nodes[1], 1);
3300 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3301 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3302 check_added_monitors!(nodes[2], 1);
3303 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3305 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3306 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3307 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3309 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3310 check_closed_broadcast!(nodes[2], true);
3311 check_added_monitors!(nodes[2], 1);
3312 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3314 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3315 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3316 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3317 // back to nodes[1] upon timeout otherwise.
3318 assert_eq!(node_txn.len(), 1);
3322 mine_transaction(&nodes[1], &tx);
3324 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3325 check_closed_broadcast!(nodes[1], true);
3326 check_added_monitors!(nodes[1], 1);
3327 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3329 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3331 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3332 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3334 mine_transaction(&nodes[2], &tx);
3335 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3336 assert_eq!(node_txn.len(), 1);
3337 assert_eq!(node_txn[0].input.len(), 1);
3338 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3339 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3340 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3342 check_spends!(node_txn[0], tx);
3346 fn test_dup_events_on_peer_disconnect() {
3347 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3348 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3349 // as we used to generate the event immediately upon receipt of the payment preimage in the
3350 // update_fulfill_htlc message.
3352 let chanmon_cfgs = create_chanmon_cfgs(2);
3353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3356 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3358 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3360 assert!(nodes[1].node.claim_funds(payment_preimage));
3361 check_added_monitors!(nodes[1], 1);
3362 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3363 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3364 expect_payment_sent!(nodes[0], payment_preimage);
3366 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3367 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3369 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3370 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3374 fn test_simple_peer_disconnect() {
3375 // Test that we can reconnect when there are no lost messages
3376 let chanmon_cfgs = create_chanmon_cfgs(3);
3377 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3378 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3379 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3380 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3381 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3383 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3384 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3385 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3387 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3388 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3389 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3390 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3392 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3393 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3394 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3396 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3397 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3398 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3399 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3401 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3402 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3404 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3405 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3407 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3409 let events = nodes[0].node.get_and_clear_pending_events();
3410 assert_eq!(events.len(), 2);
3412 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3413 assert_eq!(payment_preimage, payment_preimage_3);
3414 assert_eq!(payment_hash, payment_hash_3);
3416 _ => panic!("Unexpected event"),
3419 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3420 assert_eq!(payment_hash, payment_hash_5);
3421 assert!(rejected_by_dest);
3423 _ => panic!("Unexpected event"),
3427 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3428 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3431 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3432 // Test that we can reconnect when in-flight HTLC updates get dropped
3433 let chanmon_cfgs = create_chanmon_cfgs(2);
3434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3436 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3438 let mut as_funding_locked = None;
3439 if messages_delivered == 0 {
3440 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3441 as_funding_locked = Some(funding_locked);
3442 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3443 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3444 // it before the channel_reestablish message.
3446 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3449 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3451 let payment_event = {
3452 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3453 check_added_monitors!(nodes[0], 1);
3455 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3456 assert_eq!(events.len(), 1);
3457 SendEvent::from_event(events.remove(0))
3459 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3461 if messages_delivered < 2 {
3462 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3464 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3465 if messages_delivered >= 3 {
3466 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3467 check_added_monitors!(nodes[1], 1);
3468 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3470 if messages_delivered >= 4 {
3471 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3472 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3473 check_added_monitors!(nodes[0], 1);
3475 if messages_delivered >= 5 {
3476 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3477 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3478 // No commitment_signed so get_event_msg's assert(len == 1) passes
3479 check_added_monitors!(nodes[0], 1);
3481 if messages_delivered >= 6 {
3482 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3483 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3484 check_added_monitors!(nodes[1], 1);
3491 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3492 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3493 if messages_delivered < 3 {
3494 if simulate_broken_lnd {
3495 // lnd has a long-standing bug where they send a funding_locked prior to a
3496 // channel_reestablish if you reconnect prior to funding_locked time.
3498 // Here we simulate that behavior, delivering a funding_locked immediately on
3499 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3500 // in `reconnect_nodes` but we currently don't fail based on that.
3502 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3503 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3505 // Even if the funding_locked messages get exchanged, as long as nothing further was
3506 // received on either side, both sides will need to resend them.
3507 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3508 } else if messages_delivered == 3 {
3509 // nodes[0] still wants its RAA + commitment_signed
3510 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3511 } else if messages_delivered == 4 {
3512 // nodes[0] still wants its commitment_signed
3513 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3514 } else if messages_delivered == 5 {
3515 // nodes[1] still wants its final RAA
3516 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3517 } else if messages_delivered == 6 {
3518 // Everything was delivered...
3519 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3522 let events_1 = nodes[1].node.get_and_clear_pending_events();
3523 assert_eq!(events_1.len(), 1);
3525 Event::PendingHTLCsForwardable { .. } => { },
3526 _ => panic!("Unexpected event"),
3529 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3530 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3531 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3533 nodes[1].node.process_pending_htlc_forwards();
3535 let events_2 = nodes[1].node.get_and_clear_pending_events();
3536 assert_eq!(events_2.len(), 1);
3538 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3539 assert_eq!(payment_hash_1, *payment_hash);
3540 assert_eq!(amt, 1000000);
3542 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3543 assert!(payment_preimage.is_none());
3544 assert_eq!(payment_secret_1, *payment_secret);
3546 _ => panic!("expected PaymentPurpose::InvoicePayment")
3549 _ => panic!("Unexpected event"),
3552 nodes[1].node.claim_funds(payment_preimage_1);
3553 check_added_monitors!(nodes[1], 1);
3555 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3556 assert_eq!(events_3.len(), 1);
3557 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3558 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3559 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3560 assert!(updates.update_add_htlcs.is_empty());
3561 assert!(updates.update_fail_htlcs.is_empty());
3562 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3563 assert!(updates.update_fail_malformed_htlcs.is_empty());
3564 assert!(updates.update_fee.is_none());
3565 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3567 _ => panic!("Unexpected event"),
3570 if messages_delivered >= 1 {
3571 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3573 let events_4 = nodes[0].node.get_and_clear_pending_events();
3574 assert_eq!(events_4.len(), 1);
3576 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3577 assert_eq!(payment_preimage_1, *payment_preimage);
3578 assert_eq!(payment_hash_1, *payment_hash);
3580 _ => panic!("Unexpected event"),
3583 if messages_delivered >= 2 {
3584 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3585 check_added_monitors!(nodes[0], 1);
3586 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3588 if messages_delivered >= 3 {
3589 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3590 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3591 check_added_monitors!(nodes[1], 1);
3593 if messages_delivered >= 4 {
3594 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3595 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3596 // No commitment_signed so get_event_msg's assert(len == 1) passes
3597 check_added_monitors!(nodes[1], 1);
3599 if messages_delivered >= 5 {
3600 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3601 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3602 check_added_monitors!(nodes[0], 1);
3609 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3610 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3611 if messages_delivered < 2 {
3612 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3613 if messages_delivered < 1 {
3614 let events_4 = nodes[0].node.get_and_clear_pending_events();
3615 assert_eq!(events_4.len(), 1);
3617 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3618 assert_eq!(payment_preimage_1, *payment_preimage);
3619 assert_eq!(payment_hash_1, *payment_hash);
3621 _ => panic!("Unexpected event"),
3624 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3626 } else if messages_delivered == 2 {
3627 // nodes[0] still wants its RAA + commitment_signed
3628 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3629 } else if messages_delivered == 3 {
3630 // nodes[0] still wants its commitment_signed
3631 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3632 } else if messages_delivered == 4 {
3633 // nodes[1] still wants its final RAA
3634 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3635 } else if messages_delivered == 5 {
3636 // Everything was delivered...
3637 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3640 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3641 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3642 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3644 // Channel should still work fine...
3645 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3646 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3647 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3651 fn test_drop_messages_peer_disconnect_a() {
3652 do_test_drop_messages_peer_disconnect(0, true);
3653 do_test_drop_messages_peer_disconnect(0, false);
3654 do_test_drop_messages_peer_disconnect(1, false);
3655 do_test_drop_messages_peer_disconnect(2, false);
3659 fn test_drop_messages_peer_disconnect_b() {
3660 do_test_drop_messages_peer_disconnect(3, false);
3661 do_test_drop_messages_peer_disconnect(4, false);
3662 do_test_drop_messages_peer_disconnect(5, false);
3663 do_test_drop_messages_peer_disconnect(6, false);
3667 fn test_funding_peer_disconnect() {
3668 // Test that we can lock in our funding tx while disconnected
3669 let chanmon_cfgs = create_chanmon_cfgs(2);
3670 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3671 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3672 let persister: test_utils::TestPersister;
3673 let new_chain_monitor: test_utils::TestChainMonitor;
3674 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3676 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3678 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3679 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3681 confirm_transaction(&nodes[0], &tx);
3682 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3684 assert_eq!(events_1.len(), 1);
3686 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3687 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3688 chan_id = msg.channel_id;
3690 _ => panic!("Unexpected event"),
3693 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3696 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3698 confirm_transaction(&nodes[1], &tx);
3699 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3700 assert_eq!(events_2.len(), 2);
3701 let funding_locked = match events_2[0] {
3702 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3703 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3706 _ => panic!("Unexpected event"),
3708 let bs_announcement_sigs = match events_2[1] {
3709 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3710 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3713 _ => panic!("Unexpected event"),
3716 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3718 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3719 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3720 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3721 assert_eq!(events_3.len(), 2);
3722 let as_announcement_sigs = match events_3[0] {
3723 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3724 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3727 _ => panic!("Unexpected event"),
3729 let (as_announcement, as_update) = match events_3[1] {
3730 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3731 (msg.clone(), update_msg.clone())
3733 _ => panic!("Unexpected event"),
3736 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3737 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3738 assert_eq!(events_4.len(), 1);
3739 let (_, bs_update) = match events_4[0] {
3740 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3741 (msg.clone(), update_msg.clone())
3743 _ => panic!("Unexpected event"),
3746 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3747 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3748 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3750 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3751 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3752 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3754 // Check that after deserialization and reconnection we can still generate an identical
3755 // channel_announcement from the cached signatures.
3756 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3758 let nodes_0_serialized = nodes[0].node.encode();
3759 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3760 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3762 persister = test_utils::TestPersister::new();
3763 let keys_manager = &chanmon_cfgs[0].keys_manager;
3764 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);
3765 nodes[0].chain_monitor = &new_chain_monitor;
3766 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3767 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3768 &mut chan_0_monitor_read, keys_manager).unwrap();
3769 assert!(chan_0_monitor_read.is_empty());
3771 let mut nodes_0_read = &nodes_0_serialized[..];
3772 let (_, nodes_0_deserialized_tmp) = {
3773 let mut channel_monitors = HashMap::new();
3774 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3775 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3776 default_config: UserConfig::default(),
3778 fee_estimator: node_cfgs[0].fee_estimator,
3779 chain_monitor: nodes[0].chain_monitor,
3780 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3781 logger: nodes[0].logger,
3785 nodes_0_deserialized = nodes_0_deserialized_tmp;
3786 assert!(nodes_0_read.is_empty());
3788 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3789 nodes[0].node = &nodes_0_deserialized;
3790 check_added_monitors!(nodes[0], 1);
3792 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3794 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3795 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3796 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3797 let mut found_announcement = false;
3798 for event in msgs.iter() {
3800 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3801 if *msg == as_announcement { found_announcement = true; }
3803 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3804 _ => panic!("Unexpected event"),
3807 assert!(found_announcement);
3811 fn test_drop_messages_peer_disconnect_dual_htlc() {
3812 // Test that we can handle reconnecting when both sides of a channel have pending
3813 // commitment_updates when we disconnect.
3814 let chanmon_cfgs = create_chanmon_cfgs(2);
3815 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3816 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3817 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3818 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3820 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3822 // Now try to send a second payment which will fail to send
3823 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3824 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3825 check_added_monitors!(nodes[0], 1);
3827 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3828 assert_eq!(events_1.len(), 1);
3830 MessageSendEvent::UpdateHTLCs { .. } => {},
3831 _ => panic!("Unexpected event"),
3834 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3835 check_added_monitors!(nodes[1], 1);
3837 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3838 assert_eq!(events_2.len(), 1);
3840 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 } } => {
3841 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3842 assert!(update_add_htlcs.is_empty());
3843 assert_eq!(update_fulfill_htlcs.len(), 1);
3844 assert!(update_fail_htlcs.is_empty());
3845 assert!(update_fail_malformed_htlcs.is_empty());
3846 assert!(update_fee.is_none());
3848 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3849 let events_3 = nodes[0].node.get_and_clear_pending_events();
3850 assert_eq!(events_3.len(), 1);
3852 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3853 assert_eq!(*payment_preimage, payment_preimage_1);
3854 assert_eq!(*payment_hash, payment_hash_1);
3856 _ => panic!("Unexpected event"),
3859 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3860 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3861 // No commitment_signed so get_event_msg's assert(len == 1) passes
3862 check_added_monitors!(nodes[0], 1);
3864 _ => panic!("Unexpected event"),
3867 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3868 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3870 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3871 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3872 assert_eq!(reestablish_1.len(), 1);
3873 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3874 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3875 assert_eq!(reestablish_2.len(), 1);
3877 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3878 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3879 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3880 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3882 assert!(as_resp.0.is_none());
3883 assert!(bs_resp.0.is_none());
3885 assert!(bs_resp.1.is_none());
3886 assert!(bs_resp.2.is_none());
3888 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3890 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3891 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3892 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3893 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3894 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3895 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3896 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3897 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3898 // No commitment_signed so get_event_msg's assert(len == 1) passes
3899 check_added_monitors!(nodes[1], 1);
3901 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3902 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3903 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3904 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3905 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3906 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3907 assert!(bs_second_commitment_signed.update_fee.is_none());
3908 check_added_monitors!(nodes[1], 1);
3910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3911 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3912 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3913 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3914 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3915 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3916 assert!(as_commitment_signed.update_fee.is_none());
3917 check_added_monitors!(nodes[0], 1);
3919 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3920 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3921 // No commitment_signed so get_event_msg's assert(len == 1) passes
3922 check_added_monitors!(nodes[0], 1);
3924 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3925 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3926 // No commitment_signed so get_event_msg's assert(len == 1) passes
3927 check_added_monitors!(nodes[1], 1);
3929 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3930 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3931 check_added_monitors!(nodes[1], 1);
3933 expect_pending_htlcs_forwardable!(nodes[1]);
3935 let events_5 = nodes[1].node.get_and_clear_pending_events();
3936 assert_eq!(events_5.len(), 1);
3938 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3939 assert_eq!(payment_hash_2, *payment_hash);
3941 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3942 assert!(payment_preimage.is_none());
3943 assert_eq!(payment_secret_2, *payment_secret);
3945 _ => panic!("expected PaymentPurpose::InvoicePayment")
3948 _ => panic!("Unexpected event"),
3951 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3952 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3953 check_added_monitors!(nodes[0], 1);
3955 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3958 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3959 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3960 // to avoid our counterparty failing the channel.
3961 let chanmon_cfgs = create_chanmon_cfgs(2);
3962 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3963 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3964 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3966 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3968 let our_payment_hash = if send_partial_mpp {
3969 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3970 // Use the utility function send_payment_along_path to send the payment with MPP data which
3971 // indicates there are more HTLCs coming.
3972 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.
3973 let payment_id = PaymentId([42; 32]);
3974 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();
3975 check_added_monitors!(nodes[0], 1);
3976 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3977 assert_eq!(events.len(), 1);
3978 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3979 // hop should *not* yet generate any PaymentReceived event(s).
3980 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3983 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3986 let mut block = Block {
3987 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3990 connect_block(&nodes[0], &block);
3991 connect_block(&nodes[1], &block);
3992 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3993 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3994 block.header.prev_blockhash = block.block_hash();
3995 connect_block(&nodes[0], &block);
3996 connect_block(&nodes[1], &block);
3999 expect_pending_htlcs_forwardable!(nodes[1]);
4001 check_added_monitors!(nodes[1], 1);
4002 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4003 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4004 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4005 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4006 assert!(htlc_timeout_updates.update_fee.is_none());
4008 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4009 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4010 // 100_000 msat as u64, followed by the height at which we failed back above
4011 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4012 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4013 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4017 fn test_htlc_timeout() {
4018 do_test_htlc_timeout(true);
4019 do_test_htlc_timeout(false);
4022 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4023 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4024 let chanmon_cfgs = create_chanmon_cfgs(3);
4025 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4026 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4027 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4028 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4031 // Make sure all nodes are at the same starting height
4032 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4033 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4034 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4036 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4037 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4039 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4041 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4042 check_added_monitors!(nodes[1], 1);
4044 // Now attempt to route a second payment, which should be placed in the holding cell
4045 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4046 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4047 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4049 check_added_monitors!(nodes[0], 1);
4050 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4051 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4052 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4053 expect_pending_htlcs_forwardable!(nodes[1]);
4055 check_added_monitors!(nodes[1], 0);
4057 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4058 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4059 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4060 connect_blocks(&nodes[1], 1);
4063 expect_pending_htlcs_forwardable!(nodes[1]);
4064 check_added_monitors!(nodes[1], 1);
4065 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4066 assert_eq!(fail_commit.len(), 1);
4067 match fail_commit[0] {
4068 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4069 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4070 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4072 _ => unreachable!(),
4074 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4076 expect_payment_failed!(nodes[1], second_payment_hash, true);
4081 fn test_holding_cell_htlc_add_timeouts() {
4082 do_test_holding_cell_htlc_add_timeouts(false);
4083 do_test_holding_cell_htlc_add_timeouts(true);
4087 fn test_no_txn_manager_serialize_deserialize() {
4088 let chanmon_cfgs = create_chanmon_cfgs(2);
4089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4091 let logger: test_utils::TestLogger;
4092 let fee_estimator: test_utils::TestFeeEstimator;
4093 let persister: test_utils::TestPersister;
4094 let new_chain_monitor: test_utils::TestChainMonitor;
4095 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4096 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4098 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4100 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4102 let nodes_0_serialized = nodes[0].node.encode();
4103 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4104 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4105 .write(&mut chan_0_monitor_serialized).unwrap();
4107 logger = test_utils::TestLogger::new();
4108 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4109 persister = test_utils::TestPersister::new();
4110 let keys_manager = &chanmon_cfgs[0].keys_manager;
4111 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4112 nodes[0].chain_monitor = &new_chain_monitor;
4113 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4114 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4115 &mut chan_0_monitor_read, keys_manager).unwrap();
4116 assert!(chan_0_monitor_read.is_empty());
4118 let mut nodes_0_read = &nodes_0_serialized[..];
4119 let config = UserConfig::default();
4120 let (_, nodes_0_deserialized_tmp) = {
4121 let mut channel_monitors = HashMap::new();
4122 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4123 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4124 default_config: config,
4126 fee_estimator: &fee_estimator,
4127 chain_monitor: nodes[0].chain_monitor,
4128 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4133 nodes_0_deserialized = nodes_0_deserialized_tmp;
4134 assert!(nodes_0_read.is_empty());
4136 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4137 nodes[0].node = &nodes_0_deserialized;
4138 assert_eq!(nodes[0].node.list_channels().len(), 1);
4139 check_added_monitors!(nodes[0], 1);
4141 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4142 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4143 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4144 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4146 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4147 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4148 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4149 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4151 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4152 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4153 for node in nodes.iter() {
4154 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4155 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4156 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4159 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4163 fn test_manager_serialize_deserialize_events() {
4164 // This test makes sure the events field in ChannelManager survives de/serialization
4165 let chanmon_cfgs = create_chanmon_cfgs(2);
4166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4168 let fee_estimator: test_utils::TestFeeEstimator;
4169 let persister: test_utils::TestPersister;
4170 let logger: test_utils::TestLogger;
4171 let new_chain_monitor: test_utils::TestChainMonitor;
4172 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4173 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4175 // Start creating a channel, but stop right before broadcasting the funding transaction
4176 let channel_value = 100000;
4177 let push_msat = 10001;
4178 let a_flags = InitFeatures::known();
4179 let b_flags = InitFeatures::known();
4180 let node_a = nodes.remove(0);
4181 let node_b = nodes.remove(0);
4182 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4183 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()));
4184 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()));
4186 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4188 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4189 check_added_monitors!(node_a, 0);
4191 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()));
4193 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4194 assert_eq!(added_monitors.len(), 1);
4195 assert_eq!(added_monitors[0].0, funding_output);
4196 added_monitors.clear();
4199 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4200 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4202 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4203 assert_eq!(added_monitors.len(), 1);
4204 assert_eq!(added_monitors[0].0, funding_output);
4205 added_monitors.clear();
4207 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4212 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4213 let nodes_0_serialized = nodes[0].node.encode();
4214 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4215 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4217 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4218 logger = test_utils::TestLogger::new();
4219 persister = test_utils::TestPersister::new();
4220 let keys_manager = &chanmon_cfgs[0].keys_manager;
4221 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4222 nodes[0].chain_monitor = &new_chain_monitor;
4223 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4224 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4225 &mut chan_0_monitor_read, keys_manager).unwrap();
4226 assert!(chan_0_monitor_read.is_empty());
4228 let mut nodes_0_read = &nodes_0_serialized[..];
4229 let config = UserConfig::default();
4230 let (_, nodes_0_deserialized_tmp) = {
4231 let mut channel_monitors = HashMap::new();
4232 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4233 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4234 default_config: config,
4236 fee_estimator: &fee_estimator,
4237 chain_monitor: nodes[0].chain_monitor,
4238 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4243 nodes_0_deserialized = nodes_0_deserialized_tmp;
4244 assert!(nodes_0_read.is_empty());
4246 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4248 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4249 nodes[0].node = &nodes_0_deserialized;
4251 // After deserializing, make sure the funding_transaction is still held by the channel manager
4252 let events_4 = nodes[0].node.get_and_clear_pending_events();
4253 assert_eq!(events_4.len(), 0);
4254 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4255 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4257 // Make sure the channel is functioning as though the de/serialization never happened
4258 assert_eq!(nodes[0].node.list_channels().len(), 1);
4259 check_added_monitors!(nodes[0], 1);
4261 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4262 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4263 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4264 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4266 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4267 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4268 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4269 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4271 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4272 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4273 for node in nodes.iter() {
4274 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4275 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4276 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4279 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4283 fn test_simple_manager_serialize_deserialize() {
4284 let chanmon_cfgs = create_chanmon_cfgs(2);
4285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4287 let logger: test_utils::TestLogger;
4288 let fee_estimator: test_utils::TestFeeEstimator;
4289 let persister: test_utils::TestPersister;
4290 let new_chain_monitor: test_utils::TestChainMonitor;
4291 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4292 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4293 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4295 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4296 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4298 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4300 let nodes_0_serialized = nodes[0].node.encode();
4301 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4302 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4304 logger = test_utils::TestLogger::new();
4305 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4306 persister = test_utils::TestPersister::new();
4307 let keys_manager = &chanmon_cfgs[0].keys_manager;
4308 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4309 nodes[0].chain_monitor = &new_chain_monitor;
4310 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4311 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4312 &mut chan_0_monitor_read, keys_manager).unwrap();
4313 assert!(chan_0_monitor_read.is_empty());
4315 let mut nodes_0_read = &nodes_0_serialized[..];
4316 let (_, nodes_0_deserialized_tmp) = {
4317 let mut channel_monitors = HashMap::new();
4318 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4319 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4320 default_config: UserConfig::default(),
4322 fee_estimator: &fee_estimator,
4323 chain_monitor: nodes[0].chain_monitor,
4324 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4329 nodes_0_deserialized = nodes_0_deserialized_tmp;
4330 assert!(nodes_0_read.is_empty());
4332 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4333 nodes[0].node = &nodes_0_deserialized;
4334 check_added_monitors!(nodes[0], 1);
4336 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4338 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4339 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4343 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4344 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4345 let chanmon_cfgs = create_chanmon_cfgs(4);
4346 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4347 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4348 let logger: test_utils::TestLogger;
4349 let fee_estimator: test_utils::TestFeeEstimator;
4350 let persister: test_utils::TestPersister;
4351 let new_chain_monitor: test_utils::TestChainMonitor;
4352 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4353 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4354 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4355 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4356 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4358 let mut node_0_stale_monitors_serialized = Vec::new();
4359 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4360 let mut writer = test_utils::TestVecWriter(Vec::new());
4361 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4362 node_0_stale_monitors_serialized.push(writer.0);
4365 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4367 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4368 let nodes_0_serialized = nodes[0].node.encode();
4370 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4371 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4372 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4373 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4375 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4377 let mut node_0_monitors_serialized = Vec::new();
4378 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4379 let mut writer = test_utils::TestVecWriter(Vec::new());
4380 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4381 node_0_monitors_serialized.push(writer.0);
4384 logger = test_utils::TestLogger::new();
4385 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4386 persister = test_utils::TestPersister::new();
4387 let keys_manager = &chanmon_cfgs[0].keys_manager;
4388 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4389 nodes[0].chain_monitor = &new_chain_monitor;
4392 let mut node_0_stale_monitors = Vec::new();
4393 for serialized in node_0_stale_monitors_serialized.iter() {
4394 let mut read = &serialized[..];
4395 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4396 assert!(read.is_empty());
4397 node_0_stale_monitors.push(monitor);
4400 let mut node_0_monitors = Vec::new();
4401 for serialized in node_0_monitors_serialized.iter() {
4402 let mut read = &serialized[..];
4403 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4404 assert!(read.is_empty());
4405 node_0_monitors.push(monitor);
4408 let mut nodes_0_read = &nodes_0_serialized[..];
4409 if let Err(msgs::DecodeError::InvalidValue) =
4410 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4411 default_config: UserConfig::default(),
4413 fee_estimator: &fee_estimator,
4414 chain_monitor: nodes[0].chain_monitor,
4415 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4417 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4419 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4422 let mut nodes_0_read = &nodes_0_serialized[..];
4423 let (_, nodes_0_deserialized_tmp) =
4424 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4425 default_config: UserConfig::default(),
4427 fee_estimator: &fee_estimator,
4428 chain_monitor: nodes[0].chain_monitor,
4429 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4431 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4433 nodes_0_deserialized = nodes_0_deserialized_tmp;
4434 assert!(nodes_0_read.is_empty());
4436 { // Channel close should result in a commitment tx
4437 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4438 assert_eq!(txn.len(), 1);
4439 check_spends!(txn[0], funding_tx);
4440 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4443 for monitor in node_0_monitors.drain(..) {
4444 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4445 check_added_monitors!(nodes[0], 1);
4447 nodes[0].node = &nodes_0_deserialized;
4448 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4450 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4451 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4452 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4453 //... and we can even still claim the payment!
4454 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4456 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4457 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4458 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4459 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4460 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4461 assert_eq!(msg_events.len(), 1);
4462 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4464 &ErrorAction::SendErrorMessage { ref msg } => {
4465 assert_eq!(msg.channel_id, channel_id);
4467 _ => panic!("Unexpected event!"),
4472 macro_rules! check_spendable_outputs {
4473 ($node: expr, $keysinterface: expr) => {
4475 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4476 let mut txn = Vec::new();
4477 let mut all_outputs = Vec::new();
4478 let secp_ctx = Secp256k1::new();
4479 for event in events.drain(..) {
4481 Event::SpendableOutputs { mut outputs } => {
4482 for outp in outputs.drain(..) {
4483 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4484 all_outputs.push(outp);
4487 _ => panic!("Unexpected event"),
4490 if all_outputs.len() > 1 {
4491 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) {
4501 fn test_claim_sizeable_push_msat() {
4502 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4503 let chanmon_cfgs = create_chanmon_cfgs(2);
4504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4508 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4509 nodes[1].node.force_close_channel(&chan.2).unwrap();
4510 check_closed_broadcast!(nodes[1], true);
4511 check_added_monitors!(nodes[1], 1);
4512 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4513 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4514 assert_eq!(node_txn.len(), 1);
4515 check_spends!(node_txn[0], chan.3);
4516 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
4518 mine_transaction(&nodes[1], &node_txn[0]);
4519 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4521 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4522 assert_eq!(spend_txn.len(), 1);
4523 assert_eq!(spend_txn[0].input.len(), 1);
4524 check_spends!(spend_txn[0], node_txn[0]);
4525 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4529 fn test_claim_on_remote_sizeable_push_msat() {
4530 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4531 // to_remote output is encumbered by a P2WPKH
4532 let chanmon_cfgs = create_chanmon_cfgs(2);
4533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4535 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4537 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4538 nodes[0].node.force_close_channel(&chan.2).unwrap();
4539 check_closed_broadcast!(nodes[0], true);
4540 check_added_monitors!(nodes[0], 1);
4541 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4543 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4544 assert_eq!(node_txn.len(), 1);
4545 check_spends!(node_txn[0], chan.3);
4546 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
4548 mine_transaction(&nodes[1], &node_txn[0]);
4549 check_closed_broadcast!(nodes[1], true);
4550 check_added_monitors!(nodes[1], 1);
4551 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4552 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4554 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4555 assert_eq!(spend_txn.len(), 1);
4556 check_spends!(spend_txn[0], node_txn[0]);
4560 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4561 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4562 // to_remote output is encumbered by a P2WPKH
4564 let chanmon_cfgs = create_chanmon_cfgs(2);
4565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4567 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4569 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4570 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4571 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4572 assert_eq!(revoked_local_txn[0].input.len(), 1);
4573 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4575 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4576 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4577 check_closed_broadcast!(nodes[1], true);
4578 check_added_monitors!(nodes[1], 1);
4579 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4581 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4582 mine_transaction(&nodes[1], &node_txn[0]);
4583 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4585 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4586 assert_eq!(spend_txn.len(), 3);
4587 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4588 check_spends!(spend_txn[1], node_txn[0]);
4589 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4593 fn test_static_spendable_outputs_preimage_tx() {
4594 let chanmon_cfgs = create_chanmon_cfgs(2);
4595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4597 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4599 // Create some initial channels
4600 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4602 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4604 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4605 assert_eq!(commitment_tx[0].input.len(), 1);
4606 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4608 // Settle A's commitment tx on B's chain
4609 assert!(nodes[1].node.claim_funds(payment_preimage));
4610 check_added_monitors!(nodes[1], 1);
4611 mine_transaction(&nodes[1], &commitment_tx[0]);
4612 check_added_monitors!(nodes[1], 1);
4613 let events = nodes[1].node.get_and_clear_pending_msg_events();
4615 MessageSendEvent::UpdateHTLCs { .. } => {},
4616 _ => panic!("Unexpected event"),
4619 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4620 _ => panic!("Unexepected event"),
4623 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4624 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4625 assert_eq!(node_txn.len(), 3);
4626 check_spends!(node_txn[0], commitment_tx[0]);
4627 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4628 check_spends!(node_txn[1], chan_1.3);
4629 check_spends!(node_txn[2], node_txn[1]);
4631 mine_transaction(&nodes[1], &node_txn[0]);
4632 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4633 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4635 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4636 assert_eq!(spend_txn.len(), 1);
4637 check_spends!(spend_txn[0], node_txn[0]);
4641 fn test_static_spendable_outputs_timeout_tx() {
4642 let chanmon_cfgs = create_chanmon_cfgs(2);
4643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4645 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4647 // Create some initial channels
4648 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4650 // Rebalance the network a bit by relaying one payment through all the channels ...
4651 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4653 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4655 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4656 assert_eq!(commitment_tx[0].input.len(), 1);
4657 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4659 // Settle A's commitment tx on B' chain
4660 mine_transaction(&nodes[1], &commitment_tx[0]);
4661 check_added_monitors!(nodes[1], 1);
4662 let events = nodes[1].node.get_and_clear_pending_msg_events();
4664 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4665 _ => panic!("Unexpected event"),
4667 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4669 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4670 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4671 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4672 check_spends!(node_txn[0], chan_1.3.clone());
4673 check_spends!(node_txn[1], commitment_tx[0].clone());
4674 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4676 mine_transaction(&nodes[1], &node_txn[1]);
4677 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4678 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4679 expect_payment_failed!(nodes[1], our_payment_hash, true);
4681 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4682 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4683 check_spends!(spend_txn[0], commitment_tx[0]);
4684 check_spends!(spend_txn[1], node_txn[1]);
4685 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4689 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4690 let chanmon_cfgs = create_chanmon_cfgs(2);
4691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4693 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4695 // Create some initial channels
4696 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4698 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4699 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4700 assert_eq!(revoked_local_txn[0].input.len(), 1);
4701 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4703 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4705 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4706 check_closed_broadcast!(nodes[1], true);
4707 check_added_monitors!(nodes[1], 1);
4708 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4710 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4711 assert_eq!(node_txn.len(), 2);
4712 assert_eq!(node_txn[0].input.len(), 2);
4713 check_spends!(node_txn[0], revoked_local_txn[0]);
4715 mine_transaction(&nodes[1], &node_txn[0]);
4716 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4718 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4719 assert_eq!(spend_txn.len(), 1);
4720 check_spends!(spend_txn[0], node_txn[0]);
4724 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4725 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4726 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4731 // Create some initial channels
4732 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4734 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4735 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4736 assert_eq!(revoked_local_txn[0].input.len(), 1);
4737 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4739 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4741 // A will generate HTLC-Timeout from revoked commitment tx
4742 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4743 check_closed_broadcast!(nodes[0], true);
4744 check_added_monitors!(nodes[0], 1);
4745 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4746 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4748 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4749 assert_eq!(revoked_htlc_txn.len(), 2);
4750 check_spends!(revoked_htlc_txn[0], chan_1.3);
4751 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4752 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4753 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4754 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4756 // B will generate justice tx from A's revoked commitment/HTLC tx
4757 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4758 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4759 check_closed_broadcast!(nodes[1], true);
4760 check_added_monitors!(nodes[1], 1);
4761 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4763 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4764 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4765 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4766 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4767 // transactions next...
4768 assert_eq!(node_txn[0].input.len(), 3);
4769 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4771 assert_eq!(node_txn[1].input.len(), 2);
4772 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4773 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4774 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4776 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4777 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4780 assert_eq!(node_txn[2].input.len(), 1);
4781 check_spends!(node_txn[2], chan_1.3);
4783 mine_transaction(&nodes[1], &node_txn[1]);
4784 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4786 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4787 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4788 assert_eq!(spend_txn.len(), 1);
4789 assert_eq!(spend_txn[0].input.len(), 1);
4790 check_spends!(spend_txn[0], node_txn[1]);
4794 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4795 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4796 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4799 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4801 // Create some initial channels
4802 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4804 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4805 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4806 assert_eq!(revoked_local_txn[0].input.len(), 1);
4807 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4809 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4810 assert_eq!(revoked_local_txn[0].output.len(), 2);
4812 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4814 // B will generate HTLC-Success from revoked commitment tx
4815 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4816 check_closed_broadcast!(nodes[1], true);
4817 check_added_monitors!(nodes[1], 1);
4818 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4819 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4821 assert_eq!(revoked_htlc_txn.len(), 2);
4822 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4823 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4824 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4826 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4827 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4828 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4830 // A will generate justice tx from B's revoked commitment/HTLC tx
4831 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4832 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4833 check_closed_broadcast!(nodes[0], true);
4834 check_added_monitors!(nodes[0], 1);
4835 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4837 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4838 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4840 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4841 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4842 // transactions next...
4843 assert_eq!(node_txn[0].input.len(), 2);
4844 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4845 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4846 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4848 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4849 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4852 assert_eq!(node_txn[1].input.len(), 1);
4853 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4855 check_spends!(node_txn[2], chan_1.3);
4857 mine_transaction(&nodes[0], &node_txn[1]);
4858 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4860 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4861 // didn't try to generate any new transactions.
4863 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4864 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4865 assert_eq!(spend_txn.len(), 3);
4866 assert_eq!(spend_txn[0].input.len(), 1);
4867 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4868 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4869 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4870 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4874 fn test_onchain_to_onchain_claim() {
4875 // Test that in case of channel closure, we detect the state of output and claim HTLC
4876 // on downstream peer's remote commitment tx.
4877 // First, have C claim an HTLC against its own latest commitment transaction.
4878 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4880 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4883 let chanmon_cfgs = create_chanmon_cfgs(3);
4884 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4885 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4886 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4888 // Create some initial channels
4889 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4890 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4892 // Ensure all nodes are at the same height
4893 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4894 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4895 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4896 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4898 // Rebalance the network a bit by relaying one payment through all the channels ...
4899 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4900 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4902 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4903 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4904 check_spends!(commitment_tx[0], chan_2.3);
4905 nodes[2].node.claim_funds(payment_preimage);
4906 check_added_monitors!(nodes[2], 1);
4907 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4908 assert!(updates.update_add_htlcs.is_empty());
4909 assert!(updates.update_fail_htlcs.is_empty());
4910 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4911 assert!(updates.update_fail_malformed_htlcs.is_empty());
4913 mine_transaction(&nodes[2], &commitment_tx[0]);
4914 check_closed_broadcast!(nodes[2], true);
4915 check_added_monitors!(nodes[2], 1);
4916 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4918 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4919 assert_eq!(c_txn.len(), 3);
4920 assert_eq!(c_txn[0], c_txn[2]);
4921 assert_eq!(commitment_tx[0], c_txn[1]);
4922 check_spends!(c_txn[1], chan_2.3);
4923 check_spends!(c_txn[2], c_txn[1]);
4924 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4925 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4926 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4927 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4929 // 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
4930 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4931 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4932 check_added_monitors!(nodes[1], 1);
4933 let events = nodes[1].node.get_and_clear_pending_events();
4934 assert_eq!(events.len(), 2);
4936 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4937 _ => panic!("Unexpected event"),
4940 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
4941 assert_eq!(fee_earned_msat, Some(1000));
4942 assert_eq!(claim_from_onchain_tx, true);
4944 _ => panic!("Unexpected event"),
4947 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4948 // ChannelMonitor: claim tx
4949 assert_eq!(b_txn.len(), 1);
4950 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4953 check_added_monitors!(nodes[1], 1);
4954 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4955 assert_eq!(msg_events.len(), 3);
4956 match msg_events[0] {
4957 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4958 _ => panic!("Unexpected event"),
4960 match msg_events[1] {
4961 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4962 _ => panic!("Unexpected event"),
4964 match msg_events[2] {
4965 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, .. } } => {
4966 assert!(update_add_htlcs.is_empty());
4967 assert!(update_fail_htlcs.is_empty());
4968 assert_eq!(update_fulfill_htlcs.len(), 1);
4969 assert!(update_fail_malformed_htlcs.is_empty());
4970 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4972 _ => panic!("Unexpected event"),
4974 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4975 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4976 mine_transaction(&nodes[1], &commitment_tx[0]);
4977 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4978 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4979 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4980 assert_eq!(b_txn.len(), 3);
4981 check_spends!(b_txn[1], chan_1.3);
4982 check_spends!(b_txn[2], b_txn[1]);
4983 check_spends!(b_txn[0], commitment_tx[0]);
4984 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4985 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4986 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4988 check_closed_broadcast!(nodes[1], true);
4989 check_added_monitors!(nodes[1], 1);
4993 fn test_duplicate_payment_hash_one_failure_one_success() {
4994 // Topology : A --> B --> C --> D
4995 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4996 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4997 // we forward one of the payments onwards to D.
4998 let chanmon_cfgs = create_chanmon_cfgs(4);
4999 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5000 // When this test was written, the default base fee floated based on the HTLC count.
5001 // It is now fixed, so we simply set the fee to the expected value here.
5002 let mut config = test_default_channel_config();
5003 config.channel_options.forwarding_fee_base_msat = 196;
5004 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5005 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5006 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5008 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5009 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5010 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5012 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5013 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5014 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5015 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5016 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5018 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5020 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5021 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5022 // script push size limit so that the below script length checks match
5023 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5024 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5025 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5027 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5028 assert_eq!(commitment_txn[0].input.len(), 1);
5029 check_spends!(commitment_txn[0], chan_2.3);
5031 mine_transaction(&nodes[1], &commitment_txn[0]);
5032 check_closed_broadcast!(nodes[1], true);
5033 check_added_monitors!(nodes[1], 1);
5034 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5035 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5037 let htlc_timeout_tx;
5038 { // Extract one of the two HTLC-Timeout transaction
5039 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5040 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5041 assert_eq!(node_txn.len(), 4);
5042 check_spends!(node_txn[0], chan_2.3);
5044 check_spends!(node_txn[1], commitment_txn[0]);
5045 assert_eq!(node_txn[1].input.len(), 1);
5046 check_spends!(node_txn[2], commitment_txn[0]);
5047 assert_eq!(node_txn[2].input.len(), 1);
5048 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5049 check_spends!(node_txn[3], commitment_txn[0]);
5050 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5052 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5053 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5054 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5055 htlc_timeout_tx = node_txn[1].clone();
5058 nodes[2].node.claim_funds(our_payment_preimage);
5059 mine_transaction(&nodes[2], &commitment_txn[0]);
5060 check_added_monitors!(nodes[2], 2);
5061 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5062 let events = nodes[2].node.get_and_clear_pending_msg_events();
5064 MessageSendEvent::UpdateHTLCs { .. } => {},
5065 _ => panic!("Unexpected event"),
5068 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5069 _ => panic!("Unexepected event"),
5071 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5072 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)
5073 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5074 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5075 assert_eq!(htlc_success_txn[0].input.len(), 1);
5076 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5077 assert_eq!(htlc_success_txn[1].input.len(), 1);
5078 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5079 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5080 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5081 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5082 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5083 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5085 mine_transaction(&nodes[1], &htlc_timeout_tx);
5086 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5087 expect_pending_htlcs_forwardable!(nodes[1]);
5088 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5089 assert!(htlc_updates.update_add_htlcs.is_empty());
5090 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5091 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5092 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5093 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5094 check_added_monitors!(nodes[1], 1);
5096 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5097 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5099 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5101 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5103 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5104 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5105 // and nodes[2] fee) is rounded down and then claimed in full.
5106 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5107 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5108 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5109 assert!(updates.update_add_htlcs.is_empty());
5110 assert!(updates.update_fail_htlcs.is_empty());
5111 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5112 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5113 assert!(updates.update_fail_malformed_htlcs.is_empty());
5114 check_added_monitors!(nodes[1], 1);
5116 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5117 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5119 let events = nodes[0].node.get_and_clear_pending_events();
5121 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5122 assert_eq!(*payment_preimage, our_payment_preimage);
5123 assert_eq!(*payment_hash, duplicate_payment_hash);
5125 _ => panic!("Unexpected event"),
5130 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5131 let chanmon_cfgs = create_chanmon_cfgs(2);
5132 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5136 // Create some initial channels
5137 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5139 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5140 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5141 assert_eq!(local_txn.len(), 1);
5142 assert_eq!(local_txn[0].input.len(), 1);
5143 check_spends!(local_txn[0], chan_1.3);
5145 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5146 nodes[1].node.claim_funds(payment_preimage);
5147 check_added_monitors!(nodes[1], 1);
5148 mine_transaction(&nodes[1], &local_txn[0]);
5149 check_added_monitors!(nodes[1], 1);
5150 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5151 let events = nodes[1].node.get_and_clear_pending_msg_events();
5153 MessageSendEvent::UpdateHTLCs { .. } => {},
5154 _ => panic!("Unexpected event"),
5157 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5158 _ => panic!("Unexepected event"),
5161 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5162 assert_eq!(node_txn.len(), 3);
5163 assert_eq!(node_txn[0], node_txn[2]);
5164 assert_eq!(node_txn[1], local_txn[0]);
5165 assert_eq!(node_txn[0].input.len(), 1);
5166 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5167 check_spends!(node_txn[0], local_txn[0]);
5171 mine_transaction(&nodes[1], &node_tx);
5172 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5174 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5175 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5176 assert_eq!(spend_txn.len(), 1);
5177 assert_eq!(spend_txn[0].input.len(), 1);
5178 check_spends!(spend_txn[0], node_tx);
5179 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5182 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5183 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5184 // unrevoked commitment transaction.
5185 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5186 // a remote RAA before they could be failed backwards (and combinations thereof).
5187 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5188 // use the same payment hashes.
5189 // Thus, we use a six-node network:
5194 // And test where C fails back to A/B when D announces its latest commitment transaction
5195 let chanmon_cfgs = create_chanmon_cfgs(6);
5196 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5197 // When this test was written, the default base fee floated based on the HTLC count.
5198 // It is now fixed, so we simply set the fee to the expected value here.
5199 let mut config = test_default_channel_config();
5200 config.channel_options.forwarding_fee_base_msat = 196;
5201 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5202 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5203 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5205 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5206 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5207 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5208 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5209 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5211 // Rebalance and check output sanity...
5212 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5213 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5214 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5216 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5218 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
5220 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
5221 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5223 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
5225 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
5227 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5229 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5230 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5232 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());
5234 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());
5237 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5239 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5240 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
5243 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
5245 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5246 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());
5248 // Double-check that six of the new HTLC were added
5249 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5250 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5251 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5252 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5254 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5255 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5256 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5257 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5258 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5259 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5260 check_added_monitors!(nodes[4], 0);
5261 expect_pending_htlcs_forwardable!(nodes[4]);
5262 check_added_monitors!(nodes[4], 1);
5264 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5265 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5266 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5267 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5268 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5269 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5271 // Fail 3rd below-dust and 7th above-dust HTLCs
5272 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5273 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5274 check_added_monitors!(nodes[5], 0);
5275 expect_pending_htlcs_forwardable!(nodes[5]);
5276 check_added_monitors!(nodes[5], 1);
5278 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5279 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5280 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5281 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5283 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5285 expect_pending_htlcs_forwardable!(nodes[3]);
5286 check_added_monitors!(nodes[3], 1);
5287 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5288 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5289 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5290 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5291 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5292 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5293 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5294 if deliver_last_raa {
5295 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5297 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5300 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5301 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5302 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5303 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5305 // We now broadcast the latest commitment transaction, which *should* result in failures for
5306 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5307 // the non-broadcast above-dust HTLCs.
5309 // Alternatively, we may broadcast the previous commitment transaction, which should only
5310 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5311 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5313 if announce_latest {
5314 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5316 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5318 let events = nodes[2].node.get_and_clear_pending_events();
5319 let close_event = if deliver_last_raa {
5320 assert_eq!(events.len(), 2);
5323 assert_eq!(events.len(), 1);
5327 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5328 _ => panic!("Unexpected event"),
5331 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5332 check_closed_broadcast!(nodes[2], true);
5333 if deliver_last_raa {
5334 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5336 expect_pending_htlcs_forwardable!(nodes[2]);
5338 check_added_monitors!(nodes[2], 3);
5340 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5341 assert_eq!(cs_msgs.len(), 2);
5342 let mut a_done = false;
5343 for msg in cs_msgs {
5345 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5346 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5347 // should be failed-backwards here.
5348 let target = if *node_id == nodes[0].node.get_our_node_id() {
5349 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5350 for htlc in &updates.update_fail_htlcs {
5351 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 });
5353 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5358 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5359 for htlc in &updates.update_fail_htlcs {
5360 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5362 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5363 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5366 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5367 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5368 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5369 if announce_latest {
5370 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5371 if *node_id == nodes[0].node.get_our_node_id() {
5372 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5375 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5377 _ => panic!("Unexpected event"),
5381 let as_events = nodes[0].node.get_and_clear_pending_events();
5382 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5383 let mut as_failds = HashSet::new();
5384 let mut as_updates = 0;
5385 for event in as_events.iter() {
5386 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5387 assert!(as_failds.insert(*payment_hash));
5388 if *payment_hash != payment_hash_2 {
5389 assert_eq!(*rejected_by_dest, deliver_last_raa);
5391 assert!(!rejected_by_dest);
5393 if network_update.is_some() {
5396 } else { panic!("Unexpected event"); }
5398 assert!(as_failds.contains(&payment_hash_1));
5399 assert!(as_failds.contains(&payment_hash_2));
5400 if announce_latest {
5401 assert!(as_failds.contains(&payment_hash_3));
5402 assert!(as_failds.contains(&payment_hash_5));
5404 assert!(as_failds.contains(&payment_hash_6));
5406 let bs_events = nodes[1].node.get_and_clear_pending_events();
5407 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5408 let mut bs_failds = HashSet::new();
5409 let mut bs_updates = 0;
5410 for event in bs_events.iter() {
5411 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5412 assert!(bs_failds.insert(*payment_hash));
5413 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5414 assert_eq!(*rejected_by_dest, deliver_last_raa);
5416 assert!(!rejected_by_dest);
5418 if network_update.is_some() {
5421 } else { panic!("Unexpected event"); }
5423 assert!(bs_failds.contains(&payment_hash_1));
5424 assert!(bs_failds.contains(&payment_hash_2));
5425 if announce_latest {
5426 assert!(bs_failds.contains(&payment_hash_4));
5428 assert!(bs_failds.contains(&payment_hash_5));
5430 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5431 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5432 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5433 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5434 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5435 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5439 fn test_fail_backwards_latest_remote_announce_a() {
5440 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5444 fn test_fail_backwards_latest_remote_announce_b() {
5445 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5449 fn test_fail_backwards_previous_remote_announce() {
5450 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5451 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5452 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5456 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5457 let chanmon_cfgs = create_chanmon_cfgs(2);
5458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5460 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5462 // Create some initial channels
5463 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5465 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5466 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5467 assert_eq!(local_txn[0].input.len(), 1);
5468 check_spends!(local_txn[0], chan_1.3);
5470 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5471 mine_transaction(&nodes[0], &local_txn[0]);
5472 check_closed_broadcast!(nodes[0], true);
5473 check_added_monitors!(nodes[0], 1);
5474 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5475 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5477 let htlc_timeout = {
5478 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5479 assert_eq!(node_txn.len(), 2);
5480 check_spends!(node_txn[0], chan_1.3);
5481 assert_eq!(node_txn[1].input.len(), 1);
5482 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5483 check_spends!(node_txn[1], local_txn[0]);
5487 mine_transaction(&nodes[0], &htlc_timeout);
5488 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5489 expect_payment_failed!(nodes[0], our_payment_hash, true);
5491 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5492 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5493 assert_eq!(spend_txn.len(), 3);
5494 check_spends!(spend_txn[0], local_txn[0]);
5495 assert_eq!(spend_txn[1].input.len(), 1);
5496 check_spends!(spend_txn[1], htlc_timeout);
5497 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5498 assert_eq!(spend_txn[2].input.len(), 2);
5499 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5500 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5501 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5505 fn test_key_derivation_params() {
5506 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5507 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5508 // let us re-derive the channel key set to then derive a delayed_payment_key.
5510 let chanmon_cfgs = create_chanmon_cfgs(3);
5512 // We manually create the node configuration to backup the seed.
5513 let seed = [42; 32];
5514 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5515 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);
5516 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() };
5517 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5518 node_cfgs.remove(0);
5519 node_cfgs.insert(0, node);
5521 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5522 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5524 // Create some initial channels
5525 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5527 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5528 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5529 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5531 // Ensure all nodes are at the same height
5532 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5533 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5534 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5535 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5537 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5538 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5539 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5540 assert_eq!(local_txn_1[0].input.len(), 1);
5541 check_spends!(local_txn_1[0], chan_1.3);
5543 // We check funding pubkey are unique
5544 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]));
5545 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]));
5546 if from_0_funding_key_0 == from_1_funding_key_0
5547 || from_0_funding_key_0 == from_1_funding_key_1
5548 || from_0_funding_key_1 == from_1_funding_key_0
5549 || from_0_funding_key_1 == from_1_funding_key_1 {
5550 panic!("Funding pubkeys aren't unique");
5553 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5554 mine_transaction(&nodes[0], &local_txn_1[0]);
5555 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5556 check_closed_broadcast!(nodes[0], true);
5557 check_added_monitors!(nodes[0], 1);
5558 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5560 let htlc_timeout = {
5561 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5562 assert_eq!(node_txn[1].input.len(), 1);
5563 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5564 check_spends!(node_txn[1], local_txn_1[0]);
5568 mine_transaction(&nodes[0], &htlc_timeout);
5569 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5570 expect_payment_failed!(nodes[0], our_payment_hash, true);
5572 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5573 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5574 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5575 assert_eq!(spend_txn.len(), 3);
5576 check_spends!(spend_txn[0], local_txn_1[0]);
5577 assert_eq!(spend_txn[1].input.len(), 1);
5578 check_spends!(spend_txn[1], htlc_timeout);
5579 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5580 assert_eq!(spend_txn[2].input.len(), 2);
5581 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5582 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5583 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5587 fn test_static_output_closing_tx() {
5588 let chanmon_cfgs = create_chanmon_cfgs(2);
5589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5593 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5595 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5596 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5598 mine_transaction(&nodes[0], &closing_tx);
5599 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5600 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5602 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5603 assert_eq!(spend_txn.len(), 1);
5604 check_spends!(spend_txn[0], closing_tx);
5606 mine_transaction(&nodes[1], &closing_tx);
5607 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5608 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5610 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5611 assert_eq!(spend_txn.len(), 1);
5612 check_spends!(spend_txn[0], closing_tx);
5615 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5616 let chanmon_cfgs = create_chanmon_cfgs(2);
5617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5619 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5620 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5622 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5624 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5625 // present in B's local commitment transaction, but none of A's commitment transactions.
5626 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5627 check_added_monitors!(nodes[1], 1);
5629 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5630 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5631 let events = nodes[0].node.get_and_clear_pending_events();
5632 assert_eq!(events.len(), 1);
5634 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
5635 assert_eq!(payment_preimage, our_payment_preimage);
5636 assert_eq!(payment_hash, our_payment_hash);
5638 _ => panic!("Unexpected event"),
5641 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5642 check_added_monitors!(nodes[0], 1);
5643 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5644 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5645 check_added_monitors!(nodes[1], 1);
5647 let starting_block = nodes[1].best_block_info();
5648 let mut block = Block {
5649 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5652 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5653 connect_block(&nodes[1], &block);
5654 block.header.prev_blockhash = block.block_hash();
5656 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5657 check_closed_broadcast!(nodes[1], true);
5658 check_added_monitors!(nodes[1], 1);
5659 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5662 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5663 let chanmon_cfgs = create_chanmon_cfgs(2);
5664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5666 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5667 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5669 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5670 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5671 check_added_monitors!(nodes[0], 1);
5673 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5675 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5676 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5677 // to "time out" the HTLC.
5679 let starting_block = nodes[1].best_block_info();
5680 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5682 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5683 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5684 header.prev_blockhash = header.block_hash();
5686 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5687 check_closed_broadcast!(nodes[0], true);
5688 check_added_monitors!(nodes[0], 1);
5689 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5692 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5693 let chanmon_cfgs = create_chanmon_cfgs(3);
5694 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5695 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5696 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5697 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5699 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5700 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5701 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5702 // actually revoked.
5703 let htlc_value = if use_dust { 50000 } else { 3000000 };
5704 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5705 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5706 expect_pending_htlcs_forwardable!(nodes[1]);
5707 check_added_monitors!(nodes[1], 1);
5709 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5710 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5711 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5712 check_added_monitors!(nodes[0], 1);
5713 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5714 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5715 check_added_monitors!(nodes[1], 1);
5716 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5717 check_added_monitors!(nodes[1], 1);
5718 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5720 if check_revoke_no_close {
5721 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5722 check_added_monitors!(nodes[0], 1);
5725 let starting_block = nodes[1].best_block_info();
5726 let mut block = Block {
5727 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5730 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5731 connect_block(&nodes[0], &block);
5732 block.header.prev_blockhash = block.block_hash();
5734 if !check_revoke_no_close {
5735 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5736 check_closed_broadcast!(nodes[0], true);
5737 check_added_monitors!(nodes[0], 1);
5738 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5740 expect_payment_failed!(nodes[0], our_payment_hash, true);
5744 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5745 // There are only a few cases to test here:
5746 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5747 // broadcastable commitment transactions result in channel closure,
5748 // * its included in an unrevoked-but-previous remote commitment transaction,
5749 // * its included in the latest remote or local commitment transactions.
5750 // We test each of the three possible commitment transactions individually and use both dust and
5752 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5753 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5754 // tested for at least one of the cases in other tests.
5756 fn htlc_claim_single_commitment_only_a() {
5757 do_htlc_claim_local_commitment_only(true);
5758 do_htlc_claim_local_commitment_only(false);
5760 do_htlc_claim_current_remote_commitment_only(true);
5761 do_htlc_claim_current_remote_commitment_only(false);
5765 fn htlc_claim_single_commitment_only_b() {
5766 do_htlc_claim_previous_remote_commitment_only(true, false);
5767 do_htlc_claim_previous_remote_commitment_only(false, false);
5768 do_htlc_claim_previous_remote_commitment_only(true, true);
5769 do_htlc_claim_previous_remote_commitment_only(false, true);
5774 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5775 let chanmon_cfgs = create_chanmon_cfgs(2);
5776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5778 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5779 //Force duplicate channel ids
5780 for node in nodes.iter() {
5781 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5784 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5785 let channel_value_satoshis=10000;
5786 let push_msat=10001;
5787 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5788 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5789 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5791 //Create a second channel with a channel_id collision
5792 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5796 fn bolt2_open_channel_sending_node_checks_part2() {
5797 let chanmon_cfgs = create_chanmon_cfgs(2);
5798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5800 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5802 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5803 let channel_value_satoshis=2^24;
5804 let push_msat=10001;
5805 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5807 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5808 let channel_value_satoshis=10000;
5809 // Test when push_msat is equal to 1000 * funding_satoshis.
5810 let push_msat=1000*channel_value_satoshis+1;
5811 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5813 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5814 let channel_value_satoshis=10000;
5815 let push_msat=10001;
5816 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
5817 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5818 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5820 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5821 // 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
5822 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5824 // 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.
5825 assert!(BREAKDOWN_TIMEOUT>0);
5826 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5828 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5829 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5830 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5832 // 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.
5833 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5834 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5835 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5836 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5837 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5841 fn bolt2_open_channel_sane_dust_limit() {
5842 let chanmon_cfgs = create_chanmon_cfgs(2);
5843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5847 let channel_value_satoshis=1000000;
5848 let push_msat=10001;
5849 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5850 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5851 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5852 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5854 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5855 let events = nodes[1].node.get_and_clear_pending_msg_events();
5856 let err_msg = match events[0] {
5857 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5860 _ => panic!("Unexpected event"),
5862 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5865 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5866 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5867 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5868 // is no longer affordable once it's freed.
5870 fn test_fail_holding_cell_htlc_upon_free() {
5871 let chanmon_cfgs = create_chanmon_cfgs(2);
5872 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5873 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5874 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5875 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5877 // First nodes[0] generates an update_fee, setting the channel's
5878 // pending_update_fee.
5880 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5881 *feerate_lock += 20;
5883 nodes[0].node.timer_tick_occurred();
5884 check_added_monitors!(nodes[0], 1);
5886 let events = nodes[0].node.get_and_clear_pending_msg_events();
5887 assert_eq!(events.len(), 1);
5888 let (update_msg, commitment_signed) = match events[0] {
5889 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5890 (update_fee.as_ref(), commitment_signed)
5892 _ => panic!("Unexpected event"),
5895 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5897 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5898 let channel_reserve = chan_stat.channel_reserve_msat;
5899 let feerate = get_feerate!(nodes[0], chan.2);
5901 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5902 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5903 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5905 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5906 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5907 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5908 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5910 // Flush the pending fee update.
5911 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5912 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5913 check_added_monitors!(nodes[1], 1);
5914 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5915 check_added_monitors!(nodes[0], 1);
5917 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5918 // HTLC, but now that the fee has been raised the payment will now fail, causing
5919 // us to surface its failure to the user.
5920 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5921 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5922 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);
5923 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 {}",
5924 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5925 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5927 // Check that the payment failed to be sent out.
5928 let events = nodes[0].node.get_and_clear_pending_events();
5929 assert_eq!(events.len(), 1);
5931 &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, .. } => {
5932 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
5933 assert_eq!(our_payment_hash.clone(), *payment_hash);
5934 assert_eq!(*rejected_by_dest, false);
5935 assert_eq!(*all_paths_failed, true);
5936 assert_eq!(*network_update, None);
5937 assert_eq!(*short_channel_id, None);
5938 assert_eq!(*error_code, None);
5939 assert_eq!(*error_data, None);
5941 _ => panic!("Unexpected event"),
5945 // Test that if multiple HTLCs are released from the holding cell and one is
5946 // valid but the other is no longer valid upon release, the valid HTLC can be
5947 // successfully completed while the other one fails as expected.
5949 fn test_free_and_fail_holding_cell_htlcs() {
5950 let chanmon_cfgs = create_chanmon_cfgs(2);
5951 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5952 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5953 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5954 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5956 // First nodes[0] generates an update_fee, setting the channel's
5957 // pending_update_fee.
5959 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5960 *feerate_lock += 200;
5962 nodes[0].node.timer_tick_occurred();
5963 check_added_monitors!(nodes[0], 1);
5965 let events = nodes[0].node.get_and_clear_pending_msg_events();
5966 assert_eq!(events.len(), 1);
5967 let (update_msg, commitment_signed) = match events[0] {
5968 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5969 (update_fee.as_ref(), commitment_signed)
5971 _ => panic!("Unexpected event"),
5974 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5976 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5977 let channel_reserve = chan_stat.channel_reserve_msat;
5978 let feerate = get_feerate!(nodes[0], chan.2);
5980 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5982 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
5983 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5984 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5986 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5987 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
5988 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5989 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5990 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
5991 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5992 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5994 // Flush the pending fee update.
5995 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5996 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5997 check_added_monitors!(nodes[1], 1);
5998 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5999 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6000 check_added_monitors!(nodes[0], 2);
6002 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6003 // but now that the fee has been raised the second payment will now fail, causing us
6004 // to surface its failure to the user. The first payment should succeed.
6005 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6006 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6007 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);
6008 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 {}",
6009 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6010 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6012 // Check that the second payment failed to be sent out.
6013 let events = nodes[0].node.get_and_clear_pending_events();
6014 assert_eq!(events.len(), 1);
6016 &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, .. } => {
6017 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6018 assert_eq!(payment_hash_2.clone(), *payment_hash);
6019 assert_eq!(*rejected_by_dest, false);
6020 assert_eq!(*all_paths_failed, true);
6021 assert_eq!(*network_update, None);
6022 assert_eq!(*short_channel_id, None);
6023 assert_eq!(*error_code, None);
6024 assert_eq!(*error_data, None);
6026 _ => panic!("Unexpected event"),
6029 // Complete the first payment and the RAA from the fee update.
6030 let (payment_event, send_raa_event) = {
6031 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6032 assert_eq!(msgs.len(), 2);
6033 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6035 let raa = match send_raa_event {
6036 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6037 _ => panic!("Unexpected event"),
6039 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6040 check_added_monitors!(nodes[1], 1);
6041 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6042 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6043 let events = nodes[1].node.get_and_clear_pending_events();
6044 assert_eq!(events.len(), 1);
6046 Event::PendingHTLCsForwardable { .. } => {},
6047 _ => panic!("Unexpected event"),
6049 nodes[1].node.process_pending_htlc_forwards();
6050 let events = nodes[1].node.get_and_clear_pending_events();
6051 assert_eq!(events.len(), 1);
6053 Event::PaymentReceived { .. } => {},
6054 _ => panic!("Unexpected event"),
6056 nodes[1].node.claim_funds(payment_preimage_1);
6057 check_added_monitors!(nodes[1], 1);
6058 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6059 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6060 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6061 let events = nodes[0].node.get_and_clear_pending_events();
6062 assert_eq!(events.len(), 1);
6064 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
6065 assert_eq!(*payment_preimage, payment_preimage_1);
6066 assert_eq!(*payment_hash, payment_hash_1);
6068 _ => panic!("Unexpected event"),
6072 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6073 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6074 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6077 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6078 let chanmon_cfgs = create_chanmon_cfgs(3);
6079 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6080 // When this test was written, the default base fee floated based on the HTLC count.
6081 // It is now fixed, so we simply set the fee to the expected value here.
6082 let mut config = test_default_channel_config();
6083 config.channel_options.forwarding_fee_base_msat = 196;
6084 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6085 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6086 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6087 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6089 // First nodes[1] generates an update_fee, setting the channel's
6090 // pending_update_fee.
6092 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6093 *feerate_lock += 20;
6095 nodes[1].node.timer_tick_occurred();
6096 check_added_monitors!(nodes[1], 1);
6098 let events = nodes[1].node.get_and_clear_pending_msg_events();
6099 assert_eq!(events.len(), 1);
6100 let (update_msg, commitment_signed) = match events[0] {
6101 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6102 (update_fee.as_ref(), commitment_signed)
6104 _ => panic!("Unexpected event"),
6107 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6109 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6110 let channel_reserve = chan_stat.channel_reserve_msat;
6111 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6113 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6115 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6116 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6117 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6118 let payment_event = {
6119 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6120 check_added_monitors!(nodes[0], 1);
6122 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6123 assert_eq!(events.len(), 1);
6125 SendEvent::from_event(events.remove(0))
6127 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6128 check_added_monitors!(nodes[1], 0);
6129 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6130 expect_pending_htlcs_forwardable!(nodes[1]);
6132 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6133 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6135 // Flush the pending fee update.
6136 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6137 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6138 check_added_monitors!(nodes[2], 1);
6139 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6140 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6141 check_added_monitors!(nodes[1], 2);
6143 // A final RAA message is generated to finalize the fee update.
6144 let events = nodes[1].node.get_and_clear_pending_msg_events();
6145 assert_eq!(events.len(), 1);
6147 let raa_msg = match &events[0] {
6148 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6151 _ => panic!("Unexpected event"),
6154 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6155 check_added_monitors!(nodes[2], 1);
6156 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6158 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6159 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6160 assert_eq!(process_htlc_forwards_event.len(), 1);
6161 match &process_htlc_forwards_event[0] {
6162 &Event::PendingHTLCsForwardable { .. } => {},
6163 _ => panic!("Unexpected event"),
6166 // In response, we call ChannelManager's process_pending_htlc_forwards
6167 nodes[1].node.process_pending_htlc_forwards();
6168 check_added_monitors!(nodes[1], 1);
6170 // This causes the HTLC to be failed backwards.
6171 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6172 assert_eq!(fail_event.len(), 1);
6173 let (fail_msg, commitment_signed) = match &fail_event[0] {
6174 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6175 assert_eq!(updates.update_add_htlcs.len(), 0);
6176 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6177 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6178 assert_eq!(updates.update_fail_htlcs.len(), 1);
6179 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6181 _ => panic!("Unexpected event"),
6184 // Pass the failure messages back to nodes[0].
6185 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6186 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6188 // Complete the HTLC failure+removal process.
6189 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6190 check_added_monitors!(nodes[0], 1);
6191 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6192 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6193 check_added_monitors!(nodes[1], 2);
6194 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6195 assert_eq!(final_raa_event.len(), 1);
6196 let raa = match &final_raa_event[0] {
6197 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6198 _ => panic!("Unexpected event"),
6200 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6201 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6202 check_added_monitors!(nodes[0], 1);
6205 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6206 // 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.
6207 //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.
6210 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6211 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6212 let chanmon_cfgs = create_chanmon_cfgs(2);
6213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6216 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6218 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6219 route.paths[0][0].fee_msat = 100;
6221 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6222 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6223 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6224 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6228 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6229 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6230 let chanmon_cfgs = create_chanmon_cfgs(2);
6231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6233 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6234 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6236 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6237 route.paths[0][0].fee_msat = 0;
6238 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6239 assert_eq!(err, "Cannot send 0-msat HTLC"));
6241 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6242 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6246 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6247 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6248 let chanmon_cfgs = create_chanmon_cfgs(2);
6249 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6250 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6251 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6252 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6254 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6255 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6256 check_added_monitors!(nodes[0], 1);
6257 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6258 updates.update_add_htlcs[0].amount_msat = 0;
6260 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6261 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6262 check_closed_broadcast!(nodes[1], true).unwrap();
6263 check_added_monitors!(nodes[1], 1);
6264 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6268 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6269 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6270 //It is enforced when constructing a route.
6271 let chanmon_cfgs = create_chanmon_cfgs(2);
6272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6274 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6275 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6277 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6278 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6279 assert_eq!(err, &"Channel CLTV overflowed?"));
6283 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6284 //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.
6285 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6286 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6287 let chanmon_cfgs = create_chanmon_cfgs(2);
6288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6290 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6291 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6292 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6294 for i in 0..max_accepted_htlcs {
6295 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6296 let payment_event = {
6297 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6298 check_added_monitors!(nodes[0], 1);
6300 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6301 assert_eq!(events.len(), 1);
6302 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6303 assert_eq!(htlcs[0].htlc_id, i);
6307 SendEvent::from_event(events.remove(0))
6309 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6310 check_added_monitors!(nodes[1], 0);
6311 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6313 expect_pending_htlcs_forwardable!(nodes[1]);
6314 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6316 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6317 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6318 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6320 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6321 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6325 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6326 //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.
6327 let chanmon_cfgs = create_chanmon_cfgs(2);
6328 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6329 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6330 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6331 let channel_value = 100000;
6332 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6333 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6335 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6337 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6338 // Manually create a route over our max in flight (which our router normally automatically
6340 route.paths[0][0].fee_msat = max_in_flight + 1;
6341 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6342 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)));
6344 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6345 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);
6347 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6350 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6352 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6353 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6354 let chanmon_cfgs = create_chanmon_cfgs(2);
6355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6357 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6358 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6359 let htlc_minimum_msat: u64;
6361 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6362 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6363 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6366 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6367 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6368 check_added_monitors!(nodes[0], 1);
6369 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6370 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6371 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6372 assert!(nodes[1].node.list_channels().is_empty());
6373 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6374 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()));
6375 check_added_monitors!(nodes[1], 1);
6376 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6380 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6381 //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
6382 let chanmon_cfgs = create_chanmon_cfgs(2);
6383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6385 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6386 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6388 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6389 let channel_reserve = chan_stat.channel_reserve_msat;
6390 let feerate = get_feerate!(nodes[0], chan.2);
6391 // The 2* and +1 are for the fee spike reserve.
6392 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6394 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6395 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6396 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6397 check_added_monitors!(nodes[0], 1);
6398 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6400 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6401 // at this time channel-initiatee receivers are not required to enforce that senders
6402 // respect the fee_spike_reserve.
6403 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6406 assert!(nodes[1].node.list_channels().is_empty());
6407 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6408 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6409 check_added_monitors!(nodes[1], 1);
6410 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6414 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6415 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6416 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6417 let chanmon_cfgs = create_chanmon_cfgs(2);
6418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6420 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6421 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6423 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6424 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6425 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6426 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6427 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6428 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6430 let mut msg = msgs::UpdateAddHTLC {
6434 payment_hash: our_payment_hash,
6435 cltv_expiry: htlc_cltv,
6436 onion_routing_packet: onion_packet.clone(),
6439 for i in 0..super::channel::OUR_MAX_HTLCS {
6440 msg.htlc_id = i as u64;
6441 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6443 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6444 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6446 assert!(nodes[1].node.list_channels().is_empty());
6447 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6448 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6449 check_added_monitors!(nodes[1], 1);
6450 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6454 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6455 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6456 let chanmon_cfgs = create_chanmon_cfgs(2);
6457 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6458 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6459 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6460 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6462 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6463 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6464 check_added_monitors!(nodes[0], 1);
6465 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6466 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6467 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6469 assert!(nodes[1].node.list_channels().is_empty());
6470 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6471 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6472 check_added_monitors!(nodes[1], 1);
6473 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6477 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6478 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6479 let chanmon_cfgs = create_chanmon_cfgs(2);
6480 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6481 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6482 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6484 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6485 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6486 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6487 check_added_monitors!(nodes[0], 1);
6488 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6489 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6492 assert!(nodes[1].node.list_channels().is_empty());
6493 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6494 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6495 check_added_monitors!(nodes[1], 1);
6496 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6500 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6501 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6502 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6503 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6504 let chanmon_cfgs = create_chanmon_cfgs(2);
6505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6507 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6509 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6510 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6511 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6512 check_added_monitors!(nodes[0], 1);
6513 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6514 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6516 //Disconnect and Reconnect
6517 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6518 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6519 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6520 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6521 assert_eq!(reestablish_1.len(), 1);
6522 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6523 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6524 assert_eq!(reestablish_2.len(), 1);
6525 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6526 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6527 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6528 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6531 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6532 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6533 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6534 check_added_monitors!(nodes[1], 1);
6535 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6537 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6539 assert!(nodes[1].node.list_channels().is_empty());
6540 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6541 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6542 check_added_monitors!(nodes[1], 1);
6543 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6547 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6548 //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.
6550 let chanmon_cfgs = create_chanmon_cfgs(2);
6551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6553 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6554 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6555 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6556 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6558 check_added_monitors!(nodes[0], 1);
6559 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6560 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6562 let update_msg = msgs::UpdateFulfillHTLC{
6565 payment_preimage: our_payment_preimage,
6568 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6570 assert!(nodes[0].node.list_channels().is_empty());
6571 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6572 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()));
6573 check_added_monitors!(nodes[0], 1);
6574 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6578 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6579 //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.
6581 let chanmon_cfgs = create_chanmon_cfgs(2);
6582 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6583 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6584 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6585 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6587 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6588 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6589 check_added_monitors!(nodes[0], 1);
6590 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6593 let update_msg = msgs::UpdateFailHTLC{
6596 reason: msgs::OnionErrorPacket { data: Vec::new()},
6599 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6601 assert!(nodes[0].node.list_channels().is_empty());
6602 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6603 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()));
6604 check_added_monitors!(nodes[0], 1);
6605 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6609 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6610 //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.
6612 let chanmon_cfgs = create_chanmon_cfgs(2);
6613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6615 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6616 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6618 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6619 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6620 check_added_monitors!(nodes[0], 1);
6621 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6623 let update_msg = msgs::UpdateFailMalformedHTLC{
6626 sha256_of_onion: [1; 32],
6627 failure_code: 0x8000,
6630 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6632 assert!(nodes[0].node.list_channels().is_empty());
6633 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6634 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()));
6635 check_added_monitors!(nodes[0], 1);
6636 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6640 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6641 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6643 let chanmon_cfgs = create_chanmon_cfgs(2);
6644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6646 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6647 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6649 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6651 nodes[1].node.claim_funds(our_payment_preimage);
6652 check_added_monitors!(nodes[1], 1);
6654 let events = nodes[1].node.get_and_clear_pending_msg_events();
6655 assert_eq!(events.len(), 1);
6656 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6658 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, .. } } => {
6659 assert!(update_add_htlcs.is_empty());
6660 assert_eq!(update_fulfill_htlcs.len(), 1);
6661 assert!(update_fail_htlcs.is_empty());
6662 assert!(update_fail_malformed_htlcs.is_empty());
6663 assert!(update_fee.is_none());
6664 update_fulfill_htlcs[0].clone()
6666 _ => panic!("Unexpected event"),
6670 update_fulfill_msg.htlc_id = 1;
6672 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6674 assert!(nodes[0].node.list_channels().is_empty());
6675 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6676 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6677 check_added_monitors!(nodes[0], 1);
6678 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6682 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6683 //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.
6685 let chanmon_cfgs = create_chanmon_cfgs(2);
6686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6691 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6693 nodes[1].node.claim_funds(our_payment_preimage);
6694 check_added_monitors!(nodes[1], 1);
6696 let events = nodes[1].node.get_and_clear_pending_msg_events();
6697 assert_eq!(events.len(), 1);
6698 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6700 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, .. } } => {
6701 assert!(update_add_htlcs.is_empty());
6702 assert_eq!(update_fulfill_htlcs.len(), 1);
6703 assert!(update_fail_htlcs.is_empty());
6704 assert!(update_fail_malformed_htlcs.is_empty());
6705 assert!(update_fee.is_none());
6706 update_fulfill_htlcs[0].clone()
6708 _ => panic!("Unexpected event"),
6712 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6714 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6716 assert!(nodes[0].node.list_channels().is_empty());
6717 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6718 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6719 check_added_monitors!(nodes[0], 1);
6720 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6724 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6725 //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.
6727 let chanmon_cfgs = create_chanmon_cfgs(2);
6728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6730 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6731 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6733 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6734 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6735 check_added_monitors!(nodes[0], 1);
6737 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6738 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6740 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6741 check_added_monitors!(nodes[1], 0);
6742 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6744 let events = nodes[1].node.get_and_clear_pending_msg_events();
6746 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6748 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, .. } } => {
6749 assert!(update_add_htlcs.is_empty());
6750 assert!(update_fulfill_htlcs.is_empty());
6751 assert!(update_fail_htlcs.is_empty());
6752 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6753 assert!(update_fee.is_none());
6754 update_fail_malformed_htlcs[0].clone()
6756 _ => panic!("Unexpected event"),
6759 update_msg.failure_code &= !0x8000;
6760 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6762 assert!(nodes[0].node.list_channels().is_empty());
6763 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6764 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6765 check_added_monitors!(nodes[0], 1);
6766 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6770 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6771 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6772 // * 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.
6774 let chanmon_cfgs = create_chanmon_cfgs(3);
6775 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6776 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6777 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6778 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6779 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6781 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6784 let mut payment_event = {
6785 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6786 check_added_monitors!(nodes[0], 1);
6787 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6788 assert_eq!(events.len(), 1);
6789 SendEvent::from_event(events.remove(0))
6791 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6792 check_added_monitors!(nodes[1], 0);
6793 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6794 expect_pending_htlcs_forwardable!(nodes[1]);
6795 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6796 assert_eq!(events_2.len(), 1);
6797 check_added_monitors!(nodes[1], 1);
6798 payment_event = SendEvent::from_event(events_2.remove(0));
6799 assert_eq!(payment_event.msgs.len(), 1);
6802 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6803 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6804 check_added_monitors!(nodes[2], 0);
6805 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6807 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6808 assert_eq!(events_3.len(), 1);
6809 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6811 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 } } => {
6812 assert!(update_add_htlcs.is_empty());
6813 assert!(update_fulfill_htlcs.is_empty());
6814 assert!(update_fail_htlcs.is_empty());
6815 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6816 assert!(update_fee.is_none());
6817 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6819 _ => panic!("Unexpected event"),
6823 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6825 check_added_monitors!(nodes[1], 0);
6826 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6827 expect_pending_htlcs_forwardable!(nodes[1]);
6828 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6829 assert_eq!(events_4.len(), 1);
6831 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6833 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, .. } } => {
6834 assert!(update_add_htlcs.is_empty());
6835 assert!(update_fulfill_htlcs.is_empty());
6836 assert_eq!(update_fail_htlcs.len(), 1);
6837 assert!(update_fail_malformed_htlcs.is_empty());
6838 assert!(update_fee.is_none());
6840 _ => panic!("Unexpected event"),
6843 check_added_monitors!(nodes[1], 1);
6846 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6847 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6848 // 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
6849 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6851 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6852 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6853 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6854 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6855 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6856 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6858 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6860 // We route 2 dust-HTLCs between A and B
6861 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6862 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6863 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6865 // Cache one local commitment tx as previous
6866 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6868 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6869 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6870 check_added_monitors!(nodes[1], 0);
6871 expect_pending_htlcs_forwardable!(nodes[1]);
6872 check_added_monitors!(nodes[1], 1);
6874 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6875 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6876 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6877 check_added_monitors!(nodes[0], 1);
6879 // Cache one local commitment tx as lastest
6880 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6882 let events = nodes[0].node.get_and_clear_pending_msg_events();
6884 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6885 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6887 _ => panic!("Unexpected event"),
6890 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6891 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6893 _ => panic!("Unexpected event"),
6896 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6897 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6898 if announce_latest {
6899 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6901 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6904 check_closed_broadcast!(nodes[0], true);
6905 check_added_monitors!(nodes[0], 1);
6906 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6908 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6909 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6910 let events = nodes[0].node.get_and_clear_pending_events();
6911 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6912 assert_eq!(events.len(), 2);
6913 let mut first_failed = false;
6914 for event in events {
6916 Event::PaymentPathFailed { payment_hash, .. } => {
6917 if payment_hash == payment_hash_1 {
6918 assert!(!first_failed);
6919 first_failed = true;
6921 assert_eq!(payment_hash, payment_hash_2);
6924 _ => panic!("Unexpected event"),
6930 fn test_failure_delay_dust_htlc_local_commitment() {
6931 do_test_failure_delay_dust_htlc_local_commitment(true);
6932 do_test_failure_delay_dust_htlc_local_commitment(false);
6935 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6936 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6937 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6938 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6939 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6940 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6941 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6943 let chanmon_cfgs = create_chanmon_cfgs(3);
6944 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6945 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6946 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6947 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6949 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6951 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6952 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6954 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6955 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6957 // We revoked bs_commitment_tx
6959 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6960 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6963 let mut timeout_tx = Vec::new();
6965 // We fail dust-HTLC 1 by broadcast of local commitment tx
6966 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6967 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6968 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6969 expect_payment_failed!(nodes[0], dust_hash, true);
6971 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6972 check_closed_broadcast!(nodes[0], true);
6973 check_added_monitors!(nodes[0], 1);
6974 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6975 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6976 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6977 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6978 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6979 mine_transaction(&nodes[0], &timeout_tx[0]);
6980 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6981 expect_payment_failed!(nodes[0], non_dust_hash, true);
6983 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6984 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6985 check_closed_broadcast!(nodes[0], true);
6986 check_added_monitors!(nodes[0], 1);
6987 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6988 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6989 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6990 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6992 expect_payment_failed!(nodes[0], dust_hash, true);
6993 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6994 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6995 mine_transaction(&nodes[0], &timeout_tx[0]);
6996 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6997 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6998 expect_payment_failed!(nodes[0], non_dust_hash, true);
7000 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7002 let events = nodes[0].node.get_and_clear_pending_events();
7003 assert_eq!(events.len(), 2);
7006 Event::PaymentPathFailed { payment_hash, .. } => {
7007 if payment_hash == dust_hash { first = true; }
7008 else { first = false; }
7010 _ => panic!("Unexpected event"),
7013 Event::PaymentPathFailed { payment_hash, .. } => {
7014 if first { assert_eq!(payment_hash, non_dust_hash); }
7015 else { assert_eq!(payment_hash, dust_hash); }
7017 _ => panic!("Unexpected event"),
7024 fn test_sweep_outbound_htlc_failure_update() {
7025 do_test_sweep_outbound_htlc_failure_update(false, true);
7026 do_test_sweep_outbound_htlc_failure_update(false, false);
7027 do_test_sweep_outbound_htlc_failure_update(true, false);
7031 fn test_user_configurable_csv_delay() {
7032 // We test our channel constructors yield errors when we pass them absurd csv delay
7034 let mut low_our_to_self_config = UserConfig::default();
7035 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7036 let mut high_their_to_self_config = UserConfig::default();
7037 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7038 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7039 let chanmon_cfgs = create_chanmon_cfgs(2);
7040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7042 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7044 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7045 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) {
7047 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())); },
7048 _ => panic!("Unexpected event"),
7050 } else { assert!(false) }
7052 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7053 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7054 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7055 open_channel.to_self_delay = 200;
7056 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) {
7058 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())); },
7059 _ => panic!("Unexpected event"),
7061 } else { assert!(false); }
7063 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7064 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7065 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()));
7066 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7067 accept_channel.to_self_delay = 200;
7068 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7070 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7072 &ErrorAction::SendErrorMessage { ref msg } => {
7073 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()));
7074 reason_msg = msg.data.clone();
7078 } else { panic!(); }
7079 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7081 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7082 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7083 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7084 open_channel.to_self_delay = 200;
7085 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) {
7087 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())); },
7088 _ => panic!("Unexpected event"),
7090 } else { assert!(false); }
7094 fn test_data_loss_protect() {
7095 // We want to be sure that :
7096 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7097 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7098 // * we close channel in case of detecting other being fallen behind
7099 // * we are able to claim our own outputs thanks to to_remote being static
7100 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7106 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7107 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7108 // during signing due to revoked tx
7109 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7110 let keys_manager = &chanmon_cfgs[0].keys_manager;
7113 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7114 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7115 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7117 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7119 // Cache node A state before any channel update
7120 let previous_node_state = nodes[0].node.encode();
7121 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7122 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7124 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7125 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7127 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7128 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7130 // Restore node A from previous state
7131 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7132 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7133 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7134 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7135 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7136 persister = test_utils::TestPersister::new();
7137 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7139 let mut channel_monitors = HashMap::new();
7140 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7141 <(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 {
7142 keys_manager: keys_manager,
7143 fee_estimator: &fee_estimator,
7144 chain_monitor: &monitor,
7146 tx_broadcaster: &tx_broadcaster,
7147 default_config: UserConfig::default(),
7151 nodes[0].node = &node_state_0;
7152 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7153 nodes[0].chain_monitor = &monitor;
7154 nodes[0].chain_source = &chain_source;
7156 check_added_monitors!(nodes[0], 1);
7158 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7159 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7161 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7163 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7164 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7165 check_added_monitors!(nodes[0], 1);
7168 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7169 assert_eq!(node_txn.len(), 0);
7172 let mut reestablish_1 = Vec::with_capacity(1);
7173 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7174 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7175 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7176 reestablish_1.push(msg.clone());
7177 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7178 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7180 &ErrorAction::SendErrorMessage { ref msg } => {
7181 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");
7183 _ => panic!("Unexpected event!"),
7186 panic!("Unexpected event")
7190 // Check we close channel detecting A is fallen-behind
7191 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7192 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7193 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7194 check_added_monitors!(nodes[1], 1);
7196 // Check A is able to claim to_remote output
7197 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7198 assert_eq!(node_txn.len(), 1);
7199 check_spends!(node_txn[0], chan.3);
7200 assert_eq!(node_txn[0].output.len(), 2);
7201 mine_transaction(&nodes[0], &node_txn[0]);
7202 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7203 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() });
7204 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7205 assert_eq!(spend_txn.len(), 1);
7206 check_spends!(spend_txn[0], node_txn[0]);
7210 fn test_check_htlc_underpaying() {
7211 // Send payment through A -> B but A is maliciously
7212 // sending a probe payment (i.e less than expected value0
7213 // to B, B should refuse payment.
7215 let chanmon_cfgs = create_chanmon_cfgs(2);
7216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7218 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7220 // Create some initial channels
7221 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7223 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7224 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7225 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();
7226 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7227 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7228 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7229 check_added_monitors!(nodes[0], 1);
7231 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7232 assert_eq!(events.len(), 1);
7233 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7234 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7235 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7237 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7238 // and then will wait a second random delay before failing the HTLC back:
7239 expect_pending_htlcs_forwardable!(nodes[1]);
7240 expect_pending_htlcs_forwardable!(nodes[1]);
7242 // Node 3 is expecting payment of 100_000 but received 10_000,
7243 // it should fail htlc like we didn't know the preimage.
7244 nodes[1].node.process_pending_htlc_forwards();
7246 let events = nodes[1].node.get_and_clear_pending_msg_events();
7247 assert_eq!(events.len(), 1);
7248 let (update_fail_htlc, commitment_signed) = match events[0] {
7249 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 } } => {
7250 assert!(update_add_htlcs.is_empty());
7251 assert!(update_fulfill_htlcs.is_empty());
7252 assert_eq!(update_fail_htlcs.len(), 1);
7253 assert!(update_fail_malformed_htlcs.is_empty());
7254 assert!(update_fee.is_none());
7255 (update_fail_htlcs[0].clone(), commitment_signed)
7257 _ => panic!("Unexpected event"),
7259 check_added_monitors!(nodes[1], 1);
7261 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7262 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7264 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7265 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7266 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7267 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7271 fn test_announce_disable_channels() {
7272 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7273 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7275 let chanmon_cfgs = create_chanmon_cfgs(2);
7276 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7277 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7278 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7280 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7281 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7282 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7285 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7286 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7288 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7289 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7290 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7291 assert_eq!(msg_events.len(), 3);
7292 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7293 for e in msg_events {
7295 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7296 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7297 // Check that each channel gets updated exactly once
7298 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7299 panic!("Generated ChannelUpdate for wrong chan!");
7302 _ => panic!("Unexpected event"),
7306 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7307 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7308 assert_eq!(reestablish_1.len(), 3);
7309 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7310 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7311 assert_eq!(reestablish_2.len(), 3);
7313 // Reestablish chan_1
7314 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7315 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7316 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7317 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7318 // Reestablish chan_2
7319 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7320 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7321 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7322 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7323 // Reestablish chan_3
7324 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7325 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7326 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7327 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7329 nodes[0].node.timer_tick_occurred();
7330 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7331 nodes[0].node.timer_tick_occurred();
7332 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7333 assert_eq!(msg_events.len(), 3);
7334 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7335 for e in msg_events {
7337 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7338 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7339 // Check that each channel gets updated exactly once
7340 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7341 panic!("Generated ChannelUpdate for wrong chan!");
7344 _ => panic!("Unexpected event"),
7350 fn test_priv_forwarding_rejection() {
7351 // If we have a private channel with outbound liquidity, and
7352 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7353 // to forward through that channel.
7354 let chanmon_cfgs = create_chanmon_cfgs(3);
7355 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7356 let mut no_announce_cfg = test_default_channel_config();
7357 no_announce_cfg.channel_options.announced_channel = false;
7358 no_announce_cfg.accept_forwards_to_priv_channels = false;
7359 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7360 let persister: test_utils::TestPersister;
7361 let new_chain_monitor: test_utils::TestChainMonitor;
7362 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7363 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7365 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;
7367 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7368 // not send for private channels.
7369 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7370 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7371 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7372 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7373 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7375 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7376 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7377 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()));
7378 check_added_monitors!(nodes[2], 1);
7380 let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7381 nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7382 check_added_monitors!(nodes[1], 1);
7384 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7385 confirm_transaction_at(&nodes[1], &tx, conf_height);
7386 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7387 confirm_transaction_at(&nodes[2], &tx, conf_height);
7388 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7389 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7390 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()));
7391 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7392 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7393 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7395 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7396 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7397 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7399 // We should always be able to forward through nodes[1] as long as its out through a public
7401 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7403 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7404 // to nodes[2], which should be rejected:
7405 let route_hint = RouteHint(vec![RouteHintHop {
7406 src_node_id: nodes[1].node.get_our_node_id(),
7407 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7408 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7409 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7410 htlc_minimum_msat: None,
7411 htlc_maximum_msat: None,
7413 let last_hops = vec![route_hint];
7414 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);
7416 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7417 check_added_monitors!(nodes[0], 1);
7418 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7420 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7422 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7423 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7424 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7425 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7426 assert!(htlc_fail_updates.update_fee.is_none());
7428 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7429 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7430 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7432 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7433 // to true. Sadly there is currently no way to change it at runtime.
7435 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7436 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7438 let nodes_1_serialized = nodes[1].node.encode();
7439 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7440 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7441 get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7442 get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7444 persister = test_utils::TestPersister::new();
7445 let keys_manager = &chanmon_cfgs[1].keys_manager;
7446 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);
7447 nodes[1].chain_monitor = &new_chain_monitor;
7449 let mut monitor_a_read = &monitor_a_serialized.0[..];
7450 let mut monitor_b_read = &monitor_b_serialized.0[..];
7451 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7452 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7453 assert!(monitor_a_read.is_empty());
7454 assert!(monitor_b_read.is_empty());
7456 no_announce_cfg.accept_forwards_to_priv_channels = true;
7458 let mut nodes_1_read = &nodes_1_serialized[..];
7459 let (_, nodes_1_deserialized_tmp) = {
7460 let mut channel_monitors = HashMap::new();
7461 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7462 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7463 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7464 default_config: no_announce_cfg,
7466 fee_estimator: node_cfgs[1].fee_estimator,
7467 chain_monitor: nodes[1].chain_monitor,
7468 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7469 logger: nodes[1].logger,
7473 assert!(nodes_1_read.is_empty());
7474 nodes_1_deserialized = nodes_1_deserialized_tmp;
7476 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7477 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7478 check_added_monitors!(nodes[1], 2);
7479 nodes[1].node = &nodes_1_deserialized;
7481 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7482 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7483 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7484 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7485 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7486 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7487 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7488 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7490 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7491 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7492 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7493 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7494 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7495 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7496 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7497 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7499 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7500 check_added_monitors!(nodes[0], 1);
7501 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7502 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7506 fn test_bump_penalty_txn_on_revoked_commitment() {
7507 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7508 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7510 let chanmon_cfgs = create_chanmon_cfgs(2);
7511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7513 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7515 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7517 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7518 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7519 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7521 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7522 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7523 assert_eq!(revoked_txn[0].output.len(), 4);
7524 assert_eq!(revoked_txn[0].input.len(), 1);
7525 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7526 let revoked_txid = revoked_txn[0].txid();
7528 let mut penalty_sum = 0;
7529 for outp in revoked_txn[0].output.iter() {
7530 if outp.script_pubkey.is_v0_p2wsh() {
7531 penalty_sum += outp.value;
7535 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7536 let header_114 = connect_blocks(&nodes[1], 14);
7538 // Actually revoke tx by claiming a HTLC
7539 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7540 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7541 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7542 check_added_monitors!(nodes[1], 1);
7544 // One or more justice tx should have been broadcast, check it
7548 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7549 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7550 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7551 assert_eq!(node_txn[0].output.len(), 1);
7552 check_spends!(node_txn[0], revoked_txn[0]);
7553 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7554 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7555 penalty_1 = node_txn[0].txid();
7559 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7560 connect_blocks(&nodes[1], 15);
7561 let mut penalty_2 = penalty_1;
7562 let mut feerate_2 = 0;
7564 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7565 assert_eq!(node_txn.len(), 1);
7566 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7567 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7568 assert_eq!(node_txn[0].output.len(), 1);
7569 check_spends!(node_txn[0], revoked_txn[0]);
7570 penalty_2 = node_txn[0].txid();
7571 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7572 assert_ne!(penalty_2, penalty_1);
7573 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7574 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7575 // Verify 25% bump heuristic
7576 assert!(feerate_2 * 100 >= feerate_1 * 125);
7580 assert_ne!(feerate_2, 0);
7582 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7583 connect_blocks(&nodes[1], 1);
7585 let mut feerate_3 = 0;
7587 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7588 assert_eq!(node_txn.len(), 1);
7589 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7590 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7591 assert_eq!(node_txn[0].output.len(), 1);
7592 check_spends!(node_txn[0], revoked_txn[0]);
7593 penalty_3 = node_txn[0].txid();
7594 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7595 assert_ne!(penalty_3, penalty_2);
7596 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7597 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7598 // Verify 25% bump heuristic
7599 assert!(feerate_3 * 100 >= feerate_2 * 125);
7603 assert_ne!(feerate_3, 0);
7605 nodes[1].node.get_and_clear_pending_events();
7606 nodes[1].node.get_and_clear_pending_msg_events();
7610 fn test_bump_penalty_txn_on_revoked_htlcs() {
7611 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7612 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7614 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7615 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7618 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7620 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7621 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7622 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7623 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7624 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, &nodes[0].network_graph, None,
7625 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7626 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7627 let payee = Payee::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7628 let route = get_route(&nodes[1].node.get_our_node_id(), &payee, nodes[1].network_graph, None,
7629 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7630 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7632 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7633 assert_eq!(revoked_local_txn[0].input.len(), 1);
7634 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7636 // Revoke local commitment tx
7637 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7639 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7640 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7641 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7642 check_closed_broadcast!(nodes[1], true);
7643 check_added_monitors!(nodes[1], 1);
7644 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7645 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7647 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7648 assert_eq!(revoked_htlc_txn.len(), 3);
7649 check_spends!(revoked_htlc_txn[1], chan.3);
7651 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7652 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7653 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7655 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7656 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7657 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7658 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7660 // Broadcast set of revoked txn on A
7661 let hash_128 = connect_blocks(&nodes[0], 40);
7662 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7663 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7664 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7665 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7666 let events = nodes[0].node.get_and_clear_pending_events();
7667 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7669 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7670 _ => panic!("Unexpected event"),
7676 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7677 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7678 // Verify claim tx are spending revoked HTLC txn
7680 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7681 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7682 // which are included in the same block (they are broadcasted because we scan the
7683 // transactions linearly and generate claims as we go, they likely should be removed in the
7685 assert_eq!(node_txn[0].input.len(), 1);
7686 check_spends!(node_txn[0], revoked_local_txn[0]);
7687 assert_eq!(node_txn[1].input.len(), 1);
7688 check_spends!(node_txn[1], revoked_local_txn[0]);
7689 assert_eq!(node_txn[2].input.len(), 1);
7690 check_spends!(node_txn[2], revoked_local_txn[0]);
7692 // Each of the three justice transactions claim a separate (single) output of the three
7693 // available, which we check here:
7694 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7695 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7696 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7698 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7699 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7701 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7702 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7703 // a remote commitment tx has already been confirmed).
7704 check_spends!(node_txn[3], chan.3);
7706 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7707 // output, checked above).
7708 assert_eq!(node_txn[4].input.len(), 2);
7709 assert_eq!(node_txn[4].output.len(), 1);
7710 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7712 first = node_txn[4].txid();
7713 // Store both feerates for later comparison
7714 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7715 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7716 penalty_txn = vec![node_txn[2].clone()];
7720 // Connect one more block to see if bumped penalty are issued for HTLC txn
7721 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7722 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7723 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7724 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7726 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7727 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7729 check_spends!(node_txn[0], revoked_local_txn[0]);
7730 check_spends!(node_txn[1], revoked_local_txn[0]);
7731 // Note that these are both bogus - they spend outputs already claimed in block 129:
7732 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7733 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7735 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7736 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7742 // Few more blocks to confirm penalty txn
7743 connect_blocks(&nodes[0], 4);
7744 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7745 let header_144 = connect_blocks(&nodes[0], 9);
7747 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7748 assert_eq!(node_txn.len(), 1);
7750 assert_eq!(node_txn[0].input.len(), 2);
7751 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7752 // Verify bumped tx is different and 25% bump heuristic
7753 assert_ne!(first, node_txn[0].txid());
7754 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7755 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7756 assert!(feerate_2 * 100 > feerate_1 * 125);
7757 let txn = vec![node_txn[0].clone()];
7761 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7762 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7763 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7764 connect_blocks(&nodes[0], 20);
7766 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7767 // We verify than no new transaction has been broadcast because previously
7768 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7769 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7770 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7771 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7772 // up bumped justice generation.
7773 assert_eq!(node_txn.len(), 0);
7776 check_closed_broadcast!(nodes[0], true);
7777 check_added_monitors!(nodes[0], 1);
7781 fn test_bump_penalty_txn_on_remote_commitment() {
7782 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7783 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7786 // Provide preimage for one
7787 // Check aggregation
7789 let chanmon_cfgs = create_chanmon_cfgs(2);
7790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7792 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7794 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7795 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7796 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7798 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7799 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7800 assert_eq!(remote_txn[0].output.len(), 4);
7801 assert_eq!(remote_txn[0].input.len(), 1);
7802 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7804 // Claim a HTLC without revocation (provide B monitor with preimage)
7805 nodes[1].node.claim_funds(payment_preimage);
7806 mine_transaction(&nodes[1], &remote_txn[0]);
7807 check_added_monitors!(nodes[1], 2);
7808 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7810 // One or more claim tx should have been broadcast, check it
7814 let feerate_timeout;
7815 let feerate_preimage;
7817 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7818 // 9 transactions including:
7819 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7820 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7821 // 2 * HTLC-Success (one RBF bump we'll check later)
7823 assert_eq!(node_txn.len(), 8);
7824 assert_eq!(node_txn[0].input.len(), 1);
7825 assert_eq!(node_txn[6].input.len(), 1);
7826 check_spends!(node_txn[0], remote_txn[0]);
7827 check_spends!(node_txn[6], remote_txn[0]);
7828 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7829 preimage_bump = node_txn[3].clone();
7831 check_spends!(node_txn[1], chan.3);
7832 check_spends!(node_txn[2], node_txn[1]);
7833 assert_eq!(node_txn[1], node_txn[4]);
7834 assert_eq!(node_txn[2], node_txn[5]);
7836 timeout = node_txn[6].txid();
7837 let index = node_txn[6].input[0].previous_output.vout;
7838 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7839 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7841 preimage = node_txn[0].txid();
7842 let index = node_txn[0].input[0].previous_output.vout;
7843 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7844 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7848 assert_ne!(feerate_timeout, 0);
7849 assert_ne!(feerate_preimage, 0);
7851 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7852 connect_blocks(&nodes[1], 15);
7854 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7855 assert_eq!(node_txn.len(), 1);
7856 assert_eq!(node_txn[0].input.len(), 1);
7857 assert_eq!(preimage_bump.input.len(), 1);
7858 check_spends!(node_txn[0], remote_txn[0]);
7859 check_spends!(preimage_bump, remote_txn[0]);
7861 let index = preimage_bump.input[0].previous_output.vout;
7862 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7863 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7864 assert!(new_feerate * 100 > feerate_timeout * 125);
7865 assert_ne!(timeout, preimage_bump.txid());
7867 let index = node_txn[0].input[0].previous_output.vout;
7868 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7869 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7870 assert!(new_feerate * 100 > feerate_preimage * 125);
7871 assert_ne!(preimage, node_txn[0].txid());
7876 nodes[1].node.get_and_clear_pending_events();
7877 nodes[1].node.get_and_clear_pending_msg_events();
7881 fn test_counterparty_raa_skip_no_crash() {
7882 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7883 // commitment transaction, we would have happily carried on and provided them the next
7884 // commitment transaction based on one RAA forward. This would probably eventually have led to
7885 // channel closure, but it would not have resulted in funds loss. Still, our
7886 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7887 // check simply that the channel is closed in response to such an RAA, but don't check whether
7888 // we decide to punish our counterparty for revoking their funds (as we don't currently
7890 let chanmon_cfgs = create_chanmon_cfgs(2);
7891 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7892 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7893 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7894 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7896 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7897 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7899 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7901 // Make signer believe we got a counterparty signature, so that it allows the revocation
7902 keys.get_enforcement_state().last_holder_commitment -= 1;
7903 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7905 // Must revoke without gaps
7906 keys.get_enforcement_state().last_holder_commitment -= 1;
7907 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7909 keys.get_enforcement_state().last_holder_commitment -= 1;
7910 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7911 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7913 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7914 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7915 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7916 check_added_monitors!(nodes[1], 1);
7917 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7921 fn test_bump_txn_sanitize_tracking_maps() {
7922 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7923 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7925 let chanmon_cfgs = create_chanmon_cfgs(2);
7926 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7927 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7928 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7930 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7931 // Lock HTLC in both directions
7932 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7933 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7935 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7936 assert_eq!(revoked_local_txn[0].input.len(), 1);
7937 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7939 // Revoke local commitment tx
7940 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7942 // Broadcast set of revoked txn on A
7943 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7944 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7945 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7947 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7948 check_closed_broadcast!(nodes[0], true);
7949 check_added_monitors!(nodes[0], 1);
7950 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7952 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7953 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7954 check_spends!(node_txn[0], revoked_local_txn[0]);
7955 check_spends!(node_txn[1], revoked_local_txn[0]);
7956 check_spends!(node_txn[2], revoked_local_txn[0]);
7957 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7961 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7962 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7963 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7965 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7966 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7967 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7972 fn test_channel_conf_timeout() {
7973 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7974 // confirm within 2016 blocks, as recommended by BOLT 2.
7975 let chanmon_cfgs = create_chanmon_cfgs(2);
7976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7978 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7980 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
7982 // The outbound node should wait forever for confirmation:
7983 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7984 // copied here instead of directly referencing the constant.
7985 connect_blocks(&nodes[0], 2016);
7986 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7988 // The inbound node should fail the channel after exactly 2016 blocks
7989 connect_blocks(&nodes[1], 2015);
7990 check_added_monitors!(nodes[1], 0);
7991 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7993 connect_blocks(&nodes[1], 1);
7994 check_added_monitors!(nodes[1], 1);
7995 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7996 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7997 assert_eq!(close_ev.len(), 1);
7999 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8000 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8001 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8003 _ => panic!("Unexpected event"),
8008 fn test_override_channel_config() {
8009 let chanmon_cfgs = create_chanmon_cfgs(2);
8010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8012 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8014 // Node0 initiates a channel to node1 using the override config.
8015 let mut override_config = UserConfig::default();
8016 override_config.own_channel_config.our_to_self_delay = 200;
8018 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8020 // Assert the channel created by node0 is using the override config.
8021 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8022 assert_eq!(res.channel_flags, 0);
8023 assert_eq!(res.to_self_delay, 200);
8027 fn test_override_0msat_htlc_minimum() {
8028 let mut zero_config = UserConfig::default();
8029 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8030 let chanmon_cfgs = create_chanmon_cfgs(2);
8031 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8032 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8033 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8035 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8036 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8037 assert_eq!(res.htlc_minimum_msat, 1);
8039 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8040 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8041 assert_eq!(res.htlc_minimum_msat, 1);
8045 fn test_simple_mpp() {
8046 // Simple test of sending a multi-path payment.
8047 let chanmon_cfgs = create_chanmon_cfgs(4);
8048 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8049 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8050 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8052 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8053 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8054 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8055 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8057 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8058 let path = route.paths[0].clone();
8059 route.paths.push(path);
8060 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8061 route.paths[0][0].short_channel_id = chan_1_id;
8062 route.paths[0][1].short_channel_id = chan_3_id;
8063 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8064 route.paths[1][0].short_channel_id = chan_2_id;
8065 route.paths[1][1].short_channel_id = chan_4_id;
8066 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8067 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8071 fn test_preimage_storage() {
8072 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8073 let chanmon_cfgs = create_chanmon_cfgs(2);
8074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8078 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8081 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200);
8082 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8083 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8084 check_added_monitors!(nodes[0], 1);
8085 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8086 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8087 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8088 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8090 // Note that after leaving the above scope we have no knowledge of any arguments or return
8091 // values from previous calls.
8092 expect_pending_htlcs_forwardable!(nodes[1]);
8093 let events = nodes[1].node.get_and_clear_pending_events();
8094 assert_eq!(events.len(), 1);
8096 Event::PaymentReceived { ref purpose, .. } => {
8098 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8099 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8101 _ => panic!("expected PaymentPurpose::InvoicePayment")
8104 _ => panic!("Unexpected event"),
8109 fn test_secret_timeout() {
8110 // Simple test of payment secret storage time outs
8111 let chanmon_cfgs = create_chanmon_cfgs(2);
8112 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8113 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8114 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8116 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8118 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2);
8120 // We should fail to register the same payment hash twice, at least until we've connected a
8121 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8122 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2) {
8123 assert_eq!(err, "Duplicate payment hash");
8124 } else { panic!(); }
8126 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8128 header: BlockHeader {
8130 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8131 merkle_root: Default::default(),
8132 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8136 connect_block(&nodes[1], &block);
8137 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2) {
8138 assert_eq!(err, "Duplicate payment hash");
8139 } else { panic!(); }
8141 // If we then connect the second block, we should be able to register the same payment hash
8142 // again (this time getting a new payment secret).
8143 block.header.prev_blockhash = block.header.block_hash();
8144 block.header.time += 1;
8145 connect_block(&nodes[1], &block);
8146 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2).unwrap();
8147 assert_ne!(payment_secret_1, our_payment_secret);
8150 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8151 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8152 check_added_monitors!(nodes[0], 1);
8153 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8154 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8155 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8156 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8158 // Note that after leaving the above scope we have no knowledge of any arguments or return
8159 // values from previous calls.
8160 expect_pending_htlcs_forwardable!(nodes[1]);
8161 let events = nodes[1].node.get_and_clear_pending_events();
8162 assert_eq!(events.len(), 1);
8164 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8165 assert!(payment_preimage.is_none());
8166 assert_eq!(payment_secret, our_payment_secret);
8167 // We don't actually have the payment preimage with which to claim this payment!
8169 _ => panic!("Unexpected event"),
8174 fn test_bad_secret_hash() {
8175 // Simple test of unregistered payment hash/invalid payment secret handling
8176 let chanmon_cfgs = create_chanmon_cfgs(2);
8177 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8178 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8179 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8181 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8183 let random_payment_hash = PaymentHash([42; 32]);
8184 let random_payment_secret = PaymentSecret([43; 32]);
8185 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2);
8186 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8188 // All the below cases should end up being handled exactly identically, so we macro the
8189 // resulting events.
8190 macro_rules! handle_unknown_invalid_payment_data {
8192 check_added_monitors!(nodes[0], 1);
8193 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8194 let payment_event = SendEvent::from_event(events.pop().unwrap());
8195 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8196 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8198 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8199 // again to process the pending backwards-failure of the HTLC
8200 expect_pending_htlcs_forwardable!(nodes[1]);
8201 expect_pending_htlcs_forwardable!(nodes[1]);
8202 check_added_monitors!(nodes[1], 1);
8204 // We should fail the payment back
8205 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8206 match events.pop().unwrap() {
8207 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8208 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8209 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8211 _ => panic!("Unexpected event"),
8216 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8217 // Error data is the HTLC value (100,000) and current block height
8218 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8220 // Send a payment with the right payment hash but the wrong payment secret
8221 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8222 handle_unknown_invalid_payment_data!();
8223 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8225 // Send a payment with a random payment hash, but the right payment secret
8226 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8227 handle_unknown_invalid_payment_data!();
8228 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8230 // Send a payment with a random payment hash and random payment secret
8231 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8232 handle_unknown_invalid_payment_data!();
8233 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8237 fn test_update_err_monitor_lockdown() {
8238 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8239 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8240 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8242 // This scenario may happen in a watchtower setup, where watchtower process a block height
8243 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8244 // commitment at same time.
8246 let chanmon_cfgs = create_chanmon_cfgs(2);
8247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8249 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8251 // Create some initial channel
8252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8253 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8255 // Rebalance the network to generate htlc in the two directions
8256 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8258 // Route a HTLC from node 0 to node 1 (but don't settle)
8259 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8261 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8262 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8263 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8264 let persister = test_utils::TestPersister::new();
8266 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8267 let mut w = test_utils::TestVecWriter(Vec::new());
8268 monitor.write(&mut w).unwrap();
8269 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8270 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8271 assert!(new_monitor == *monitor);
8272 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);
8273 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8276 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8277 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8278 // transaction lock time requirements here.
8279 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8280 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8282 // Try to update ChannelMonitor
8283 assert!(nodes[1].node.claim_funds(preimage));
8284 check_added_monitors!(nodes[1], 1);
8285 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8286 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8287 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8288 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8289 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8290 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8291 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8292 } else { assert!(false); }
8293 } else { assert!(false); };
8294 // Our local monitor is in-sync and hasn't processed yet timeout
8295 check_added_monitors!(nodes[0], 1);
8296 let events = nodes[0].node.get_and_clear_pending_events();
8297 assert_eq!(events.len(), 1);
8301 fn test_concurrent_monitor_claim() {
8302 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8303 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8304 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8305 // state N+1 confirms. Alice claims output from state N+1.
8307 let chanmon_cfgs = create_chanmon_cfgs(2);
8308 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8309 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8310 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8312 // Create some initial channel
8313 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8314 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8316 // Rebalance the network to generate htlc in the two directions
8317 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8319 // Route a HTLC from node 0 to node 1 (but don't settle)
8320 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8322 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8323 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8324 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8325 let persister = test_utils::TestPersister::new();
8326 let watchtower_alice = {
8327 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8328 let mut w = test_utils::TestVecWriter(Vec::new());
8329 monitor.write(&mut w).unwrap();
8330 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8331 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8332 assert!(new_monitor == *monitor);
8333 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);
8334 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8337 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8338 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8339 // transaction lock time requirements here.
8340 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8341 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8343 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8345 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8346 assert_eq!(txn.len(), 2);
8350 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8351 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8352 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8353 let persister = test_utils::TestPersister::new();
8354 let watchtower_bob = {
8355 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8356 let mut w = test_utils::TestVecWriter(Vec::new());
8357 monitor.write(&mut w).unwrap();
8358 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8359 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8360 assert!(new_monitor == *monitor);
8361 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);
8362 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8365 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8366 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8368 // Route another payment to generate another update with still previous HTLC pending
8369 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8371 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8373 check_added_monitors!(nodes[1], 1);
8375 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8376 assert_eq!(updates.update_add_htlcs.len(), 1);
8377 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8378 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8379 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8380 // Watchtower Alice should already have seen the block and reject the update
8381 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8382 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8383 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8384 } else { assert!(false); }
8385 } else { assert!(false); };
8386 // Our local monitor is in-sync and hasn't processed yet timeout
8387 check_added_monitors!(nodes[0], 1);
8389 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8390 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8391 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8393 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8396 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8397 assert_eq!(txn.len(), 2);
8398 bob_state_y = txn[0].clone();
8402 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8404 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);
8406 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8407 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8408 // the onchain detection of the HTLC output
8409 assert_eq!(htlc_txn.len(), 2);
8410 check_spends!(htlc_txn[0], bob_state_y);
8411 check_spends!(htlc_txn[1], bob_state_y);
8416 fn test_pre_lockin_no_chan_closed_update() {
8417 // Test that if a peer closes a channel in response to a funding_created message we don't
8418 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8421 // Doing so would imply a channel monitor update before the initial channel monitor
8422 // registration, violating our API guarantees.
8424 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8425 // then opening a second channel with the same funding output as the first (which is not
8426 // rejected because the first channel does not exist in the ChannelManager) and closing it
8427 // before receiving funding_signed.
8428 let chanmon_cfgs = create_chanmon_cfgs(2);
8429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8433 // Create an initial channel
8434 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8435 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8436 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8437 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8438 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8440 // Move the first channel through the funding flow...
8441 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8443 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8444 check_added_monitors!(nodes[0], 0);
8446 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8447 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8448 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8449 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8450 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8454 fn test_htlc_no_detection() {
8455 // This test is a mutation to underscore the detection logic bug we had
8456 // before #653. HTLC value routed is above the remaining balance, thus
8457 // inverting HTLC and `to_remote` output. HTLC will come second and
8458 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8459 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8460 // outputs order detection for correct spending children filtring.
8462 let chanmon_cfgs = create_chanmon_cfgs(2);
8463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8467 // Create some initial channels
8468 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8470 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8471 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8472 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8473 assert_eq!(local_txn[0].input.len(), 1);
8474 assert_eq!(local_txn[0].output.len(), 3);
8475 check_spends!(local_txn[0], chan_1.3);
8477 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8478 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8479 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8480 // We deliberately connect the local tx twice as this should provoke a failure calling
8481 // this test before #653 fix.
8482 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);
8483 check_closed_broadcast!(nodes[0], true);
8484 check_added_monitors!(nodes[0], 1);
8485 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8486 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8488 let htlc_timeout = {
8489 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8490 assert_eq!(node_txn[1].input.len(), 1);
8491 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8492 check_spends!(node_txn[1], local_txn[0]);
8496 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8497 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8498 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8499 expect_payment_failed!(nodes[0], our_payment_hash, true);
8502 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8503 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8504 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8505 // Carol, Alice would be the upstream node, and Carol the downstream.)
8507 // Steps of the test:
8508 // 1) Alice sends a HTLC to Carol through Bob.
8509 // 2) Carol doesn't settle the HTLC.
8510 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8511 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8512 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8513 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8514 // 5) Carol release the preimage to Bob off-chain.
8515 // 6) Bob claims the offered output on the broadcasted commitment.
8516 let chanmon_cfgs = create_chanmon_cfgs(3);
8517 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8518 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8519 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8521 // Create some initial channels
8522 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8523 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8525 // Steps (1) and (2):
8526 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8527 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8529 // Check that Alice's commitment transaction now contains an output for this HTLC.
8530 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8531 check_spends!(alice_txn[0], chan_ab.3);
8532 assert_eq!(alice_txn[0].output.len(), 2);
8533 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8534 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8535 assert_eq!(alice_txn.len(), 2);
8537 // Steps (3) and (4):
8538 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8539 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8540 let mut force_closing_node = 0; // Alice force-closes
8541 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8542 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8543 check_closed_broadcast!(nodes[force_closing_node], true);
8544 check_added_monitors!(nodes[force_closing_node], 1);
8545 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8546 if go_onchain_before_fulfill {
8547 let txn_to_broadcast = match broadcast_alice {
8548 true => alice_txn.clone(),
8549 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8551 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8552 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8553 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8554 if broadcast_alice {
8555 check_closed_broadcast!(nodes[1], true);
8556 check_added_monitors!(nodes[1], 1);
8557 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8559 assert_eq!(bob_txn.len(), 1);
8560 check_spends!(bob_txn[0], chan_ab.3);
8564 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8565 // process of removing the HTLC from their commitment transactions.
8566 assert!(nodes[2].node.claim_funds(payment_preimage));
8567 check_added_monitors!(nodes[2], 1);
8568 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8569 assert!(carol_updates.update_add_htlcs.is_empty());
8570 assert!(carol_updates.update_fail_htlcs.is_empty());
8571 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8572 assert!(carol_updates.update_fee.is_none());
8573 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8575 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8576 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8577 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8578 if !go_onchain_before_fulfill && broadcast_alice {
8579 let events = nodes[1].node.get_and_clear_pending_msg_events();
8580 assert_eq!(events.len(), 1);
8582 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8583 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8585 _ => panic!("Unexpected event"),
8588 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8589 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8590 // Carol<->Bob's updated commitment transaction info.
8591 check_added_monitors!(nodes[1], 2);
8593 let events = nodes[1].node.get_and_clear_pending_msg_events();
8594 assert_eq!(events.len(), 2);
8595 let bob_revocation = match events[0] {
8596 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8597 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8600 _ => panic!("Unexpected event"),
8602 let bob_updates = match events[1] {
8603 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8604 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8607 _ => panic!("Unexpected event"),
8610 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8611 check_added_monitors!(nodes[2], 1);
8612 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8613 check_added_monitors!(nodes[2], 1);
8615 let events = nodes[2].node.get_and_clear_pending_msg_events();
8616 assert_eq!(events.len(), 1);
8617 let carol_revocation = match events[0] {
8618 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8619 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8622 _ => panic!("Unexpected event"),
8624 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8625 check_added_monitors!(nodes[1], 1);
8627 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8628 // here's where we put said channel's commitment tx on-chain.
8629 let mut txn_to_broadcast = alice_txn.clone();
8630 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8631 if !go_onchain_before_fulfill {
8632 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8633 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8634 // If Bob was the one to force-close, he will have already passed these checks earlier.
8635 if broadcast_alice {
8636 check_closed_broadcast!(nodes[1], true);
8637 check_added_monitors!(nodes[1], 1);
8638 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8640 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8641 if broadcast_alice {
8642 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8643 // new block being connected. The ChannelManager being notified triggers a monitor update,
8644 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8645 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8647 assert_eq!(bob_txn.len(), 3);
8648 check_spends!(bob_txn[1], chan_ab.3);
8650 assert_eq!(bob_txn.len(), 2);
8651 check_spends!(bob_txn[0], chan_ab.3);
8656 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8657 // broadcasted commitment transaction.
8659 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8660 if go_onchain_before_fulfill {
8661 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8662 assert_eq!(bob_txn.len(), 2);
8664 let script_weight = match broadcast_alice {
8665 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8666 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8668 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8669 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8670 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8671 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8672 if broadcast_alice && !go_onchain_before_fulfill {
8673 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8674 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8676 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8677 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8683 fn test_onchain_htlc_settlement_after_close() {
8684 do_test_onchain_htlc_settlement_after_close(true, true);
8685 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8686 do_test_onchain_htlc_settlement_after_close(true, false);
8687 do_test_onchain_htlc_settlement_after_close(false, false);
8691 fn test_duplicate_chan_id() {
8692 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8693 // already open we reject it and keep the old channel.
8695 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8696 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8697 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8698 // updating logic for the existing channel.
8699 let chanmon_cfgs = create_chanmon_cfgs(2);
8700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8704 // Create an initial channel
8705 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8706 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8707 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8708 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()));
8710 // Try to create a second channel with the same temporary_channel_id as the first and check
8711 // that it is rejected.
8712 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8714 let events = nodes[1].node.get_and_clear_pending_msg_events();
8715 assert_eq!(events.len(), 1);
8717 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8718 // Technically, at this point, nodes[1] would be justified in thinking both the
8719 // first (valid) and second (invalid) channels are closed, given they both have
8720 // the same non-temporary channel_id. However, currently we do not, so we just
8721 // move forward with it.
8722 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8723 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8725 _ => panic!("Unexpected event"),
8729 // Move the first channel through the funding flow...
8730 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8732 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8733 check_added_monitors!(nodes[0], 0);
8735 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8736 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8738 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8739 assert_eq!(added_monitors.len(), 1);
8740 assert_eq!(added_monitors[0].0, funding_output);
8741 added_monitors.clear();
8743 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8745 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8746 let channel_id = funding_outpoint.to_channel_id();
8748 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8751 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8752 // Technically this is allowed by the spec, but we don't support it and there's little reason
8753 // to. Still, it shouldn't cause any other issues.
8754 open_chan_msg.temporary_channel_id = channel_id;
8755 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8757 let events = nodes[1].node.get_and_clear_pending_msg_events();
8758 assert_eq!(events.len(), 1);
8760 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8761 // Technically, at this point, nodes[1] would be justified in thinking both
8762 // channels are closed, but currently we do not, so we just move forward with it.
8763 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8764 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8766 _ => panic!("Unexpected event"),
8770 // Now try to create a second channel which has a duplicate funding output.
8771 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8772 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8773 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8774 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()));
8775 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8777 let funding_created = {
8778 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8779 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8780 let logger = test_utils::TestLogger::new();
8781 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8783 check_added_monitors!(nodes[0], 0);
8784 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8785 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8786 // still needs to be cleared here.
8787 check_added_monitors!(nodes[1], 1);
8789 // ...still, nodes[1] will reject the duplicate channel.
8791 let events = nodes[1].node.get_and_clear_pending_msg_events();
8792 assert_eq!(events.len(), 1);
8794 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8795 // Technically, at this point, nodes[1] would be justified in thinking both
8796 // channels are closed, but currently we do not, so we just move forward with it.
8797 assert_eq!(msg.channel_id, channel_id);
8798 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8800 _ => panic!("Unexpected event"),
8804 // finally, finish creating the original channel and send a payment over it to make sure
8805 // everything is functional.
8806 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8808 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8809 assert_eq!(added_monitors.len(), 1);
8810 assert_eq!(added_monitors[0].0, funding_output);
8811 added_monitors.clear();
8814 let events_4 = nodes[0].node.get_and_clear_pending_events();
8815 assert_eq!(events_4.len(), 0);
8816 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8817 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8819 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8820 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8821 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8822 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8826 fn test_error_chans_closed() {
8827 // Test that we properly handle error messages, closing appropriate channels.
8829 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8830 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8831 // we can test various edge cases around it to ensure we don't regress.
8832 let chanmon_cfgs = create_chanmon_cfgs(3);
8833 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8834 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8835 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8837 // Create some initial channels
8838 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8839 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8840 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8842 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8843 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8844 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8846 // Closing a channel from a different peer has no effect
8847 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8848 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8850 // Closing one channel doesn't impact others
8851 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8852 check_added_monitors!(nodes[0], 1);
8853 check_closed_broadcast!(nodes[0], false);
8854 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8855 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8856 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8857 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);
8858 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);
8860 // A null channel ID should close all channels
8861 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8862 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8863 check_added_monitors!(nodes[0], 2);
8864 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8865 let events = nodes[0].node.get_and_clear_pending_msg_events();
8866 assert_eq!(events.len(), 2);
8868 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8869 assert_eq!(msg.contents.flags & 2, 2);
8871 _ => panic!("Unexpected event"),
8874 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8875 assert_eq!(msg.contents.flags & 2, 2);
8877 _ => panic!("Unexpected event"),
8879 // Note that at this point users of a standard PeerHandler will end up calling
8880 // peer_disconnected with no_connection_possible set to false, duplicating the
8881 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8882 // users with their own peer handling logic. We duplicate the call here, however.
8883 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8884 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8886 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8887 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8888 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8892 fn test_invalid_funding_tx() {
8893 // Test that we properly handle invalid funding transactions sent to us from a peer.
8895 // Previously, all other major lightning implementations had failed to properly sanitize
8896 // funding transactions from their counterparties, leading to a multi-implementation critical
8897 // security vulnerability (though we always sanitized properly, we've previously had
8898 // un-released crashes in the sanitization process).
8899 let chanmon_cfgs = create_chanmon_cfgs(2);
8900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8904 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8905 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()));
8906 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()));
8908 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8909 for output in tx.output.iter_mut() {
8910 // Make the confirmed funding transaction have a bogus script_pubkey
8911 output.script_pubkey = bitcoin::Script::new();
8914 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8915 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()));
8916 check_added_monitors!(nodes[1], 1);
8918 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()));
8919 check_added_monitors!(nodes[0], 1);
8921 let events_1 = nodes[0].node.get_and_clear_pending_events();
8922 assert_eq!(events_1.len(), 0);
8924 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8925 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8926 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8928 let expected_err = "funding tx had wrong script/value or output index";
8929 confirm_transaction_at(&nodes[1], &tx, 1);
8930 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8931 check_added_monitors!(nodes[1], 1);
8932 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8933 assert_eq!(events_2.len(), 1);
8934 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8935 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8936 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8937 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8938 } else { panic!(); }
8939 } else { panic!(); }
8940 assert_eq!(nodes[1].node.list_channels().len(), 0);
8943 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8944 // In the first version of the chain::Confirm interface, after a refactor was made to not
8945 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8946 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8947 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8948 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8949 // spending transaction until height N+1 (or greater). This was due to the way
8950 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8951 // spending transaction at the height the input transaction was confirmed at, not whether we
8952 // should broadcast a spending transaction at the current height.
8953 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8954 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8955 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8956 // until we learned about an additional block.
8958 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8959 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8960 let chanmon_cfgs = create_chanmon_cfgs(3);
8961 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8962 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8963 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8964 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8966 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8967 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8968 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8969 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8970 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8972 nodes[1].node.force_close_channel(&channel_id).unwrap();
8973 check_closed_broadcast!(nodes[1], true);
8974 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8975 check_added_monitors!(nodes[1], 1);
8976 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8977 assert_eq!(node_txn.len(), 1);
8979 let conf_height = nodes[1].best_block_info().1;
8980 if !test_height_before_timelock {
8981 connect_blocks(&nodes[1], 24 * 6);
8983 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8984 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8985 if test_height_before_timelock {
8986 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8987 // generate any events or broadcast any transactions
8988 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8989 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8991 // We should broadcast an HTLC transaction spending our funding transaction first
8992 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8993 assert_eq!(spending_txn.len(), 2);
8994 assert_eq!(spending_txn[0], node_txn[0]);
8995 check_spends!(spending_txn[1], node_txn[0]);
8996 // We should also generate a SpendableOutputs event with the to_self output (as its
8998 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8999 assert_eq!(descriptor_spend_txn.len(), 1);
9001 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9002 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9003 // additional block built on top of the current chain.
9004 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9005 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9006 expect_pending_htlcs_forwardable!(nodes[1]);
9007 check_added_monitors!(nodes[1], 1);
9009 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9010 assert!(updates.update_add_htlcs.is_empty());
9011 assert!(updates.update_fulfill_htlcs.is_empty());
9012 assert_eq!(updates.update_fail_htlcs.len(), 1);
9013 assert!(updates.update_fail_malformed_htlcs.is_empty());
9014 assert!(updates.update_fee.is_none());
9015 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9016 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9017 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9022 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9023 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9024 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9028 fn test_forwardable_regen() {
9029 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9030 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9032 // We test it for both payment receipt and payment forwarding.
9034 let chanmon_cfgs = create_chanmon_cfgs(3);
9035 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9036 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9037 let persister: test_utils::TestPersister;
9038 let new_chain_monitor: test_utils::TestChainMonitor;
9039 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9040 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9041 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9042 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9044 // First send a payment to nodes[1]
9045 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9046 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9047 check_added_monitors!(nodes[0], 1);
9049 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9050 assert_eq!(events.len(), 1);
9051 let payment_event = SendEvent::from_event(events.pop().unwrap());
9052 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9053 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9055 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9057 // Next send a payment which is forwarded by nodes[1]
9058 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9059 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9060 check_added_monitors!(nodes[0], 1);
9062 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9063 assert_eq!(events.len(), 1);
9064 let payment_event = SendEvent::from_event(events.pop().unwrap());
9065 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9066 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9068 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9070 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9072 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9073 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9074 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9076 let nodes_1_serialized = nodes[1].node.encode();
9077 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9078 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9079 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9080 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9082 persister = test_utils::TestPersister::new();
9083 let keys_manager = &chanmon_cfgs[1].keys_manager;
9084 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);
9085 nodes[1].chain_monitor = &new_chain_monitor;
9087 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9088 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9089 &mut chan_0_monitor_read, keys_manager).unwrap();
9090 assert!(chan_0_monitor_read.is_empty());
9091 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9092 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9093 &mut chan_1_monitor_read, keys_manager).unwrap();
9094 assert!(chan_1_monitor_read.is_empty());
9096 let mut nodes_1_read = &nodes_1_serialized[..];
9097 let (_, nodes_1_deserialized_tmp) = {
9098 let mut channel_monitors = HashMap::new();
9099 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9100 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9101 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9102 default_config: UserConfig::default(),
9104 fee_estimator: node_cfgs[1].fee_estimator,
9105 chain_monitor: nodes[1].chain_monitor,
9106 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9107 logger: nodes[1].logger,
9111 nodes_1_deserialized = nodes_1_deserialized_tmp;
9112 assert!(nodes_1_read.is_empty());
9114 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9115 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9116 nodes[1].node = &nodes_1_deserialized;
9117 check_added_monitors!(nodes[1], 2);
9119 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9120 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9121 // the commitment state.
9122 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9124 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9126 expect_pending_htlcs_forwardable!(nodes[1]);
9127 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9128 check_added_monitors!(nodes[1], 1);
9130 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9131 assert_eq!(events.len(), 1);
9132 let payment_event = SendEvent::from_event(events.pop().unwrap());
9133 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9134 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9135 expect_pending_htlcs_forwardable!(nodes[2]);
9136 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9138 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9139 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9143 fn test_keysend_payments_to_public_node() {
9144 let chanmon_cfgs = create_chanmon_cfgs(2);
9145 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9146 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9147 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9149 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9150 let network_graph = nodes[0].network_graph;
9151 let payer_pubkey = nodes[0].node.get_our_node_id();
9152 let payee_pubkey = nodes[1].node.get_our_node_id();
9153 let params = RouteParameters {
9154 payee: Payee::for_keysend(payee_pubkey),
9155 final_value_msat: 10000,
9156 final_cltv_expiry_delta: 40,
9158 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9159 let route = find_route(&payer_pubkey, ¶ms, network_graph, None, nodes[0].logger, &scorer).unwrap();
9161 let test_preimage = PaymentPreimage([42; 32]);
9162 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9163 check_added_monitors!(nodes[0], 1);
9164 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9165 assert_eq!(events.len(), 1);
9166 let event = events.pop().unwrap();
9167 let path = vec![&nodes[1]];
9168 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9169 claim_payment(&nodes[0], &path, test_preimage);
9173 fn test_keysend_payments_to_private_node() {
9174 let chanmon_cfgs = create_chanmon_cfgs(2);
9175 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9176 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9177 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9179 let payer_pubkey = nodes[0].node.get_our_node_id();
9180 let payee_pubkey = nodes[1].node.get_our_node_id();
9181 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9182 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9184 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9185 let params = RouteParameters {
9186 payee: Payee::for_keysend(payee_pubkey),
9187 final_value_msat: 10000,
9188 final_cltv_expiry_delta: 40,
9190 let network_graph = nodes[0].network_graph;
9191 let first_hops = nodes[0].node.list_usable_channels();
9192 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9193 let route = find_route(
9194 &payer_pubkey, ¶ms, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9195 nodes[0].logger, &scorer
9198 let test_preimage = PaymentPreimage([42; 32]);
9199 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9200 check_added_monitors!(nodes[0], 1);
9201 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9202 assert_eq!(events.len(), 1);
9203 let event = events.pop().unwrap();
9204 let path = vec![&nodes[1]];
9205 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9206 claim_payment(&nodes[0], &path, test_preimage);
9209 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9210 #[derive(Clone, Copy, PartialEq)]
9211 enum ExposureEvent {
9212 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9214 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9216 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9217 AtUpdateFeeOutbound,
9220 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9221 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9224 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9225 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9226 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9227 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9228 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9229 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9230 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9231 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9233 let chanmon_cfgs = create_chanmon_cfgs(2);
9234 let mut config = test_default_channel_config();
9235 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9236 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9237 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9238 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9240 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9241 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9242 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9243 open_channel.max_accepted_htlcs = 60;
9245 open_channel.dust_limit_satoshis = 546;
9247 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9248 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9249 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9251 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9254 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9255 chan.holder_dust_limit_satoshis = 546;
9259 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9260 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()));
9261 check_added_monitors!(nodes[1], 1);
9263 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()));
9264 check_added_monitors!(nodes[0], 1);
9266 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9267 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9268 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9270 let dust_buffer_feerate = {
9271 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9272 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9273 chan.get_dust_buffer_feerate(None) as u64
9275 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_TIMEOUT_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9276 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9278 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_SUCCESS_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9279 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9281 let dust_htlc_on_counterparty_tx: u64 = 25;
9282 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9285 if dust_outbound_balance {
9286 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9287 // Outbound dust balance: 4372 sats
9288 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9289 for i in 0..dust_outbound_htlc_on_holder_tx {
9290 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9291 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9294 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9295 // Inbound dust balance: 4372 sats
9296 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9297 for _ in 0..dust_inbound_htlc_on_holder_tx {
9298 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9302 if dust_outbound_balance {
9303 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9304 // Outbound dust balance: 5000 sats
9305 for i in 0..dust_htlc_on_counterparty_tx {
9306 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9307 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9310 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9311 // Inbound dust balance: 5000 sats
9312 for _ in 0..dust_htlc_on_counterparty_tx {
9313 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9318 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9319 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9320 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 });
9321 let mut config = UserConfig::default();
9322 // With default dust exposure: 5000 sats
9324 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9325 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9326 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)));
9328 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)));
9330 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9331 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 });
9332 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9333 check_added_monitors!(nodes[1], 1);
9334 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9335 assert_eq!(events.len(), 1);
9336 let payment_event = SendEvent::from_event(events.remove(0));
9337 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9338 // With default dust exposure: 5000 sats
9340 // Outbound dust balance: 6399 sats
9341 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9342 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9343 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);
9345 // Outbound dust balance: 5200 sats
9346 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);
9348 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9349 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9350 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9352 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9353 *feerate_lock = *feerate_lock * 10;
9355 nodes[0].node.timer_tick_occurred();
9356 check_added_monitors!(nodes[0], 1);
9357 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);
9360 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9361 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9362 added_monitors.clear();
9366 fn test_max_dust_htlc_exposure() {
9367 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9368 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9369 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9370 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9371 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9372 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9373 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9374 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9375 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9376 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9377 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9378 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);