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::{KeysInterface, BaseSign};
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, 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;
26 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
27 use routing::network_graph::RoutingFees;
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
39 use bitcoin::hash_types::{Txid, BlockHash};
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::script::Builder;
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
46 use bitcoin::hashes::sha256::Hash as Sha256;
47 use bitcoin::hashes::Hash;
49 use bitcoin::secp256k1::{Secp256k1, Message};
50 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use sync::{Arc, Mutex};
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
64 fn test_insane_channel_opens() {
65 // Stand up a network of 2 nodes
66 let chanmon_cfgs = create_chanmon_cfgs(2);
67 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
68 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
69 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
71 // Instantiate channel parameters where we push the maximum msats given our
73 let channel_value_sat = 31337; // same as funding satoshis
74 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
75 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
77 // Have node0 initiate a channel to node1 with aforementioned parameters
78 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
80 // Extract the channel open message from node0 to node1
81 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
83 // Test helper that asserts we get the correct error string given a mutator
84 // that supposedly makes the channel open message insane
85 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
86 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
87 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
88 assert_eq!(msg_events.len(), 1);
89 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
90 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
92 &ErrorAction::SendErrorMessage { .. } => {
93 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
95 _ => panic!("unexpected event!"),
97 } else { assert!(false); }
100 use ln::channel::MAX_FUNDING_SATOSHIS;
101 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103 // Test all mutations that would make the channel open message insane
104 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 });
106 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
108 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 });
110 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
112 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 });
114 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 });
116 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 });
118 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
120 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
124 fn test_async_inbound_update_fee() {
125 let chanmon_cfgs = create_chanmon_cfgs(2);
126 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
130 let logger = test_utils::TestLogger::new();
133 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
137 // send (1) commitment_signed -.
138 // <- update_add_htlc/commitment_signed
139 // send (2) RAA (awaiting remote revoke) -.
140 // (1) commitment_signed is delivered ->
141 // .- send (3) RAA (awaiting remote revoke)
142 // (2) RAA is delivered ->
143 // .- send (4) commitment_signed
144 // <- (3) RAA is delivered
145 // send (5) commitment_signed -.
146 // <- (4) commitment_signed is delivered
148 // (5) commitment_signed is delivered ->
150 // (6) RAA is delivered ->
152 // First nodes[0] generates an update_fee
154 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
157 nodes[0].node.timer_tick_occurred();
158 check_added_monitors!(nodes[0], 1);
160 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
161 assert_eq!(events_0.len(), 1);
162 let (update_msg, commitment_signed) = match events_0[0] { // (1)
163 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
164 (update_fee.as_ref(), commitment_signed)
166 _ => panic!("Unexpected event"),
169 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
171 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
172 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
173 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
174 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
175 check_added_monitors!(nodes[1], 1);
177 let payment_event = {
178 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
179 assert_eq!(events_1.len(), 1);
180 SendEvent::from_event(events_1.remove(0))
182 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
183 assert_eq!(payment_event.msgs.len(), 1);
185 // ...now when the messages get delivered everyone should be happy
186 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
187 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
188 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
189 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
190 check_added_monitors!(nodes[0], 1);
192 // deliver(1), generate (3):
193 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
194 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
195 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
196 check_added_monitors!(nodes[1], 1);
198 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
199 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
200 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
202 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
203 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
204 assert!(bs_update.update_fee.is_none()); // (4)
205 check_added_monitors!(nodes[1], 1);
207 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
208 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
209 assert!(as_update.update_add_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
211 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
212 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
213 assert!(as_update.update_fee.is_none()); // (5)
214 check_added_monitors!(nodes[0], 1);
216 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
217 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
218 // only (6) so get_event_msg's assert(len == 1) passes
219 check_added_monitors!(nodes[0], 1);
221 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
222 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
223 check_added_monitors!(nodes[1], 1);
225 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
226 check_added_monitors!(nodes[0], 1);
228 let events_2 = nodes[0].node.get_and_clear_pending_events();
229 assert_eq!(events_2.len(), 1);
231 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
232 _ => panic!("Unexpected event"),
235 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
236 check_added_monitors!(nodes[1], 1);
240 fn test_update_fee_unordered_raa() {
241 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
242 // crash in an earlier version of the update_fee patch)
243 let chanmon_cfgs = create_chanmon_cfgs(2);
244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
246 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
247 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
248 let logger = test_utils::TestLogger::new();
251 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
253 // First nodes[0] generates an update_fee
255 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
258 nodes[0].node.timer_tick_occurred();
259 check_added_monitors!(nodes[0], 1);
261 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
262 assert_eq!(events_0.len(), 1);
263 let update_msg = match events_0[0] { // (1)
264 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
267 _ => panic!("Unexpected event"),
270 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
272 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
273 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
274 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
275 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
276 check_added_monitors!(nodes[1], 1);
278 let payment_event = {
279 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
280 assert_eq!(events_1.len(), 1);
281 SendEvent::from_event(events_1.remove(0))
283 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
284 assert_eq!(payment_event.msgs.len(), 1);
286 // ...now when the messages get delivered everyone should be happy
287 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
288 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
289 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
290 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
291 check_added_monitors!(nodes[0], 1);
293 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
294 check_added_monitors!(nodes[1], 1);
296 // We can't continue, sadly, because our (1) now has a bogus signature
300 fn test_multi_flight_update_fee() {
301 let chanmon_cfgs = create_chanmon_cfgs(2);
302 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
303 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
304 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
305 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
308 // update_fee/commitment_signed ->
309 // .- send (1) RAA and (2) commitment_signed
310 // update_fee (never committed) ->
312 // We have to manually generate the above update_fee, it is allowed by the protocol but we
313 // don't track which updates correspond to which revoke_and_ack responses so we're in
314 // AwaitingRAA mode and will not generate the update_fee yet.
315 // <- (1) RAA delivered
316 // (3) is generated and send (4) CS -.
317 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
318 // know the per_commitment_point to use for it.
319 // <- (2) commitment_signed delivered
321 // B should send no response here
322 // (4) commitment_signed delivered ->
323 // <- RAA/commitment_signed delivered
326 // First nodes[0] generates an update_fee
329 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
330 initial_feerate = *feerate_lock;
331 *feerate_lock = initial_feerate + 20;
333 nodes[0].node.timer_tick_occurred();
334 check_added_monitors!(nodes[0], 1);
336 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
337 assert_eq!(events_0.len(), 1);
338 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
339 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
340 (update_fee.as_ref().unwrap(), commitment_signed)
342 _ => panic!("Unexpected event"),
345 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
346 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
347 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
348 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
349 check_added_monitors!(nodes[1], 1);
351 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
354 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
355 *feerate_lock = initial_feerate + 40;
357 nodes[0].node.timer_tick_occurred();
358 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
359 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
361 // Create the (3) update_fee message that nodes[0] will generate before it does...
362 let mut update_msg_2 = msgs::UpdateFee {
363 channel_id: update_msg_1.channel_id.clone(),
364 feerate_per_kw: (initial_feerate + 30) as u32,
367 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
369 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
371 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
373 // Deliver (1), generating (3) and (4)
374 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
375 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
376 check_added_monitors!(nodes[0], 1);
377 assert!(as_second_update.update_add_htlcs.is_empty());
378 assert!(as_second_update.update_fulfill_htlcs.is_empty());
379 assert!(as_second_update.update_fail_htlcs.is_empty());
380 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
381 // Check that the update_fee newly generated matches what we delivered:
382 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
383 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
385 // Deliver (2) commitment_signed
386 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
387 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
388 check_added_monitors!(nodes[0], 1);
389 // No commitment_signed so get_event_msg's assert(len == 1) passes
391 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
392 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
393 check_added_monitors!(nodes[1], 1);
396 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
397 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
398 check_added_monitors!(nodes[1], 1);
400 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
401 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
402 check_added_monitors!(nodes[0], 1);
404 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
405 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
406 // No commitment_signed so get_event_msg's assert(len == 1) passes
407 check_added_monitors!(nodes[0], 1);
409 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
410 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
411 check_added_monitors!(nodes[1], 1);
414 fn do_test_1_conf_open(connect_style: ConnectStyle) {
415 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
416 // tests that we properly send one in that case.
417 let mut alice_config = UserConfig::default();
418 alice_config.own_channel_config.minimum_depth = 1;
419 alice_config.channel_options.announced_channel = true;
420 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
421 let mut bob_config = UserConfig::default();
422 bob_config.own_channel_config.minimum_depth = 1;
423 bob_config.channel_options.announced_channel = true;
424 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
425 let chanmon_cfgs = create_chanmon_cfgs(2);
426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
428 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
429 *nodes[0].connect_style.borrow_mut() = connect_style;
431 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
432 mine_transaction(&nodes[1], &tx);
433 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()));
435 mine_transaction(&nodes[0], &tx);
436 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
437 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
440 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
441 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
442 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
446 fn test_1_conf_open() {
447 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
448 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
449 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
452 fn do_test_sanity_on_in_flight_opens(steps: u8) {
453 // Previously, we had issues deserializing channels when we hadn't connected the first block
454 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
455 // serialization round-trips and simply do steps towards opening a channel and then drop the
458 let chanmon_cfgs = create_chanmon_cfgs(2);
459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
460 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
461 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
463 if steps & 0b1000_0000 != 0{
465 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
468 connect_block(&nodes[0], &block);
469 connect_block(&nodes[1], &block);
472 if steps & 0x0f == 0 { return; }
473 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
474 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
476 if steps & 0x0f == 1 { return; }
477 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
478 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
480 if steps & 0x0f == 2 { return; }
481 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
483 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
485 if steps & 0x0f == 3 { return; }
486 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
487 check_added_monitors!(nodes[0], 0);
488 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
490 if steps & 0x0f == 4 { return; }
491 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
493 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
494 assert_eq!(added_monitors.len(), 1);
495 assert_eq!(added_monitors[0].0, funding_output);
496 added_monitors.clear();
498 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
500 if steps & 0x0f == 5 { return; }
501 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
503 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
504 assert_eq!(added_monitors.len(), 1);
505 assert_eq!(added_monitors[0].0, funding_output);
506 added_monitors.clear();
509 let events_4 = nodes[0].node.get_and_clear_pending_events();
510 assert_eq!(events_4.len(), 0);
512 if steps & 0x0f == 6 { return; }
513 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
515 if steps & 0x0f == 7 { return; }
516 confirm_transaction_at(&nodes[0], &tx, 2);
517 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
518 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
522 fn test_sanity_on_in_flight_opens() {
523 do_test_sanity_on_in_flight_opens(0);
524 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
525 do_test_sanity_on_in_flight_opens(1);
526 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
527 do_test_sanity_on_in_flight_opens(2);
528 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
529 do_test_sanity_on_in_flight_opens(3);
530 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
531 do_test_sanity_on_in_flight_opens(4);
532 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
533 do_test_sanity_on_in_flight_opens(5);
534 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
535 do_test_sanity_on_in_flight_opens(6);
536 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
537 do_test_sanity_on_in_flight_opens(7);
538 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
539 do_test_sanity_on_in_flight_opens(8);
540 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
544 fn test_update_fee_vanilla() {
545 let chanmon_cfgs = create_chanmon_cfgs(2);
546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
549 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
552 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
555 nodes[0].node.timer_tick_occurred();
556 check_added_monitors!(nodes[0], 1);
558 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
559 assert_eq!(events_0.len(), 1);
560 let (update_msg, commitment_signed) = match events_0[0] {
561 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 } } => {
562 (update_fee.as_ref(), commitment_signed)
564 _ => panic!("Unexpected event"),
566 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
568 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
569 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
570 check_added_monitors!(nodes[1], 1);
572 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
573 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
574 check_added_monitors!(nodes[0], 1);
576 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
577 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
578 // No commitment_signed so get_event_msg's assert(len == 1) passes
579 check_added_monitors!(nodes[0], 1);
581 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
582 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
583 check_added_monitors!(nodes[1], 1);
587 fn test_update_fee_that_funder_cannot_afford() {
588 let chanmon_cfgs = create_chanmon_cfgs(2);
589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
592 let channel_value = 1888;
593 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
594 let channel_id = chan.2;
598 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
599 *feerate_lock = feerate;
601 nodes[0].node.timer_tick_occurred();
602 check_added_monitors!(nodes[0], 1);
603 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
605 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
607 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
609 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
610 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
612 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
614 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
615 let num_htlcs = commitment_tx.output.len() - 2;
616 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
617 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
618 actual_fee = channel_value - actual_fee;
619 assert_eq!(total_fee, actual_fee);
622 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
623 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
625 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
626 *feerate_lock = feerate + 2;
628 nodes[0].node.timer_tick_occurred();
629 check_added_monitors!(nodes[0], 1);
631 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
633 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
635 //While producing the commitment_signed response after handling a received update_fee request the
636 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
637 //Should produce and error.
638 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
639 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
640 check_added_monitors!(nodes[1], 1);
641 check_closed_broadcast!(nodes[1], true);
645 fn test_update_fee_with_fundee_update_add_htlc() {
646 let chanmon_cfgs = create_chanmon_cfgs(2);
647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
650 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
651 let logger = test_utils::TestLogger::new();
654 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
663 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
664 assert_eq!(events_0.len(), 1);
665 let (update_msg, commitment_signed) = match events_0[0] {
666 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 } } => {
667 (update_fee.as_ref(), commitment_signed)
669 _ => panic!("Unexpected event"),
671 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
672 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
673 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
674 check_added_monitors!(nodes[1], 1);
676 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
677 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
678 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
680 // nothing happens since node[1] is in AwaitingRemoteRevoke
681 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
683 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
684 assert_eq!(added_monitors.len(), 0);
685 added_monitors.clear();
687 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
688 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
689 // node[1] has nothing to do
691 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
692 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
693 check_added_monitors!(nodes[0], 1);
695 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
696 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
697 // No commitment_signed so get_event_msg's assert(len == 1) passes
698 check_added_monitors!(nodes[0], 1);
699 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
700 check_added_monitors!(nodes[1], 1);
701 // AwaitingRemoteRevoke ends here
703 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
704 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
705 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
706 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
707 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
708 assert_eq!(commitment_update.update_fee.is_none(), true);
710 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
711 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
712 check_added_monitors!(nodes[0], 1);
713 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
715 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
716 check_added_monitors!(nodes[1], 1);
717 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
719 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
720 check_added_monitors!(nodes[1], 1);
721 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
722 // No commitment_signed so get_event_msg's assert(len == 1) passes
724 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
725 check_added_monitors!(nodes[0], 1);
726 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
728 expect_pending_htlcs_forwardable!(nodes[0]);
730 let events = nodes[0].node.get_and_clear_pending_events();
731 assert_eq!(events.len(), 1);
733 Event::PaymentReceived { .. } => { },
734 _ => panic!("Unexpected event"),
737 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
739 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
740 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
741 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
745 fn test_update_fee() {
746 let chanmon_cfgs = create_chanmon_cfgs(2);
747 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
748 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
749 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
750 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
751 let channel_id = chan.2;
754 // (1) update_fee/commitment_signed ->
755 // <- (2) revoke_and_ack
756 // .- send (3) commitment_signed
757 // (4) update_fee/commitment_signed ->
758 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
759 // <- (3) commitment_signed delivered
760 // send (6) revoke_and_ack -.
761 // <- (5) deliver revoke_and_ack
762 // (6) deliver revoke_and_ack ->
763 // .- send (7) commitment_signed in response to (4)
764 // <- (7) deliver commitment_signed
767 // Create and deliver (1)...
770 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
771 feerate = *feerate_lock;
772 *feerate_lock = feerate + 20;
774 nodes[0].node.timer_tick_occurred();
775 check_added_monitors!(nodes[0], 1);
777 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
778 assert_eq!(events_0.len(), 1);
779 let (update_msg, commitment_signed) = match events_0[0] {
780 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 } } => {
781 (update_fee.as_ref(), commitment_signed)
783 _ => panic!("Unexpected event"),
785 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
787 // Generate (2) and (3):
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
793 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
794 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
795 check_added_monitors!(nodes[0], 1);
797 // Create and deliver (4)...
799 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
800 *feerate_lock = feerate + 30;
802 nodes[0].node.timer_tick_occurred();
803 check_added_monitors!(nodes[0], 1);
804 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
805 assert_eq!(events_0.len(), 1);
806 let (update_msg, commitment_signed) = match events_0[0] {
807 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 } } => {
808 (update_fee.as_ref(), commitment_signed)
810 _ => panic!("Unexpected event"),
813 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
814 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
815 check_added_monitors!(nodes[1], 1);
817 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
818 // No commitment_signed so get_event_msg's assert(len == 1) passes
820 // Handle (3), creating (6):
821 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
822 check_added_monitors!(nodes[0], 1);
823 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
824 // No commitment_signed so get_event_msg's assert(len == 1) passes
827 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
828 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
829 check_added_monitors!(nodes[0], 1);
831 // Deliver (6), creating (7):
832 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
833 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
834 assert!(commitment_update.update_add_htlcs.is_empty());
835 assert!(commitment_update.update_fulfill_htlcs.is_empty());
836 assert!(commitment_update.update_fail_htlcs.is_empty());
837 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
838 assert!(commitment_update.update_fee.is_none());
839 check_added_monitors!(nodes[1], 1);
842 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
843 check_added_monitors!(nodes[0], 1);
844 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
845 // No commitment_signed so get_event_msg's assert(len == 1) passes
847 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
848 check_added_monitors!(nodes[1], 1);
849 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
851 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
852 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
853 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 fn fake_network_test() {
858 // Simple test which builds a network of ChannelManagers, connects them to each other, and
859 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
860 let chanmon_cfgs = create_chanmon_cfgs(4);
861 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
862 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
863 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
865 // Create some initial channels
866 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
867 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
868 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
870 // Rebalance the network a bit by relaying one payment through all the channels...
871 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
872 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
873 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
874 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
876 // Send some more payments
877 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
878 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
879 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
881 // Test failure packets
882 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
883 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
885 // Add a new channel that skips 3
886 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
888 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
889 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
890 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
891 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
892 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
893 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
894 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
896 // Do some rebalance loop payments, simultaneously
897 let mut hops = Vec::with_capacity(3);
899 pubkey: nodes[2].node.get_our_node_id(),
900 node_features: NodeFeatures::empty(),
901 short_channel_id: chan_2.0.contents.short_channel_id,
902 channel_features: ChannelFeatures::empty(),
904 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
907 pubkey: nodes[3].node.get_our_node_id(),
908 node_features: NodeFeatures::empty(),
909 short_channel_id: chan_3.0.contents.short_channel_id,
910 channel_features: ChannelFeatures::empty(),
912 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
915 pubkey: nodes[1].node.get_our_node_id(),
916 node_features: NodeFeatures::known(),
917 short_channel_id: chan_4.0.contents.short_channel_id,
918 channel_features: ChannelFeatures::known(),
920 cltv_expiry_delta: TEST_FINAL_CLTV,
922 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;
923 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;
924 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
926 let mut hops = Vec::with_capacity(3);
928 pubkey: nodes[3].node.get_our_node_id(),
929 node_features: NodeFeatures::empty(),
930 short_channel_id: chan_4.0.contents.short_channel_id,
931 channel_features: ChannelFeatures::empty(),
933 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
936 pubkey: nodes[2].node.get_our_node_id(),
937 node_features: NodeFeatures::empty(),
938 short_channel_id: chan_3.0.contents.short_channel_id,
939 channel_features: ChannelFeatures::empty(),
941 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
944 pubkey: nodes[1].node.get_our_node_id(),
945 node_features: NodeFeatures::known(),
946 short_channel_id: chan_2.0.contents.short_channel_id,
947 channel_features: ChannelFeatures::known(),
949 cltv_expiry_delta: TEST_FINAL_CLTV,
951 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;
952 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;
953 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
955 // Claim the rebalances...
956 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
957 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
959 // Add a duplicate new channel from 2 to 4
960 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
962 // Send some payments across both channels
963 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
964 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
965 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
968 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
969 let events = nodes[0].node.get_and_clear_pending_msg_events();
970 assert_eq!(events.len(), 0);
971 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);
973 //TODO: Test that routes work again here as we've been notified that the channel is full
975 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
976 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
977 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
979 // Close down the channels...
980 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
981 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
982 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
983 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
984 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
988 fn holding_cell_htlc_counting() {
989 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
990 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
991 // commitment dance rounds.
992 let chanmon_cfgs = create_chanmon_cfgs(3);
993 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
994 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
995 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
996 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
997 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
998 let logger = test_utils::TestLogger::new();
1000 let mut payments = Vec::new();
1001 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1002 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
1003 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1004 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1005 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1006 payments.push((payment_preimage, payment_hash));
1008 check_added_monitors!(nodes[1], 1);
1010 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1011 assert_eq!(events.len(), 1);
1012 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1013 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1015 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1016 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1018 let (_, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[2]);
1020 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1021 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1022 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1023 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1024 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1025 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1028 // This should also be true if we try to forward a payment.
1029 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[2]);
1031 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1032 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1033 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1034 check_added_monitors!(nodes[0], 1);
1037 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1038 assert_eq!(events.len(), 1);
1039 let payment_event = SendEvent::from_event(events.pop().unwrap());
1040 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1042 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1043 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1044 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1045 // fails), the second will process the resulting failure and fail the HTLC backward.
1046 expect_pending_htlcs_forwardable!(nodes[1]);
1047 expect_pending_htlcs_forwardable!(nodes[1]);
1048 check_added_monitors!(nodes[1], 1);
1050 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1051 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1052 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1054 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, false);
1055 expect_payment_failed!(nodes[0], payment_hash_2, false);
1057 // Now forward all the pending HTLCs and claim them back
1058 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1059 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1060 check_added_monitors!(nodes[2], 1);
1062 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1063 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1064 check_added_monitors!(nodes[1], 1);
1065 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1067 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1068 check_added_monitors!(nodes[1], 1);
1069 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1071 for ref update in as_updates.update_add_htlcs.iter() {
1072 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1074 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1075 check_added_monitors!(nodes[2], 1);
1076 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1077 check_added_monitors!(nodes[2], 1);
1078 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1080 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1081 check_added_monitors!(nodes[1], 1);
1082 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1083 check_added_monitors!(nodes[1], 1);
1084 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1086 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1087 check_added_monitors!(nodes[2], 1);
1089 expect_pending_htlcs_forwardable!(nodes[2]);
1091 let events = nodes[2].node.get_and_clear_pending_events();
1092 assert_eq!(events.len(), payments.len());
1093 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1095 &Event::PaymentReceived { ref payment_hash, .. } => {
1096 assert_eq!(*payment_hash, *hash);
1098 _ => panic!("Unexpected event"),
1102 for (preimage, _) in payments.drain(..) {
1103 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1106 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1110 fn duplicate_htlc_test() {
1111 // Test that we accept duplicate payment_hash HTLCs across the network and that
1112 // claiming/failing them are all separate and don't affect each other
1113 let chanmon_cfgs = create_chanmon_cfgs(6);
1114 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1115 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1116 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1118 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1119 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1120 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1121 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1122 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1123 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1125 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1127 *nodes[0].network_payment_count.borrow_mut() -= 1;
1128 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1130 *nodes[0].network_payment_count.borrow_mut() -= 1;
1131 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1133 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1134 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1135 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1139 fn test_duplicate_htlc_different_direction_onchain() {
1140 // Test that ChannelMonitor doesn't generate 2 preimage txn
1141 // when we have 2 HTLCs with same preimage that go across a node
1142 // in opposite directions, even with the same payment secret.
1143 let chanmon_cfgs = create_chanmon_cfgs(2);
1144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1146 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1148 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1149 let logger = test_utils::TestLogger::new();
1152 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1154 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1156 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1157 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1158 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1159 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1161 // Provide preimage to node 0 by claiming payment
1162 nodes[0].node.claim_funds(payment_preimage);
1163 check_added_monitors!(nodes[0], 1);
1165 // Broadcast node 1 commitment txn
1166 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1168 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1169 let mut has_both_htlcs = 0; // check htlcs match ones committed
1170 for outp in remote_txn[0].output.iter() {
1171 if outp.value == 800_000 / 1000 {
1172 has_both_htlcs += 1;
1173 } else if outp.value == 900_000 / 1000 {
1174 has_both_htlcs += 1;
1177 assert_eq!(has_both_htlcs, 2);
1179 mine_transaction(&nodes[0], &remote_txn[0]);
1180 check_added_monitors!(nodes[0], 1);
1181 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1183 // Check we only broadcast 1 timeout tx
1184 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1185 assert_eq!(claim_txn.len(), 8);
1186 assert_eq!(claim_txn[1], claim_txn[4]);
1187 assert_eq!(claim_txn[2], claim_txn[5]);
1188 check_spends!(claim_txn[1], chan_1.3);
1189 check_spends!(claim_txn[2], claim_txn[1]);
1190 check_spends!(claim_txn[7], claim_txn[1]);
1192 assert_eq!(claim_txn[0].input.len(), 1);
1193 assert_eq!(claim_txn[3].input.len(), 1);
1194 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1196 assert_eq!(claim_txn[0].input.len(), 1);
1197 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1198 check_spends!(claim_txn[0], remote_txn[0]);
1199 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1200 assert_eq!(claim_txn[6].input.len(), 1);
1201 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1202 check_spends!(claim_txn[6], remote_txn[0]);
1203 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1205 let events = nodes[0].node.get_and_clear_pending_msg_events();
1206 assert_eq!(events.len(), 3);
1209 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1210 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1211 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1212 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1214 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, .. } } => {
1215 assert!(update_add_htlcs.is_empty());
1216 assert!(update_fail_htlcs.is_empty());
1217 assert_eq!(update_fulfill_htlcs.len(), 1);
1218 assert!(update_fail_malformed_htlcs.is_empty());
1219 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1221 _ => panic!("Unexpected event"),
1227 fn test_basic_channel_reserve() {
1228 let chanmon_cfgs = create_chanmon_cfgs(2);
1229 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1230 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1231 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1232 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1233 let logger = test_utils::TestLogger::new();
1235 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1236 let channel_reserve = chan_stat.channel_reserve_msat;
1238 // The 2* and +1 are for the fee spike reserve.
1239 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
1240 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1241 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1242 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1243 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1244 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1246 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1248 &APIError::ChannelUnavailable{ref err} =>
1249 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1250 _ => panic!("Unexpected error variant"),
1253 _ => panic!("Unexpected error variant"),
1255 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1256 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);
1258 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1262 fn test_fee_spike_violation_fails_htlc() {
1263 let chanmon_cfgs = create_chanmon_cfgs(2);
1264 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1265 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1266 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1267 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1269 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1270 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1271 let secp_ctx = Secp256k1::new();
1272 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1274 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1276 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1277 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1278 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1279 let msg = msgs::UpdateAddHTLC {
1282 amount_msat: htlc_msat,
1283 payment_hash: payment_hash,
1284 cltv_expiry: htlc_cltv,
1285 onion_routing_packet: onion_packet,
1288 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1290 // Now manually create the commitment_signed message corresponding to the update_add
1291 // nodes[0] just sent. In the code for construction of this message, "local" refers
1292 // to the sender of the message, and "remote" refers to the receiver.
1294 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1296 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1298 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1299 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1300 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1301 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1302 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1303 let chan_signer = local_chan.get_signer();
1304 // Make the signer believe we validated another commitment, so we can release the secret
1305 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1307 let pubkeys = chan_signer.pubkeys();
1308 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1309 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1310 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1312 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1313 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1314 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1315 let chan_signer = remote_chan.get_signer();
1316 let pubkeys = chan_signer.pubkeys();
1317 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1318 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1321 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1322 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1323 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1325 // Build the remote commitment transaction so we can sign it, and then later use the
1326 // signature for the commitment_signed message.
1327 let local_chan_balance = 1313;
1329 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1331 amount_msat: 3460001,
1332 cltv_expiry: htlc_cltv,
1334 transaction_output_index: Some(1),
1337 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1340 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1341 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1342 let local_chan_signer = local_chan.get_signer();
1343 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1347 commit_tx_keys.clone(),
1349 &mut vec![(accepted_htlc_info, ())],
1350 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1352 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1355 let commit_signed_msg = msgs::CommitmentSigned {
1358 htlc_signatures: res.1
1361 // Send the commitment_signed message to the nodes[1].
1362 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1363 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1365 // Send the RAA to nodes[1].
1366 let raa_msg = msgs::RevokeAndACK {
1368 per_commitment_secret: local_secret,
1369 next_per_commitment_point: next_local_point
1371 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1373 let events = nodes[1].node.get_and_clear_pending_msg_events();
1374 assert_eq!(events.len(), 1);
1375 // Make sure the HTLC failed in the way we expect.
1377 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1378 assert_eq!(update_fail_htlcs.len(), 1);
1379 update_fail_htlcs[0].clone()
1381 _ => panic!("Unexpected event"),
1383 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1384 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1386 check_added_monitors!(nodes[1], 2);
1390 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1391 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1392 // Set the fee rate for the channel very high, to the point where the fundee
1393 // sending any above-dust amount would result in a channel reserve violation.
1394 // In this test we check that we would be prevented from sending an HTLC in
1396 let feerate_per_kw = 253;
1397 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1398 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1401 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1403 let mut push_amt = 100_000_000;
1404 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1405 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1407 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1409 // Sending exactly enough to hit the reserve amount should be accepted
1410 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1412 // However one more HTLC should be significantly over the reserve amount and fail.
1413 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1414 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1415 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1416 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1417 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);
1421 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1422 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1423 // Set the fee rate for the channel very high, to the point where the funder
1424 // receiving 1 update_add_htlc would result in them closing the channel due
1425 // to channel reserve violation. This close could also happen if the fee went
1426 // up a more realistic amount, but many HTLCs were outstanding at the time of
1427 // the update_add_htlc.
1428 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1429 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1432 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1433 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1435 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1436 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1437 let secp_ctx = Secp256k1::new();
1438 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1439 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1440 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1441 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1442 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1443 let msg = msgs::UpdateAddHTLC {
1446 amount_msat: htlc_msat + 1,
1447 payment_hash: payment_hash,
1448 cltv_expiry: htlc_cltv,
1449 onion_routing_packet: onion_packet,
1452 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1453 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1454 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);
1455 assert_eq!(nodes[0].node.list_channels().len(), 0);
1456 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1457 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1458 check_added_monitors!(nodes[0], 1);
1462 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1463 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1464 // calculating our commitment transaction fee (this was previously broken).
1465 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1466 let feerate_per_kw = 253;
1467 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1468 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1474 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1475 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1476 // transaction fee with 0 HTLCs (183 sats)).
1477 let mut push_amt = 100_000_000;
1478 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1479 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1480 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1482 let dust_amt = crate::ln::channel::MIN_DUST_LIMIT_SATOSHIS * 1000
1483 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1484 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1485 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1486 // commitment transaction fee.
1487 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1489 // One more than the dust amt should fail, however.
1490 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1491 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1492 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1496 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1497 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1498 // calculating our counterparty's commitment transaction fee (this was previously broken).
1499 let chanmon_cfgs = create_chanmon_cfgs(2);
1500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1502 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1503 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1505 let payment_amt = 46000; // Dust amount
1506 // In the previous code, these first four payments would succeed.
1507 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1508 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1509 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1510 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1512 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1513 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1514 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1515 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1516 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1517 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1519 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1520 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1521 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1522 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1526 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1527 let chanmon_cfgs = create_chanmon_cfgs(3);
1528 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1529 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1530 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1531 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1532 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1535 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1536 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1537 let feerate = get_feerate!(nodes[0], chan.2);
1539 // Add a 2* and +1 for the fee spike reserve.
1540 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1541 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;
1542 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1544 // Add a pending HTLC.
1545 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1546 let payment_event_1 = {
1547 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1548 check_added_monitors!(nodes[0], 1);
1550 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1551 assert_eq!(events.len(), 1);
1552 SendEvent::from_event(events.remove(0))
1554 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1556 // Attempt to trigger a channel reserve violation --> payment failure.
1557 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1558 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;
1559 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1560 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1562 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1563 let secp_ctx = Secp256k1::new();
1564 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1565 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1566 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1567 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1568 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1569 let msg = msgs::UpdateAddHTLC {
1572 amount_msat: htlc_msat + 1,
1573 payment_hash: our_payment_hash_1,
1574 cltv_expiry: htlc_cltv,
1575 onion_routing_packet: onion_packet,
1578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1579 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1580 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1581 assert_eq!(nodes[1].node.list_channels().len(), 1);
1582 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1583 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1584 check_added_monitors!(nodes[1], 1);
1588 fn test_inbound_outbound_capacity_is_not_zero() {
1589 let chanmon_cfgs = create_chanmon_cfgs(2);
1590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1592 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1593 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1594 let channels0 = node_chanmgrs[0].list_channels();
1595 let channels1 = node_chanmgrs[1].list_channels();
1596 assert_eq!(channels0.len(), 1);
1597 assert_eq!(channels1.len(), 1);
1599 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1600 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1601 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1603 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1604 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1607 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1608 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1612 fn test_channel_reserve_holding_cell_htlcs() {
1613 let chanmon_cfgs = create_chanmon_cfgs(3);
1614 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1615 // When this test was written, the default base fee floated based on the HTLC count.
1616 // It is now fixed, so we simply set the fee to the expected value here.
1617 let mut config = test_default_channel_config();
1618 config.channel_options.forwarding_fee_base_msat = 239;
1619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1620 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1621 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1622 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1624 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1625 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1627 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1628 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1630 macro_rules! expect_forward {
1632 let mut events = $node.node.get_and_clear_pending_msg_events();
1633 assert_eq!(events.len(), 1);
1634 check_added_monitors!($node, 1);
1635 let payment_event = SendEvent::from_event(events.remove(0));
1640 let feemsat = 239; // set above
1641 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1642 let feerate = get_feerate!(nodes[0], chan_1.2);
1644 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1646 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1648 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1649 route.paths[0].last_mut().unwrap().fee_msat += 1;
1650 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1651 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1652 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)));
1653 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1654 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);
1657 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1658 // nodes[0]'s wealth
1660 let amt_msat = recv_value_0 + total_fee_msat;
1661 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1662 // Also, ensure that each payment has enough to be over the dust limit to
1663 // ensure it'll be included in each commit tx fee calculation.
1664 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1665 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1666 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1669 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1671 let (stat01_, stat11_, stat12_, stat22_) = (
1672 get_channel_value_stat!(nodes[0], chan_1.2),
1673 get_channel_value_stat!(nodes[1], chan_1.2),
1674 get_channel_value_stat!(nodes[1], chan_2.2),
1675 get_channel_value_stat!(nodes[2], chan_2.2),
1678 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1679 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1680 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1681 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1682 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1685 // adding pending output.
1686 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1687 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1688 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1689 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1690 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1691 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1692 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1693 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1694 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1696 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1697 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1698 let amt_msat_1 = recv_value_1 + total_fee_msat;
1700 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);
1701 let payment_event_1 = {
1702 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1703 check_added_monitors!(nodes[0], 1);
1705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706 assert_eq!(events.len(), 1);
1707 SendEvent::from_event(events.remove(0))
1709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1711 // channel reserve test with htlc pending output > 0
1712 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1714 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1715 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1716 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1717 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1720 // split the rest to test holding cell
1721 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1722 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1723 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1724 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1726 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1727 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);
1730 // now see if they go through on both sides
1731 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);
1732 // but this will stuck in the holding cell
1733 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1734 check_added_monitors!(nodes[0], 0);
1735 let events = nodes[0].node.get_and_clear_pending_events();
1736 assert_eq!(events.len(), 0);
1738 // test with outbound holding cell amount > 0
1740 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1741 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1742 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1743 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1744 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);
1747 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);
1748 // this will also stuck in the holding cell
1749 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1750 check_added_monitors!(nodes[0], 0);
1751 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1752 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1754 // flush the pending htlc
1755 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1756 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1757 check_added_monitors!(nodes[1], 1);
1759 // the pending htlc should be promoted to committed
1760 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1761 check_added_monitors!(nodes[0], 1);
1762 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1764 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1765 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1766 // No commitment_signed so get_event_msg's assert(len == 1) passes
1767 check_added_monitors!(nodes[0], 1);
1769 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771 check_added_monitors!(nodes[1], 1);
1773 expect_pending_htlcs_forwardable!(nodes[1]);
1775 let ref payment_event_11 = expect_forward!(nodes[1]);
1776 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1777 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1779 expect_pending_htlcs_forwardable!(nodes[2]);
1780 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1782 // flush the htlcs in the holding cell
1783 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1785 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1786 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1787 expect_pending_htlcs_forwardable!(nodes[1]);
1789 let ref payment_event_3 = expect_forward!(nodes[1]);
1790 assert_eq!(payment_event_3.msgs.len(), 2);
1791 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1792 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1794 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1795 expect_pending_htlcs_forwardable!(nodes[2]);
1797 let events = nodes[2].node.get_and_clear_pending_events();
1798 assert_eq!(events.len(), 2);
1800 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1801 assert_eq!(our_payment_hash_21, *payment_hash);
1802 assert_eq!(recv_value_21, amt);
1804 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1805 assert!(payment_preimage.is_none());
1806 assert_eq!(our_payment_secret_21, *payment_secret);
1808 _ => panic!("expected PaymentPurpose::InvoicePayment")
1811 _ => panic!("Unexpected event"),
1814 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1815 assert_eq!(our_payment_hash_22, *payment_hash);
1816 assert_eq!(recv_value_22, amt);
1818 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1819 assert!(payment_preimage.is_none());
1820 assert_eq!(our_payment_secret_22, *payment_secret);
1822 _ => panic!("expected PaymentPurpose::InvoicePayment")
1825 _ => panic!("Unexpected event"),
1828 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1829 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1830 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1832 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1833 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1834 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1836 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1837 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);
1838 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1839 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1840 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1842 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1843 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1847 fn channel_reserve_in_flight_removes() {
1848 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1849 // can send to its counterparty, but due to update ordering, the other side may not yet have
1850 // considered those HTLCs fully removed.
1851 // This tests that we don't count HTLCs which will not be included in the next remote
1852 // commitment transaction towards the reserve value (as it implies no commitment transaction
1853 // will be generated which violates the remote reserve value).
1854 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1856 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1857 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1858 // you only consider the value of the first HTLC, it may not),
1859 // * start routing a third HTLC from A to B,
1860 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1861 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1862 // * deliver the first fulfill from B
1863 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1865 // * deliver A's response CS and RAA.
1866 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1867 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1868 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1869 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1870 let chanmon_cfgs = create_chanmon_cfgs(2);
1871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1873 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1874 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1875 let logger = test_utils::TestLogger::new();
1877 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1878 // Route the first two HTLCs.
1879 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1880 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1882 // Start routing the third HTLC (this is just used to get everyone in the right state).
1883 let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
1885 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1886 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
1887 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1888 check_added_monitors!(nodes[0], 1);
1889 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1890 assert_eq!(events.len(), 1);
1891 SendEvent::from_event(events.remove(0))
1894 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1895 // initial fulfill/CS.
1896 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1897 check_added_monitors!(nodes[1], 1);
1898 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1900 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1901 // remove the second HTLC when we send the HTLC back from B to A.
1902 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1903 check_added_monitors!(nodes[1], 1);
1904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1906 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1907 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1908 check_added_monitors!(nodes[0], 1);
1909 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1910 expect_payment_sent!(nodes[0], payment_preimage_1);
1912 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1913 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1914 check_added_monitors!(nodes[1], 1);
1915 // B is already AwaitingRAA, so cant generate a CS here
1916 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1918 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1919 check_added_monitors!(nodes[1], 1);
1920 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1922 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1923 check_added_monitors!(nodes[0], 1);
1924 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1926 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1927 check_added_monitors!(nodes[1], 1);
1928 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1930 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1931 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1932 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1933 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1934 // on-chain as necessary).
1935 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1936 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1937 check_added_monitors!(nodes[0], 1);
1938 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1939 expect_payment_sent!(nodes[0], payment_preimage_2);
1941 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1942 check_added_monitors!(nodes[1], 1);
1943 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1945 expect_pending_htlcs_forwardable!(nodes[1]);
1946 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1948 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1949 // resolve the second HTLC from A's point of view.
1950 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1951 check_added_monitors!(nodes[0], 1);
1952 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1954 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1955 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1956 let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
1958 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1959 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
1960 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1961 check_added_monitors!(nodes[1], 1);
1962 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1963 assert_eq!(events.len(), 1);
1964 SendEvent::from_event(events.remove(0))
1967 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1968 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1969 check_added_monitors!(nodes[0], 1);
1970 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1972 // Now just resolve all the outstanding messages/HTLCs for completeness...
1974 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1975 check_added_monitors!(nodes[1], 1);
1976 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1978 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1979 check_added_monitors!(nodes[1], 1);
1981 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1982 check_added_monitors!(nodes[0], 1);
1983 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1985 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1986 check_added_monitors!(nodes[1], 1);
1987 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1989 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1990 check_added_monitors!(nodes[0], 1);
1992 expect_pending_htlcs_forwardable!(nodes[0]);
1993 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
1995 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1996 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2000 fn channel_monitor_network_test() {
2001 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2002 // tests that ChannelMonitor is able to recover from various states.
2003 let chanmon_cfgs = create_chanmon_cfgs(5);
2004 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2005 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2006 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2008 // Create some initial channels
2009 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2010 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2011 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2012 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2014 // Make sure all nodes are at the same starting height
2015 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2016 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2017 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2018 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2019 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2021 // Rebalance the network a bit by relaying one payment through all the channels...
2022 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2023 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2024 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2025 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2027 // Simple case with no pending HTLCs:
2028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2029 check_added_monitors!(nodes[1], 1);
2030 check_closed_broadcast!(nodes[1], false);
2032 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2033 assert_eq!(node_txn.len(), 1);
2034 mine_transaction(&nodes[0], &node_txn[0]);
2035 check_added_monitors!(nodes[0], 1);
2036 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2038 check_closed_broadcast!(nodes[0], true);
2039 assert_eq!(nodes[0].node.list_channels().len(), 0);
2040 assert_eq!(nodes[1].node.list_channels().len(), 1);
2042 // One pending HTLC is discarded by the force-close:
2043 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2045 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2046 // broadcasted until we reach the timelock time).
2047 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2048 check_closed_broadcast!(nodes[1], false);
2049 check_added_monitors!(nodes[1], 1);
2051 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2052 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2053 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2054 mine_transaction(&nodes[2], &node_txn[0]);
2055 check_added_monitors!(nodes[2], 1);
2056 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2058 check_closed_broadcast!(nodes[2], true);
2059 assert_eq!(nodes[1].node.list_channels().len(), 0);
2060 assert_eq!(nodes[2].node.list_channels().len(), 1);
2062 macro_rules! claim_funds {
2063 ($node: expr, $prev_node: expr, $preimage: expr) => {
2065 assert!($node.node.claim_funds($preimage));
2066 check_added_monitors!($node, 1);
2068 let events = $node.node.get_and_clear_pending_msg_events();
2069 assert_eq!(events.len(), 1);
2071 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2072 assert!(update_add_htlcs.is_empty());
2073 assert!(update_fail_htlcs.is_empty());
2074 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2076 _ => panic!("Unexpected event"),
2082 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2083 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2084 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2085 check_added_monitors!(nodes[2], 1);
2086 check_closed_broadcast!(nodes[2], false);
2087 let node2_commitment_txid;
2089 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2090 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2091 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2092 node2_commitment_txid = node_txn[0].txid();
2094 // Claim the payment on nodes[3], giving it knowledge of the preimage
2095 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2096 mine_transaction(&nodes[3], &node_txn[0]);
2097 check_added_monitors!(nodes[3], 1);
2098 check_preimage_claim(&nodes[3], &node_txn);
2100 check_closed_broadcast!(nodes[3], true);
2101 assert_eq!(nodes[2].node.list_channels().len(), 0);
2102 assert_eq!(nodes[3].node.list_channels().len(), 1);
2104 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2105 // confusing us in the following tests.
2106 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2108 // One pending HTLC to time out:
2109 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2110 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2113 let (close_chan_update_1, close_chan_update_2) = {
2114 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2115 let events = nodes[3].node.get_and_clear_pending_msg_events();
2116 assert_eq!(events.len(), 2);
2117 let close_chan_update_1 = match events[0] {
2118 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2121 _ => panic!("Unexpected event"),
2124 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2125 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2127 _ => panic!("Unexpected event"),
2129 check_added_monitors!(nodes[3], 1);
2131 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2133 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2134 node_txn.retain(|tx| {
2135 if tx.input[0].previous_output.txid == node2_commitment_txid {
2141 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2143 // Claim the payment on nodes[4], giving it knowledge of the preimage
2144 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2146 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2147 let events = nodes[4].node.get_and_clear_pending_msg_events();
2148 assert_eq!(events.len(), 2);
2149 let close_chan_update_2 = match events[0] {
2150 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2153 _ => panic!("Unexpected event"),
2156 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2157 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2159 _ => panic!("Unexpected event"),
2161 check_added_monitors!(nodes[4], 1);
2162 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2164 mine_transaction(&nodes[4], &node_txn[0]);
2165 check_preimage_claim(&nodes[4], &node_txn);
2166 (close_chan_update_1, close_chan_update_2)
2168 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2169 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2170 assert_eq!(nodes[3].node.list_channels().len(), 0);
2171 assert_eq!(nodes[4].node.list_channels().len(), 0);
2173 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2177 fn test_justice_tx() {
2178 // Test justice txn built on revoked HTLC-Success tx, against both sides
2179 let mut alice_config = UserConfig::default();
2180 alice_config.channel_options.announced_channel = true;
2181 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2182 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2183 let mut bob_config = UserConfig::default();
2184 bob_config.channel_options.announced_channel = true;
2185 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2186 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2187 let user_cfgs = [Some(alice_config), Some(bob_config)];
2188 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2189 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2190 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2193 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2194 // Create some new channels:
2195 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2197 // A pending HTLC which will be revoked:
2198 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2199 // Get the will-be-revoked local txn from nodes[0]
2200 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2201 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2202 assert_eq!(revoked_local_txn[0].input.len(), 1);
2203 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2204 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2205 assert_eq!(revoked_local_txn[1].input.len(), 1);
2206 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2207 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2208 // Revoke the old state
2209 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2212 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2214 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2215 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2216 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2218 check_spends!(node_txn[0], revoked_local_txn[0]);
2219 node_txn.swap_remove(0);
2220 node_txn.truncate(1);
2222 check_added_monitors!(nodes[1], 1);
2223 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2225 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2226 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2227 // Verify broadcast of revoked HTLC-timeout
2228 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2229 check_added_monitors!(nodes[0], 1);
2230 // Broadcast revoked HTLC-timeout on node 1
2231 mine_transaction(&nodes[1], &node_txn[1]);
2232 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2234 get_announce_close_broadcast_events(&nodes, 0, 1);
2236 assert_eq!(nodes[0].node.list_channels().len(), 0);
2237 assert_eq!(nodes[1].node.list_channels().len(), 0);
2239 // We test justice_tx build by A on B's revoked HTLC-Success tx
2240 // Create some new channels:
2241 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2243 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2247 // A pending HTLC which will be revoked:
2248 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2249 // Get the will-be-revoked local txn from B
2250 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2251 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2252 assert_eq!(revoked_local_txn[0].input.len(), 1);
2253 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2254 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2255 // Revoke the old state
2256 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2258 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2260 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2261 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2262 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2264 check_spends!(node_txn[0], revoked_local_txn[0]);
2265 node_txn.swap_remove(0);
2267 check_added_monitors!(nodes[0], 1);
2268 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2270 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2271 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2272 check_added_monitors!(nodes[1], 1);
2273 mine_transaction(&nodes[0], &node_txn[1]);
2274 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2276 get_announce_close_broadcast_events(&nodes, 0, 1);
2277 assert_eq!(nodes[0].node.list_channels().len(), 0);
2278 assert_eq!(nodes[1].node.list_channels().len(), 0);
2282 fn revoked_output_claim() {
2283 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2284 // transaction is broadcast by its counterparty
2285 let chanmon_cfgs = create_chanmon_cfgs(2);
2286 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2287 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2288 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2289 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2290 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2291 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2292 assert_eq!(revoked_local_txn.len(), 1);
2293 // Only output is the full channel value back to nodes[0]:
2294 assert_eq!(revoked_local_txn[0].output.len(), 1);
2295 // Send a payment through, updating everyone's latest commitment txn
2296 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2298 // Inform nodes[1] that nodes[0] broadcast a stale tx
2299 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2300 check_added_monitors!(nodes[1], 1);
2301 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2302 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2304 check_spends!(node_txn[0], revoked_local_txn[0]);
2305 check_spends!(node_txn[1], chan_1.3);
2307 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2308 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2309 get_announce_close_broadcast_events(&nodes, 0, 1);
2310 check_added_monitors!(nodes[0], 1)
2314 fn claim_htlc_outputs_shared_tx() {
2315 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2316 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2317 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2320 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2322 // Create some new channel:
2323 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2325 // Rebalance the network to generate htlc in the two directions
2326 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2327 // 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
2328 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2329 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2331 // Get the will-be-revoked local txn from node[0]
2332 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2333 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2334 assert_eq!(revoked_local_txn[0].input.len(), 1);
2335 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2336 assert_eq!(revoked_local_txn[1].input.len(), 1);
2337 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2338 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2339 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2341 //Revoke the old state
2342 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2345 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2346 check_added_monitors!(nodes[0], 1);
2347 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2348 check_added_monitors!(nodes[1], 1);
2349 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2350 expect_payment_failed!(nodes[1], payment_hash_2, true);
2352 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2353 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2355 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2356 check_spends!(node_txn[0], revoked_local_txn[0]);
2358 let mut witness_lens = BTreeSet::new();
2359 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2360 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2361 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2362 assert_eq!(witness_lens.len(), 3);
2363 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2364 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2365 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2367 // Next nodes[1] broadcasts its current local tx state:
2368 assert_eq!(node_txn[1].input.len(), 1);
2369 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2371 get_announce_close_broadcast_events(&nodes, 0, 1);
2372 assert_eq!(nodes[0].node.list_channels().len(), 0);
2373 assert_eq!(nodes[1].node.list_channels().len(), 0);
2377 fn claim_htlc_outputs_single_tx() {
2378 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2379 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2380 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2381 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2382 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2383 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2385 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2387 // Rebalance the network to generate htlc in the two directions
2388 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2389 // 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
2390 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2391 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2392 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2394 // Get the will-be-revoked local txn from node[0]
2395 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2397 //Revoke the old state
2398 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2401 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2402 check_added_monitors!(nodes[0], 1);
2403 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2404 check_added_monitors!(nodes[1], 1);
2405 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2407 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2408 expect_payment_failed!(nodes[1], payment_hash_2, true);
2410 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2411 assert_eq!(node_txn.len(), 9);
2412 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2413 // ChannelManager: local commmitment + local HTLC-timeout (2)
2414 // 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)
2415 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2417 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2418 assert_eq!(node_txn[0].input.len(), 1);
2419 check_spends!(node_txn[0], chan_1.3);
2420 assert_eq!(node_txn[1].input.len(), 1);
2421 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2422 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2423 check_spends!(node_txn[1], node_txn[0]);
2425 // Justice transactions are indices 1-2-4
2426 assert_eq!(node_txn[2].input.len(), 1);
2427 assert_eq!(node_txn[3].input.len(), 1);
2428 assert_eq!(node_txn[4].input.len(), 1);
2430 check_spends!(node_txn[2], revoked_local_txn[0]);
2431 check_spends!(node_txn[3], revoked_local_txn[0]);
2432 check_spends!(node_txn[4], revoked_local_txn[0]);
2434 let mut witness_lens = BTreeSet::new();
2435 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2436 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2437 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2438 assert_eq!(witness_lens.len(), 3);
2439 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2440 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2441 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2443 get_announce_close_broadcast_events(&nodes, 0, 1);
2444 assert_eq!(nodes[0].node.list_channels().len(), 0);
2445 assert_eq!(nodes[1].node.list_channels().len(), 0);
2449 fn test_htlc_on_chain_success() {
2450 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2451 // the preimage backward accordingly. So here we test that ChannelManager is
2452 // broadcasting the right event to other nodes in payment path.
2453 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2454 // A --------------------> B ----------------------> C (preimage)
2455 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2456 // commitment transaction was broadcast.
2457 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2459 // B should be able to claim via preimage if A then broadcasts its local tx.
2460 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2461 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2462 // PaymentSent event).
2464 let chanmon_cfgs = create_chanmon_cfgs(3);
2465 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2466 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2467 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2469 // Create some initial channels
2470 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2471 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2473 // Ensure all nodes are at the same height
2474 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2475 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2476 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2477 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2479 // Rebalance the network a bit by relaying one payment through all the channels...
2480 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2481 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2483 let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2484 let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2486 // Broadcast legit commitment tx from C on B's chain
2487 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2488 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2489 assert_eq!(commitment_tx.len(), 1);
2490 check_spends!(commitment_tx[0], chan_2.3);
2491 nodes[2].node.claim_funds(our_payment_preimage);
2492 nodes[2].node.claim_funds(our_payment_preimage_2);
2493 check_added_monitors!(nodes[2], 2);
2494 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2495 assert!(updates.update_add_htlcs.is_empty());
2496 assert!(updates.update_fail_htlcs.is_empty());
2497 assert!(updates.update_fail_malformed_htlcs.is_empty());
2498 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2500 mine_transaction(&nodes[2], &commitment_tx[0]);
2501 check_closed_broadcast!(nodes[2], true);
2502 check_added_monitors!(nodes[2], 1);
2503 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)
2504 assert_eq!(node_txn.len(), 5);
2505 assert_eq!(node_txn[0], node_txn[3]);
2506 assert_eq!(node_txn[1], node_txn[4]);
2507 assert_eq!(node_txn[2], commitment_tx[0]);
2508 check_spends!(node_txn[0], commitment_tx[0]);
2509 check_spends!(node_txn[1], commitment_tx[0]);
2510 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2511 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2512 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2513 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2514 assert_eq!(node_txn[0].lock_time, 0);
2515 assert_eq!(node_txn[1].lock_time, 0);
2517 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2518 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2519 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2520 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2522 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2523 assert_eq!(added_monitors.len(), 1);
2524 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2525 added_monitors.clear();
2527 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2528 assert_eq!(forwarded_events.len(), 2);
2529 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[0] {
2530 } else { panic!(); }
2531 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2532 } else { panic!(); }
2533 let events = nodes[1].node.get_and_clear_pending_msg_events();
2535 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2536 assert_eq!(added_monitors.len(), 2);
2537 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2538 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2539 added_monitors.clear();
2541 assert_eq!(events.len(), 3);
2543 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2544 _ => panic!("Unexpected event"),
2547 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2548 _ => panic!("Unexpected event"),
2552 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, .. } } => {
2553 assert!(update_add_htlcs.is_empty());
2554 assert!(update_fail_htlcs.is_empty());
2555 assert_eq!(update_fulfill_htlcs.len(), 1);
2556 assert!(update_fail_malformed_htlcs.is_empty());
2557 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2559 _ => panic!("Unexpected event"),
2561 macro_rules! check_tx_local_broadcast {
2562 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2563 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2564 assert_eq!(node_txn.len(), 3);
2565 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2566 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2567 check_spends!(node_txn[1], $commitment_tx);
2568 check_spends!(node_txn[2], $commitment_tx);
2569 assert_ne!(node_txn[1].lock_time, 0);
2570 assert_ne!(node_txn[2].lock_time, 0);
2572 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2573 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2574 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2575 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2577 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2578 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2579 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2580 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2582 check_spends!(node_txn[0], $chan_tx);
2583 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2587 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2588 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2589 // timeout-claim of the output that nodes[2] just claimed via success.
2590 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2592 // Broadcast legit commitment tx from A on B's chain
2593 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2594 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2595 check_spends!(node_a_commitment_tx[0], chan_1.3);
2596 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2597 check_closed_broadcast!(nodes[1], true);
2598 check_added_monitors!(nodes[1], 1);
2599 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2600 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2601 let commitment_spend =
2602 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2603 check_spends!(node_txn[1], commitment_tx[0]);
2604 check_spends!(node_txn[2], commitment_tx[0]);
2605 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2608 check_spends!(node_txn[0], commitment_tx[0]);
2609 check_spends!(node_txn[1], commitment_tx[0]);
2610 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2614 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2615 assert_eq!(commitment_spend.input.len(), 2);
2616 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2617 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2618 assert_eq!(commitment_spend.lock_time, 0);
2619 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2620 check_spends!(node_txn[3], chan_1.3);
2621 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2622 check_spends!(node_txn[4], node_txn[3]);
2623 check_spends!(node_txn[5], node_txn[3]);
2624 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2625 // we already checked the same situation with A.
2627 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2628 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2629 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2630 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2631 check_closed_broadcast!(nodes[0], true);
2632 check_added_monitors!(nodes[0], 1);
2633 let events = nodes[0].node.get_and_clear_pending_events();
2634 assert_eq!(events.len(), 2);
2635 let mut first_claimed = false;
2636 for event in events {
2638 Event::PaymentSent { payment_preimage } => {
2639 if payment_preimage == our_payment_preimage {
2640 assert!(!first_claimed);
2641 first_claimed = true;
2643 assert_eq!(payment_preimage, our_payment_preimage_2);
2646 _ => panic!("Unexpected event"),
2649 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2652 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2653 // Test that in case of a unilateral close onchain, we detect the state of output and
2654 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2655 // broadcasting the right event to other nodes in payment path.
2656 // A ------------------> B ----------------------> C (timeout)
2657 // B's commitment tx C's commitment tx
2659 // B's HTLC timeout tx B's timeout tx
2661 let chanmon_cfgs = create_chanmon_cfgs(3);
2662 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2663 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2664 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2665 *nodes[0].connect_style.borrow_mut() = connect_style;
2666 *nodes[1].connect_style.borrow_mut() = connect_style;
2667 *nodes[2].connect_style.borrow_mut() = connect_style;
2669 // Create some intial channels
2670 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2671 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2673 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2674 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2675 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2677 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2679 // Broadcast legit commitment tx from C on B's chain
2680 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2681 check_spends!(commitment_tx[0], chan_2.3);
2682 nodes[2].node.fail_htlc_backwards(&payment_hash);
2683 check_added_monitors!(nodes[2], 0);
2684 expect_pending_htlcs_forwardable!(nodes[2]);
2685 check_added_monitors!(nodes[2], 1);
2687 let events = nodes[2].node.get_and_clear_pending_msg_events();
2688 assert_eq!(events.len(), 1);
2690 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, .. } } => {
2691 assert!(update_add_htlcs.is_empty());
2692 assert!(!update_fail_htlcs.is_empty());
2693 assert!(update_fulfill_htlcs.is_empty());
2694 assert!(update_fail_malformed_htlcs.is_empty());
2695 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2697 _ => panic!("Unexpected event"),
2699 mine_transaction(&nodes[2], &commitment_tx[0]);
2700 check_closed_broadcast!(nodes[2], true);
2701 check_added_monitors!(nodes[2], 1);
2702 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2703 assert_eq!(node_txn.len(), 1);
2704 check_spends!(node_txn[0], chan_2.3);
2705 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2707 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2708 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2709 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2710 mine_transaction(&nodes[1], &commitment_tx[0]);
2713 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2714 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2715 assert_eq!(node_txn[0], node_txn[3]);
2716 assert_eq!(node_txn[1], node_txn[4]);
2718 check_spends!(node_txn[2], commitment_tx[0]);
2719 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2721 check_spends!(node_txn[0], chan_2.3);
2722 check_spends!(node_txn[1], node_txn[0]);
2723 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2724 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2726 timeout_tx = node_txn[2].clone();
2730 mine_transaction(&nodes[1], &timeout_tx);
2731 check_added_monitors!(nodes[1], 1);
2732 check_closed_broadcast!(nodes[1], true);
2734 // B will rebroadcast a fee-bumped timeout transaction here.
2735 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2736 assert_eq!(node_txn.len(), 1);
2737 check_spends!(node_txn[0], commitment_tx[0]);
2740 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2742 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2743 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2744 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2745 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2746 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2747 if node_txn.len() == 1 {
2748 check_spends!(node_txn[0], chan_2.3);
2750 assert_eq!(node_txn.len(), 0);
2754 expect_pending_htlcs_forwardable!(nodes[1]);
2755 check_added_monitors!(nodes[1], 1);
2756 let events = nodes[1].node.get_and_clear_pending_msg_events();
2757 assert_eq!(events.len(), 1);
2759 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, .. } } => {
2760 assert!(update_add_htlcs.is_empty());
2761 assert!(!update_fail_htlcs.is_empty());
2762 assert!(update_fulfill_htlcs.is_empty());
2763 assert!(update_fail_malformed_htlcs.is_empty());
2764 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2766 _ => panic!("Unexpected event"),
2769 // Broadcast legit commitment tx from B on A's chain
2770 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2771 check_spends!(commitment_tx[0], chan_1.3);
2773 mine_transaction(&nodes[0], &commitment_tx[0]);
2774 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2776 check_closed_broadcast!(nodes[0], true);
2777 check_added_monitors!(nodes[0], 1);
2778 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2779 assert_eq!(node_txn.len(), 2);
2780 check_spends!(node_txn[0], chan_1.3);
2781 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2782 check_spends!(node_txn[1], commitment_tx[0]);
2783 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2787 fn test_htlc_on_chain_timeout() {
2788 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2789 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2790 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2794 fn test_simple_commitment_revoked_fail_backward() {
2795 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2796 // and fail backward accordingly.
2798 let chanmon_cfgs = create_chanmon_cfgs(3);
2799 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2800 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2801 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2803 // Create some initial channels
2804 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2805 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2807 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2808 // Get the will-be-revoked local txn from nodes[2]
2809 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2810 // Revoke the old state
2811 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2813 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2815 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2816 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2817 check_added_monitors!(nodes[1], 1);
2818 check_closed_broadcast!(nodes[1], true);
2820 expect_pending_htlcs_forwardable!(nodes[1]);
2821 check_added_monitors!(nodes[1], 1);
2822 let events = nodes[1].node.get_and_clear_pending_msg_events();
2823 assert_eq!(events.len(), 1);
2825 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, .. } } => {
2826 assert!(update_add_htlcs.is_empty());
2827 assert_eq!(update_fail_htlcs.len(), 1);
2828 assert!(update_fulfill_htlcs.is_empty());
2829 assert!(update_fail_malformed_htlcs.is_empty());
2830 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2832 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2833 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2834 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, true);
2835 expect_payment_failed!(nodes[0], payment_hash, false);
2837 _ => panic!("Unexpected event"),
2841 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2842 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2843 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2844 // commitment transaction anymore.
2845 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2846 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2847 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2848 // technically disallowed and we should probably handle it reasonably.
2849 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2850 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2852 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2853 // commitment_signed (implying it will be in the latest remote commitment transaction).
2854 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2855 // and once they revoke the previous commitment transaction (allowing us to send a new
2856 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2857 let chanmon_cfgs = create_chanmon_cfgs(3);
2858 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2859 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2860 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2862 // Create some initial channels
2863 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2864 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2866 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 });
2867 // Get the will-be-revoked local txn from nodes[2]
2868 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2869 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2870 // Revoke the old state
2871 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2873 let value = if use_dust {
2874 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2875 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2876 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2879 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2880 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2881 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2883 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2884 expect_pending_htlcs_forwardable!(nodes[2]);
2885 check_added_monitors!(nodes[2], 1);
2886 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2887 assert!(updates.update_add_htlcs.is_empty());
2888 assert!(updates.update_fulfill_htlcs.is_empty());
2889 assert!(updates.update_fail_malformed_htlcs.is_empty());
2890 assert_eq!(updates.update_fail_htlcs.len(), 1);
2891 assert!(updates.update_fee.is_none());
2892 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2893 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2894 // Drop the last RAA from 3 -> 2
2896 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2897 expect_pending_htlcs_forwardable!(nodes[2]);
2898 check_added_monitors!(nodes[2], 1);
2899 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2900 assert!(updates.update_add_htlcs.is_empty());
2901 assert!(updates.update_fulfill_htlcs.is_empty());
2902 assert!(updates.update_fail_malformed_htlcs.is_empty());
2903 assert_eq!(updates.update_fail_htlcs.len(), 1);
2904 assert!(updates.update_fee.is_none());
2905 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2906 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2907 check_added_monitors!(nodes[1], 1);
2908 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2909 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2910 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2911 check_added_monitors!(nodes[2], 1);
2913 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2914 expect_pending_htlcs_forwardable!(nodes[2]);
2915 check_added_monitors!(nodes[2], 1);
2916 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2917 assert!(updates.update_add_htlcs.is_empty());
2918 assert!(updates.update_fulfill_htlcs.is_empty());
2919 assert!(updates.update_fail_malformed_htlcs.is_empty());
2920 assert_eq!(updates.update_fail_htlcs.len(), 1);
2921 assert!(updates.update_fee.is_none());
2922 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2923 // At this point first_payment_hash has dropped out of the latest two commitment
2924 // transactions that nodes[1] is tracking...
2925 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2926 check_added_monitors!(nodes[1], 1);
2927 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2928 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2929 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2930 check_added_monitors!(nodes[2], 1);
2932 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2933 // on nodes[2]'s RAA.
2934 let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
2935 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2936 let logger = test_utils::TestLogger::new();
2937 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
2938 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2939 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2940 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2941 check_added_monitors!(nodes[1], 0);
2944 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2945 // One monitor for the new revocation preimage, no second on as we won't generate a new
2946 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2947 check_added_monitors!(nodes[1], 1);
2948 let events = nodes[1].node.get_and_clear_pending_events();
2949 assert_eq!(events.len(), 1);
2951 Event::PendingHTLCsForwardable { .. } => { },
2952 _ => panic!("Unexpected event"),
2954 // Deliberately don't process the pending fail-back so they all fail back at once after
2955 // block connection just like the !deliver_bs_raa case
2958 let mut failed_htlcs = HashSet::new();
2959 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2961 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2962 check_added_monitors!(nodes[1], 1);
2963 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2965 let events = nodes[1].node.get_and_clear_pending_events();
2966 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2968 Event::PaymentFailed { ref payment_hash, .. } => {
2969 assert_eq!(*payment_hash, fourth_payment_hash);
2971 _ => panic!("Unexpected event"),
2973 if !deliver_bs_raa {
2975 Event::PendingHTLCsForwardable { .. } => { },
2976 _ => panic!("Unexpected event"),
2979 nodes[1].node.process_pending_htlc_forwards();
2980 check_added_monitors!(nodes[1], 1);
2982 let events = nodes[1].node.get_and_clear_pending_msg_events();
2983 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
2984 match events[if deliver_bs_raa { 1 } else { 0 }] {
2985 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2986 _ => panic!("Unexpected event"),
2988 match events[if deliver_bs_raa { 2 } else { 1 }] {
2989 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
2990 assert_eq!(channel_id, chan_2.2);
2991 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
2993 _ => panic!("Unexpected event"),
2997 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, .. } } => {
2998 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2999 assert_eq!(update_add_htlcs.len(), 1);
3000 assert!(update_fulfill_htlcs.is_empty());
3001 assert!(update_fail_htlcs.is_empty());
3002 assert!(update_fail_malformed_htlcs.is_empty());
3004 _ => panic!("Unexpected event"),
3007 match events[if deliver_bs_raa { 3 } else { 2 }] {
3008 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, .. } } => {
3009 assert!(update_add_htlcs.is_empty());
3010 assert_eq!(update_fail_htlcs.len(), 3);
3011 assert!(update_fulfill_htlcs.is_empty());
3012 assert!(update_fail_malformed_htlcs.is_empty());
3013 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3015 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3016 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3017 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3019 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3021 let events = nodes[0].node.get_and_clear_pending_msg_events();
3022 // If we delivered B's RAA we got an unknown preimage error, not something
3023 // that we should update our routing table for.
3024 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3025 for event in events {
3027 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3028 _ => panic!("Unexpected event"),
3031 let events = nodes[0].node.get_and_clear_pending_events();
3032 assert_eq!(events.len(), 3);
3034 Event::PaymentFailed { ref payment_hash, .. } => {
3035 assert!(failed_htlcs.insert(payment_hash.0));
3037 _ => panic!("Unexpected event"),
3040 Event::PaymentFailed { ref payment_hash, .. } => {
3041 assert!(failed_htlcs.insert(payment_hash.0));
3043 _ => panic!("Unexpected event"),
3046 Event::PaymentFailed { ref payment_hash, .. } => {
3047 assert!(failed_htlcs.insert(payment_hash.0));
3049 _ => panic!("Unexpected event"),
3052 _ => panic!("Unexpected event"),
3055 assert!(failed_htlcs.contains(&first_payment_hash.0));
3056 assert!(failed_htlcs.contains(&second_payment_hash.0));
3057 assert!(failed_htlcs.contains(&third_payment_hash.0));
3061 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3062 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3063 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3064 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3065 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3069 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3070 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3071 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3072 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3073 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3077 fn fail_backward_pending_htlc_upon_channel_failure() {
3078 let chanmon_cfgs = create_chanmon_cfgs(2);
3079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3081 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3082 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3083 let logger = test_utils::TestLogger::new();
3085 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3087 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3088 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3089 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3090 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3091 check_added_monitors!(nodes[0], 1);
3093 let payment_event = {
3094 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3095 assert_eq!(events.len(), 1);
3096 SendEvent::from_event(events.remove(0))
3098 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3099 assert_eq!(payment_event.msgs.len(), 1);
3102 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3103 let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3105 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3106 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3107 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3108 check_added_monitors!(nodes[0], 0);
3110 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3113 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3115 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3117 let secp_ctx = Secp256k1::new();
3118 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3119 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3120 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3121 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3122 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3123 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3124 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3126 // Send a 0-msat update_add_htlc to fail the channel.
3127 let update_add_htlc = msgs::UpdateAddHTLC {
3133 onion_routing_packet,
3135 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3138 // Check that Alice fails backward the pending HTLC from the second payment.
3139 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3140 check_closed_broadcast!(nodes[0], true);
3141 check_added_monitors!(nodes[0], 1);
3145 fn test_htlc_ignore_latest_remote_commitment() {
3146 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3147 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3148 let chanmon_cfgs = create_chanmon_cfgs(2);
3149 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3150 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3151 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3152 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3154 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3155 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3156 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3157 check_closed_broadcast!(nodes[0], true);
3158 check_added_monitors!(nodes[0], 1);
3160 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3161 assert_eq!(node_txn.len(), 3);
3162 assert_eq!(node_txn[0], node_txn[1]);
3164 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3165 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3166 check_closed_broadcast!(nodes[1], true);
3167 check_added_monitors!(nodes[1], 1);
3169 // Duplicate the connect_block call since this may happen due to other listeners
3170 // registering new transactions
3171 header.prev_blockhash = header.block_hash();
3172 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3176 fn test_force_close_fail_back() {
3177 // Check which HTLCs are failed-backwards on channel force-closure
3178 let chanmon_cfgs = create_chanmon_cfgs(3);
3179 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3180 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3181 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3182 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3183 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3184 let logger = test_utils::TestLogger::new();
3186 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3188 let mut payment_event = {
3189 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3190 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3191 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3192 check_added_monitors!(nodes[0], 1);
3194 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3195 assert_eq!(events.len(), 1);
3196 SendEvent::from_event(events.remove(0))
3199 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3200 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3202 expect_pending_htlcs_forwardable!(nodes[1]);
3204 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3205 assert_eq!(events_2.len(), 1);
3206 payment_event = SendEvent::from_event(events_2.remove(0));
3207 assert_eq!(payment_event.msgs.len(), 1);
3209 check_added_monitors!(nodes[1], 1);
3210 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3211 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3212 check_added_monitors!(nodes[2], 1);
3213 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3215 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3216 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3217 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3219 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3220 check_closed_broadcast!(nodes[2], true);
3221 check_added_monitors!(nodes[2], 1);
3223 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3224 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3225 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3226 // back to nodes[1] upon timeout otherwise.
3227 assert_eq!(node_txn.len(), 1);
3231 mine_transaction(&nodes[1], &tx);
3233 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3234 check_closed_broadcast!(nodes[1], true);
3235 check_added_monitors!(nodes[1], 1);
3237 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3239 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3240 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3241 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3243 mine_transaction(&nodes[2], &tx);
3244 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3245 assert_eq!(node_txn.len(), 1);
3246 assert_eq!(node_txn[0].input.len(), 1);
3247 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3248 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3249 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3251 check_spends!(node_txn[0], tx);
3255 fn test_dup_events_on_peer_disconnect() {
3256 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3257 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3258 // as we used to generate the event immediately upon receipt of the payment preimage in the
3259 // update_fulfill_htlc message.
3261 let chanmon_cfgs = create_chanmon_cfgs(2);
3262 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3263 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3264 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3265 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3267 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3269 assert!(nodes[1].node.claim_funds(payment_preimage));
3270 check_added_monitors!(nodes[1], 1);
3271 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3272 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3273 expect_payment_sent!(nodes[0], payment_preimage);
3275 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3276 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3278 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3279 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3283 fn test_simple_peer_disconnect() {
3284 // Test that we can reconnect when there are no lost messages
3285 let chanmon_cfgs = create_chanmon_cfgs(3);
3286 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3287 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3288 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3289 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3290 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3292 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3293 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3294 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3296 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3297 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3298 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3299 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3301 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3302 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3303 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3305 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3306 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3307 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3308 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3310 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3311 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3313 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3314 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3316 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3318 let events = nodes[0].node.get_and_clear_pending_events();
3319 assert_eq!(events.len(), 2);
3321 Event::PaymentSent { payment_preimage } => {
3322 assert_eq!(payment_preimage, payment_preimage_3);
3324 _ => panic!("Unexpected event"),
3327 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3328 assert_eq!(payment_hash, payment_hash_5);
3329 assert!(rejected_by_dest);
3331 _ => panic!("Unexpected event"),
3335 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3336 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3339 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3340 // Test that we can reconnect when in-flight HTLC updates get dropped
3341 let chanmon_cfgs = create_chanmon_cfgs(2);
3342 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3343 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3344 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3346 let mut as_funding_locked = None;
3347 if messages_delivered == 0 {
3348 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3349 as_funding_locked = Some(funding_locked);
3350 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3351 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3352 // it before the channel_reestablish message.
3354 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3357 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3359 let logger = test_utils::TestLogger::new();
3360 let payment_event = {
3361 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3362 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3363 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3364 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3365 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3366 check_added_monitors!(nodes[0], 1);
3368 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3369 assert_eq!(events.len(), 1);
3370 SendEvent::from_event(events.remove(0))
3372 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3374 if messages_delivered < 2 {
3375 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3378 if messages_delivered >= 3 {
3379 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3380 check_added_monitors!(nodes[1], 1);
3381 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3383 if messages_delivered >= 4 {
3384 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3385 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3386 check_added_monitors!(nodes[0], 1);
3388 if messages_delivered >= 5 {
3389 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3390 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3391 // No commitment_signed so get_event_msg's assert(len == 1) passes
3392 check_added_monitors!(nodes[0], 1);
3394 if messages_delivered >= 6 {
3395 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3396 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3397 check_added_monitors!(nodes[1], 1);
3404 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3405 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3406 if messages_delivered < 3 {
3407 if simulate_broken_lnd {
3408 // lnd has a long-standing bug where they send a funding_locked prior to a
3409 // channel_reestablish if you reconnect prior to funding_locked time.
3411 // Here we simulate that behavior, delivering a funding_locked immediately on
3412 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3413 // in `reconnect_nodes` but we currently don't fail based on that.
3415 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3416 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3418 // Even if the funding_locked messages get exchanged, as long as nothing further was
3419 // received on either side, both sides will need to resend them.
3420 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3421 } else if messages_delivered == 3 {
3422 // nodes[0] still wants its RAA + commitment_signed
3423 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3424 } else if messages_delivered == 4 {
3425 // nodes[0] still wants its commitment_signed
3426 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3427 } else if messages_delivered == 5 {
3428 // nodes[1] still wants its final RAA
3429 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3430 } else if messages_delivered == 6 {
3431 // Everything was delivered...
3432 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3435 let events_1 = nodes[1].node.get_and_clear_pending_events();
3436 assert_eq!(events_1.len(), 1);
3438 Event::PendingHTLCsForwardable { .. } => { },
3439 _ => panic!("Unexpected event"),
3442 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3443 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3444 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3446 nodes[1].node.process_pending_htlc_forwards();
3448 let events_2 = nodes[1].node.get_and_clear_pending_events();
3449 assert_eq!(events_2.len(), 1);
3451 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3452 assert_eq!(payment_hash_1, *payment_hash);
3453 assert_eq!(amt, 1000000);
3455 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3456 assert!(payment_preimage.is_none());
3457 assert_eq!(payment_secret_1, *payment_secret);
3459 _ => panic!("expected PaymentPurpose::InvoicePayment")
3462 _ => panic!("Unexpected event"),
3465 nodes[1].node.claim_funds(payment_preimage_1);
3466 check_added_monitors!(nodes[1], 1);
3468 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3469 assert_eq!(events_3.len(), 1);
3470 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3471 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3472 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3473 assert!(updates.update_add_htlcs.is_empty());
3474 assert!(updates.update_fail_htlcs.is_empty());
3475 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3476 assert!(updates.update_fail_malformed_htlcs.is_empty());
3477 assert!(updates.update_fee.is_none());
3478 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3480 _ => panic!("Unexpected event"),
3483 if messages_delivered >= 1 {
3484 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3486 let events_4 = nodes[0].node.get_and_clear_pending_events();
3487 assert_eq!(events_4.len(), 1);
3489 Event::PaymentSent { ref payment_preimage } => {
3490 assert_eq!(payment_preimage_1, *payment_preimage);
3492 _ => panic!("Unexpected event"),
3495 if messages_delivered >= 2 {
3496 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3497 check_added_monitors!(nodes[0], 1);
3498 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3500 if messages_delivered >= 3 {
3501 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3502 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3503 check_added_monitors!(nodes[1], 1);
3505 if messages_delivered >= 4 {
3506 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3507 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3508 // No commitment_signed so get_event_msg's assert(len == 1) passes
3509 check_added_monitors!(nodes[1], 1);
3511 if messages_delivered >= 5 {
3512 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3513 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3514 check_added_monitors!(nodes[0], 1);
3521 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3522 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3523 if messages_delivered < 2 {
3524 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3525 if messages_delivered < 1 {
3526 let events_4 = nodes[0].node.get_and_clear_pending_events();
3527 assert_eq!(events_4.len(), 1);
3529 Event::PaymentSent { ref payment_preimage } => {
3530 assert_eq!(payment_preimage_1, *payment_preimage);
3532 _ => panic!("Unexpected event"),
3535 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3537 } else if messages_delivered == 2 {
3538 // nodes[0] still wants its RAA + commitment_signed
3539 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3540 } else if messages_delivered == 3 {
3541 // nodes[0] still wants its commitment_signed
3542 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3543 } else if messages_delivered == 4 {
3544 // nodes[1] still wants its final RAA
3545 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3546 } else if messages_delivered == 5 {
3547 // Everything was delivered...
3548 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3551 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3552 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3553 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3555 // Channel should still work fine...
3556 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3557 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3558 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3559 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3560 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3561 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3565 fn test_drop_messages_peer_disconnect_a() {
3566 do_test_drop_messages_peer_disconnect(0, true);
3567 do_test_drop_messages_peer_disconnect(0, false);
3568 do_test_drop_messages_peer_disconnect(1, false);
3569 do_test_drop_messages_peer_disconnect(2, false);
3573 fn test_drop_messages_peer_disconnect_b() {
3574 do_test_drop_messages_peer_disconnect(3, false);
3575 do_test_drop_messages_peer_disconnect(4, false);
3576 do_test_drop_messages_peer_disconnect(5, false);
3577 do_test_drop_messages_peer_disconnect(6, false);
3581 fn test_funding_peer_disconnect() {
3582 // Test that we can lock in our funding tx while disconnected
3583 let chanmon_cfgs = create_chanmon_cfgs(2);
3584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3586 let persister: test_utils::TestPersister;
3587 let new_chain_monitor: test_utils::TestChainMonitor;
3588 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3589 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3590 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3592 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3593 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3595 confirm_transaction(&nodes[0], &tx);
3596 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3597 assert_eq!(events_1.len(), 1);
3599 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3600 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3602 _ => panic!("Unexpected event"),
3605 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3607 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3608 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3610 confirm_transaction(&nodes[1], &tx);
3611 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3612 assert_eq!(events_2.len(), 2);
3613 let funding_locked = match events_2[0] {
3614 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3615 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3618 _ => panic!("Unexpected event"),
3620 let bs_announcement_sigs = match events_2[1] {
3621 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3622 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3625 _ => panic!("Unexpected event"),
3628 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3630 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3631 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3632 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3633 assert_eq!(events_3.len(), 2);
3634 let as_announcement_sigs = match events_3[0] {
3635 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3636 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3639 _ => panic!("Unexpected event"),
3641 let (as_announcement, as_update) = match events_3[1] {
3642 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3643 (msg.clone(), update_msg.clone())
3645 _ => panic!("Unexpected event"),
3648 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3649 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3650 assert_eq!(events_4.len(), 1);
3651 let (_, bs_update) = match events_4[0] {
3652 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3653 (msg.clone(), update_msg.clone())
3655 _ => panic!("Unexpected event"),
3658 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3659 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3660 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3662 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3663 let logger = test_utils::TestLogger::new();
3664 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3665 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3666 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3668 // Check that after deserialization and reconnection we can still generate an identical
3669 // channel_announcement from the cached signatures.
3670 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3672 let nodes_0_serialized = nodes[0].node.encode();
3673 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3674 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3676 persister = test_utils::TestPersister::new();
3677 let keys_manager = &chanmon_cfgs[0].keys_manager;
3678 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);
3679 nodes[0].chain_monitor = &new_chain_monitor;
3680 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3681 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3682 &mut chan_0_monitor_read, keys_manager).unwrap();
3683 assert!(chan_0_monitor_read.is_empty());
3685 let mut nodes_0_read = &nodes_0_serialized[..];
3686 let (_, nodes_0_deserialized_tmp) = {
3687 let mut channel_monitors = HashMap::new();
3688 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3689 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3690 default_config: UserConfig::default(),
3692 fee_estimator: node_cfgs[0].fee_estimator,
3693 chain_monitor: nodes[0].chain_monitor,
3694 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3695 logger: nodes[0].logger,
3699 nodes_0_deserialized = nodes_0_deserialized_tmp;
3700 assert!(nodes_0_read.is_empty());
3702 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3703 nodes[0].node = &nodes_0_deserialized;
3704 check_added_monitors!(nodes[0], 1);
3706 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3708 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3709 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3710 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3711 let mut found_announcement = false;
3712 for event in msgs.iter() {
3714 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3715 if *msg == as_announcement { found_announcement = true; }
3717 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3718 _ => panic!("Unexpected event"),
3721 assert!(found_announcement);
3725 fn test_drop_messages_peer_disconnect_dual_htlc() {
3726 // Test that we can handle reconnecting when both sides of a channel have pending
3727 // commitment_updates when we disconnect.
3728 let chanmon_cfgs = create_chanmon_cfgs(2);
3729 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3730 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3731 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3732 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3733 let logger = test_utils::TestLogger::new();
3735 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3737 // Now try to send a second payment which will fail to send
3738 let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
3739 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3740 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3741 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3742 check_added_monitors!(nodes[0], 1);
3744 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3745 assert_eq!(events_1.len(), 1);
3747 MessageSendEvent::UpdateHTLCs { .. } => {},
3748 _ => panic!("Unexpected event"),
3751 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3752 check_added_monitors!(nodes[1], 1);
3754 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3755 assert_eq!(events_2.len(), 1);
3757 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 } } => {
3758 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3759 assert!(update_add_htlcs.is_empty());
3760 assert_eq!(update_fulfill_htlcs.len(), 1);
3761 assert!(update_fail_htlcs.is_empty());
3762 assert!(update_fail_malformed_htlcs.is_empty());
3763 assert!(update_fee.is_none());
3765 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3766 let events_3 = nodes[0].node.get_and_clear_pending_events();
3767 assert_eq!(events_3.len(), 1);
3769 Event::PaymentSent { ref payment_preimage } => {
3770 assert_eq!(*payment_preimage, payment_preimage_1);
3772 _ => panic!("Unexpected event"),
3775 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3776 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3777 // No commitment_signed so get_event_msg's assert(len == 1) passes
3778 check_added_monitors!(nodes[0], 1);
3780 _ => panic!("Unexpected event"),
3783 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3784 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3786 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3787 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3788 assert_eq!(reestablish_1.len(), 1);
3789 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3790 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3791 assert_eq!(reestablish_2.len(), 1);
3793 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3794 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3795 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3796 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3798 assert!(as_resp.0.is_none());
3799 assert!(bs_resp.0.is_none());
3801 assert!(bs_resp.1.is_none());
3802 assert!(bs_resp.2.is_none());
3804 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3806 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3807 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3808 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3809 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3810 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3811 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3812 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3813 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3814 // No commitment_signed so get_event_msg's assert(len == 1) passes
3815 check_added_monitors!(nodes[1], 1);
3817 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3818 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3819 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3820 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3821 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3822 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3823 assert!(bs_second_commitment_signed.update_fee.is_none());
3824 check_added_monitors!(nodes[1], 1);
3826 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3827 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3828 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3829 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3830 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3831 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3832 assert!(as_commitment_signed.update_fee.is_none());
3833 check_added_monitors!(nodes[0], 1);
3835 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3836 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3837 // No commitment_signed so get_event_msg's assert(len == 1) passes
3838 check_added_monitors!(nodes[0], 1);
3840 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3841 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3842 // No commitment_signed so get_event_msg's assert(len == 1) passes
3843 check_added_monitors!(nodes[1], 1);
3845 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3846 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3847 check_added_monitors!(nodes[1], 1);
3849 expect_pending_htlcs_forwardable!(nodes[1]);
3851 let events_5 = nodes[1].node.get_and_clear_pending_events();
3852 assert_eq!(events_5.len(), 1);
3854 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3855 assert_eq!(payment_hash_2, *payment_hash);
3857 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3858 assert!(payment_preimage.is_none());
3859 assert_eq!(payment_secret_2, *payment_secret);
3861 _ => panic!("expected PaymentPurpose::InvoicePayment")
3864 _ => panic!("Unexpected event"),
3867 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3868 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3869 check_added_monitors!(nodes[0], 1);
3871 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3874 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3875 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3876 // to avoid our counterparty failing the channel.
3877 let chanmon_cfgs = create_chanmon_cfgs(2);
3878 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3879 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3880 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3882 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3883 let logger = test_utils::TestLogger::new();
3885 let our_payment_hash = if send_partial_mpp {
3886 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3887 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3888 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
3889 // Use the utility function send_payment_along_path to send the payment with MPP data which
3890 // indicates there are more HTLCs coming.
3891 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.
3892 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, &None).unwrap();
3893 check_added_monitors!(nodes[0], 1);
3894 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3895 assert_eq!(events.len(), 1);
3896 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3897 // hop should *not* yet generate any PaymentReceived event(s).
3898 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3901 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3904 let mut block = Block {
3905 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3908 connect_block(&nodes[0], &block);
3909 connect_block(&nodes[1], &block);
3910 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3911 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3912 block.header.prev_blockhash = block.block_hash();
3913 connect_block(&nodes[0], &block);
3914 connect_block(&nodes[1], &block);
3917 expect_pending_htlcs_forwardable!(nodes[1]);
3919 check_added_monitors!(nodes[1], 1);
3920 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3921 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3922 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3923 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3924 assert!(htlc_timeout_updates.update_fee.is_none());
3926 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3927 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3928 // 100_000 msat as u64, followed by the height at which we failed back above
3929 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3930 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3931 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3935 fn test_htlc_timeout() {
3936 do_test_htlc_timeout(true);
3937 do_test_htlc_timeout(false);
3940 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3941 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3942 let chanmon_cfgs = create_chanmon_cfgs(3);
3943 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3944 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3945 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3946 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3947 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3949 // Make sure all nodes are at the same starting height
3950 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3951 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3952 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3954 let logger = test_utils::TestLogger::new();
3956 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3957 let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3959 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3960 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3961 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3963 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3964 check_added_monitors!(nodes[1], 1);
3966 // Now attempt to route a second payment, which should be placed in the holding cell
3967 let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3969 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3970 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3971 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
3972 check_added_monitors!(nodes[0], 1);
3973 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3974 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3975 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3976 expect_pending_htlcs_forwardable!(nodes[1]);
3977 check_added_monitors!(nodes[1], 0);
3979 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3980 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3981 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3982 check_added_monitors!(nodes[1], 0);
3985 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3986 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3987 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3988 connect_blocks(&nodes[1], 1);
3991 expect_pending_htlcs_forwardable!(nodes[1]);
3992 check_added_monitors!(nodes[1], 1);
3993 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3994 assert_eq!(fail_commit.len(), 1);
3995 match fail_commit[0] {
3996 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3997 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3998 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4000 _ => unreachable!(),
4002 expect_payment_failed!(nodes[0], second_payment_hash, false);
4003 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, false);
4005 expect_payment_failed!(nodes[1], second_payment_hash, true);
4010 fn test_holding_cell_htlc_add_timeouts() {
4011 do_test_holding_cell_htlc_add_timeouts(false);
4012 do_test_holding_cell_htlc_add_timeouts(true);
4016 fn test_invalid_channel_announcement() {
4017 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4018 let secp_ctx = Secp256k1::new();
4019 let chanmon_cfgs = create_chanmon_cfgs(2);
4020 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4021 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4022 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4024 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4026 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4027 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4028 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4029 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4031 nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4033 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4034 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4036 let as_network_key = nodes[0].node.get_our_node_id();
4037 let bs_network_key = nodes[1].node.get_our_node_id();
4039 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4041 let mut chan_announcement;
4043 macro_rules! dummy_unsigned_msg {
4045 msgs::UnsignedChannelAnnouncement {
4046 features: ChannelFeatures::known(),
4047 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4048 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4049 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4050 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4051 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4052 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4053 excess_data: Vec::new(),
4058 macro_rules! sign_msg {
4059 ($unsigned_msg: expr) => {
4060 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4061 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4062 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4063 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4064 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4065 chan_announcement = msgs::ChannelAnnouncement {
4066 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4067 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4068 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4069 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4070 contents: $unsigned_msg
4075 let unsigned_msg = dummy_unsigned_msg!();
4076 sign_msg!(unsigned_msg);
4077 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4078 let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4080 // Configured with Network::Testnet
4081 let mut unsigned_msg = dummy_unsigned_msg!();
4082 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4083 sign_msg!(unsigned_msg);
4084 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4086 let mut unsigned_msg = dummy_unsigned_msg!();
4087 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4088 sign_msg!(unsigned_msg);
4089 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4093 fn test_no_txn_manager_serialize_deserialize() {
4094 let chanmon_cfgs = create_chanmon_cfgs(2);
4095 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4096 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4097 let logger: test_utils::TestLogger;
4098 let fee_estimator: test_utils::TestFeeEstimator;
4099 let persister: test_utils::TestPersister;
4100 let new_chain_monitor: test_utils::TestChainMonitor;
4101 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4102 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4104 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4106 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4108 let nodes_0_serialized = nodes[0].node.encode();
4109 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4110 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4112 logger = test_utils::TestLogger::new();
4113 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4114 persister = test_utils::TestPersister::new();
4115 let keys_manager = &chanmon_cfgs[0].keys_manager;
4116 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4117 nodes[0].chain_monitor = &new_chain_monitor;
4118 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4119 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4120 &mut chan_0_monitor_read, keys_manager).unwrap();
4121 assert!(chan_0_monitor_read.is_empty());
4123 let mut nodes_0_read = &nodes_0_serialized[..];
4124 let config = UserConfig::default();
4125 let (_, nodes_0_deserialized_tmp) = {
4126 let mut channel_monitors = HashMap::new();
4127 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4128 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4129 default_config: config,
4131 fee_estimator: &fee_estimator,
4132 chain_monitor: nodes[0].chain_monitor,
4133 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4138 nodes_0_deserialized = nodes_0_deserialized_tmp;
4139 assert!(nodes_0_read.is_empty());
4141 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4142 nodes[0].node = &nodes_0_deserialized;
4143 assert_eq!(nodes[0].node.list_channels().len(), 1);
4144 check_added_monitors!(nodes[0], 1);
4146 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4147 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4148 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4149 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4151 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4152 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4153 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4154 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4156 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4157 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4158 for node in nodes.iter() {
4159 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4160 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4161 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4164 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4168 fn test_dup_htlc_onchain_fails_on_reload() {
4169 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4170 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4171 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4172 // the ChannelMonitor tells it to.
4174 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4175 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4176 // PaymentFailed event appearing). However, because we may not serialize the relevant
4177 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4178 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4179 // and de-duplicates ChannelMonitor events.
4181 // This tests that explicit tracking behavior.
4182 let chanmon_cfgs = create_chanmon_cfgs(2);
4183 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4184 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4185 let persister: test_utils::TestPersister;
4186 let new_chain_monitor: test_utils::TestChainMonitor;
4187 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4188 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4190 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4192 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4194 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4195 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4196 check_closed_broadcast!(nodes[0], true);
4197 check_added_monitors!(nodes[0], 1);
4199 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4200 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4202 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4203 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4204 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4205 assert_eq!(node_txn.len(), 3);
4206 assert_eq!(node_txn[0], node_txn[1]);
4208 assert!(nodes[1].node.claim_funds(payment_preimage));
4209 check_added_monitors!(nodes[1], 1);
4211 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4212 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4213 check_closed_broadcast!(nodes[1], true);
4214 check_added_monitors!(nodes[1], 1);
4215 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4217 header.prev_blockhash = nodes[0].best_block_hash();
4218 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4220 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4221 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4222 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4223 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4224 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4226 header.prev_blockhash = nodes[0].best_block_hash();
4227 let claim_block = Block { header, txdata: claim_txn};
4228 connect_block(&nodes[0], &claim_block);
4229 expect_payment_sent!(nodes[0], payment_preimage);
4231 // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4232 // connected a highly-relevant block, it likely gets serialized out now.
4233 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4234 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4236 // Now reload nodes[0]...
4237 persister = test_utils::TestPersister::new();
4238 let keys_manager = &chanmon_cfgs[0].keys_manager;
4239 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);
4240 nodes[0].chain_monitor = &new_chain_monitor;
4241 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4242 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4243 &mut chan_0_monitor_read, keys_manager).unwrap();
4244 assert!(chan_0_monitor_read.is_empty());
4246 let (_, nodes_0_deserialized_tmp) = {
4247 let mut channel_monitors = HashMap::new();
4248 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4249 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4250 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4251 default_config: Default::default(),
4253 fee_estimator: node_cfgs[0].fee_estimator,
4254 chain_monitor: nodes[0].chain_monitor,
4255 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4256 logger: nodes[0].logger,
4260 nodes_0_deserialized = nodes_0_deserialized_tmp;
4262 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4263 check_added_monitors!(nodes[0], 1);
4264 nodes[0].node = &nodes_0_deserialized;
4266 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4267 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4268 // payment events should kick in, leaving us with no pending events here.
4269 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4270 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4271 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4275 fn test_manager_serialize_deserialize_events() {
4276 // This test makes sure the events field in ChannelManager survives de/serialization
4277 let chanmon_cfgs = create_chanmon_cfgs(2);
4278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4280 let fee_estimator: test_utils::TestFeeEstimator;
4281 let persister: test_utils::TestPersister;
4282 let logger: test_utils::TestLogger;
4283 let new_chain_monitor: test_utils::TestChainMonitor;
4284 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4285 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4287 // Start creating a channel, but stop right before broadcasting the funding transaction
4288 let channel_value = 100000;
4289 let push_msat = 10001;
4290 let a_flags = InitFeatures::known();
4291 let b_flags = InitFeatures::known();
4292 let node_a = nodes.remove(0);
4293 let node_b = nodes.remove(0);
4294 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4295 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()));
4296 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()));
4298 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4300 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4301 check_added_monitors!(node_a, 0);
4303 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()));
4305 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4306 assert_eq!(added_monitors.len(), 1);
4307 assert_eq!(added_monitors[0].0, funding_output);
4308 added_monitors.clear();
4311 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4313 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4314 assert_eq!(added_monitors.len(), 1);
4315 assert_eq!(added_monitors[0].0, funding_output);
4316 added_monitors.clear();
4318 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4323 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4324 let nodes_0_serialized = nodes[0].node.encode();
4325 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4326 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4328 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4329 logger = test_utils::TestLogger::new();
4330 persister = test_utils::TestPersister::new();
4331 let keys_manager = &chanmon_cfgs[0].keys_manager;
4332 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4333 nodes[0].chain_monitor = &new_chain_monitor;
4334 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4335 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4336 &mut chan_0_monitor_read, keys_manager).unwrap();
4337 assert!(chan_0_monitor_read.is_empty());
4339 let mut nodes_0_read = &nodes_0_serialized[..];
4340 let config = UserConfig::default();
4341 let (_, nodes_0_deserialized_tmp) = {
4342 let mut channel_monitors = HashMap::new();
4343 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4344 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4345 default_config: config,
4347 fee_estimator: &fee_estimator,
4348 chain_monitor: nodes[0].chain_monitor,
4349 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4354 nodes_0_deserialized = nodes_0_deserialized_tmp;
4355 assert!(nodes_0_read.is_empty());
4357 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4359 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4360 nodes[0].node = &nodes_0_deserialized;
4362 // After deserializing, make sure the funding_transaction is still held by the channel manager
4363 let events_4 = nodes[0].node.get_and_clear_pending_events();
4364 assert_eq!(events_4.len(), 0);
4365 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4366 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4368 // Make sure the channel is functioning as though the de/serialization never happened
4369 assert_eq!(nodes[0].node.list_channels().len(), 1);
4370 check_added_monitors!(nodes[0], 1);
4372 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4373 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4374 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4375 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4377 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4378 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4379 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4380 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4382 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4383 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4384 for node in nodes.iter() {
4385 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4386 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4387 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4390 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4394 fn test_simple_manager_serialize_deserialize() {
4395 let chanmon_cfgs = create_chanmon_cfgs(2);
4396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4398 let logger: test_utils::TestLogger;
4399 let fee_estimator: test_utils::TestFeeEstimator;
4400 let persister: test_utils::TestPersister;
4401 let new_chain_monitor: test_utils::TestChainMonitor;
4402 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4403 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4404 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4406 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4407 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4409 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4411 let nodes_0_serialized = nodes[0].node.encode();
4412 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4413 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4415 logger = test_utils::TestLogger::new();
4416 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4417 persister = test_utils::TestPersister::new();
4418 let keys_manager = &chanmon_cfgs[0].keys_manager;
4419 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4420 nodes[0].chain_monitor = &new_chain_monitor;
4421 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4422 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4423 &mut chan_0_monitor_read, keys_manager).unwrap();
4424 assert!(chan_0_monitor_read.is_empty());
4426 let mut nodes_0_read = &nodes_0_serialized[..];
4427 let (_, nodes_0_deserialized_tmp) = {
4428 let mut channel_monitors = HashMap::new();
4429 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4430 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4431 default_config: UserConfig::default(),
4433 fee_estimator: &fee_estimator,
4434 chain_monitor: nodes[0].chain_monitor,
4435 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4440 nodes_0_deserialized = nodes_0_deserialized_tmp;
4441 assert!(nodes_0_read.is_empty());
4443 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4444 nodes[0].node = &nodes_0_deserialized;
4445 check_added_monitors!(nodes[0], 1);
4447 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4449 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4450 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4454 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4455 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4456 let chanmon_cfgs = create_chanmon_cfgs(4);
4457 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4458 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4459 let logger: test_utils::TestLogger;
4460 let fee_estimator: test_utils::TestFeeEstimator;
4461 let persister: test_utils::TestPersister;
4462 let new_chain_monitor: test_utils::TestChainMonitor;
4463 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4464 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4465 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4466 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4467 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4469 let mut node_0_stale_monitors_serialized = Vec::new();
4470 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4471 let mut writer = test_utils::TestVecWriter(Vec::new());
4472 monitor.1.write(&mut writer).unwrap();
4473 node_0_stale_monitors_serialized.push(writer.0);
4476 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4478 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4479 let nodes_0_serialized = nodes[0].node.encode();
4481 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4482 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4483 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4484 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4486 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4488 let mut node_0_monitors_serialized = Vec::new();
4489 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4490 let mut writer = test_utils::TestVecWriter(Vec::new());
4491 monitor.1.write(&mut writer).unwrap();
4492 node_0_monitors_serialized.push(writer.0);
4495 logger = test_utils::TestLogger::new();
4496 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4497 persister = test_utils::TestPersister::new();
4498 let keys_manager = &chanmon_cfgs[0].keys_manager;
4499 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4500 nodes[0].chain_monitor = &new_chain_monitor;
4503 let mut node_0_stale_monitors = Vec::new();
4504 for serialized in node_0_stale_monitors_serialized.iter() {
4505 let mut read = &serialized[..];
4506 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4507 assert!(read.is_empty());
4508 node_0_stale_monitors.push(monitor);
4511 let mut node_0_monitors = Vec::new();
4512 for serialized in node_0_monitors_serialized.iter() {
4513 let mut read = &serialized[..];
4514 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4515 assert!(read.is_empty());
4516 node_0_monitors.push(monitor);
4519 let mut nodes_0_read = &nodes_0_serialized[..];
4520 if let Err(msgs::DecodeError::InvalidValue) =
4521 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4522 default_config: UserConfig::default(),
4524 fee_estimator: &fee_estimator,
4525 chain_monitor: nodes[0].chain_monitor,
4526 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4528 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4530 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4533 let mut nodes_0_read = &nodes_0_serialized[..];
4534 let (_, nodes_0_deserialized_tmp) =
4535 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4536 default_config: UserConfig::default(),
4538 fee_estimator: &fee_estimator,
4539 chain_monitor: nodes[0].chain_monitor,
4540 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4542 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4544 nodes_0_deserialized = nodes_0_deserialized_tmp;
4545 assert!(nodes_0_read.is_empty());
4547 { // Channel close should result in a commitment tx
4548 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4549 assert_eq!(txn.len(), 1);
4550 check_spends!(txn[0], funding_tx);
4551 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4554 for monitor in node_0_monitors.drain(..) {
4555 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4556 check_added_monitors!(nodes[0], 1);
4558 nodes[0].node = &nodes_0_deserialized;
4560 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4561 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4562 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4563 //... and we can even still claim the payment!
4564 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4566 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4567 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4568 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4569 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4570 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4571 assert_eq!(msg_events.len(), 1);
4572 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4574 &ErrorAction::SendErrorMessage { ref msg } => {
4575 assert_eq!(msg.channel_id, channel_id);
4577 _ => panic!("Unexpected event!"),
4582 macro_rules! check_spendable_outputs {
4583 ($node: expr, $keysinterface: expr) => {
4585 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4586 let mut txn = Vec::new();
4587 let mut all_outputs = Vec::new();
4588 let secp_ctx = Secp256k1::new();
4589 for event in events.drain(..) {
4591 Event::SpendableOutputs { mut outputs } => {
4592 for outp in outputs.drain(..) {
4593 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4594 all_outputs.push(outp);
4597 _ => panic!("Unexpected event"),
4600 if all_outputs.len() > 1 {
4601 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) {
4611 fn test_claim_sizeable_push_msat() {
4612 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4613 let chanmon_cfgs = create_chanmon_cfgs(2);
4614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4616 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4618 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4619 nodes[1].node.force_close_channel(&chan.2).unwrap();
4620 check_closed_broadcast!(nodes[1], true);
4621 check_added_monitors!(nodes[1], 1);
4622 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4623 assert_eq!(node_txn.len(), 1);
4624 check_spends!(node_txn[0], chan.3);
4625 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
4627 mine_transaction(&nodes[1], &node_txn[0]);
4628 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4630 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4631 assert_eq!(spend_txn.len(), 1);
4632 assert_eq!(spend_txn[0].input.len(), 1);
4633 check_spends!(spend_txn[0], node_txn[0]);
4634 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4638 fn test_claim_on_remote_sizeable_push_msat() {
4639 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4640 // to_remote output is encumbered by a P2WPKH
4641 let chanmon_cfgs = create_chanmon_cfgs(2);
4642 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4643 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4644 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4646 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4647 nodes[0].node.force_close_channel(&chan.2).unwrap();
4648 check_closed_broadcast!(nodes[0], true);
4649 check_added_monitors!(nodes[0], 1);
4651 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4652 assert_eq!(node_txn.len(), 1);
4653 check_spends!(node_txn[0], chan.3);
4654 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
4656 mine_transaction(&nodes[1], &node_txn[0]);
4657 check_closed_broadcast!(nodes[1], true);
4658 check_added_monitors!(nodes[1], 1);
4659 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4661 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4662 assert_eq!(spend_txn.len(), 1);
4663 check_spends!(spend_txn[0], node_txn[0]);
4667 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4668 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4669 // to_remote output is encumbered by a P2WPKH
4671 let chanmon_cfgs = create_chanmon_cfgs(2);
4672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4674 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4676 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4677 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4678 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4679 assert_eq!(revoked_local_txn[0].input.len(), 1);
4680 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4682 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4683 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4684 check_closed_broadcast!(nodes[1], true);
4685 check_added_monitors!(nodes[1], 1);
4687 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4688 mine_transaction(&nodes[1], &node_txn[0]);
4689 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4691 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4692 assert_eq!(spend_txn.len(), 3);
4693 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4694 check_spends!(spend_txn[1], node_txn[0]);
4695 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4699 fn test_static_spendable_outputs_preimage_tx() {
4700 let chanmon_cfgs = create_chanmon_cfgs(2);
4701 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4702 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4703 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4705 // Create some initial channels
4706 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4708 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4710 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4711 assert_eq!(commitment_tx[0].input.len(), 1);
4712 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4714 // Settle A's commitment tx on B's chain
4715 assert!(nodes[1].node.claim_funds(payment_preimage));
4716 check_added_monitors!(nodes[1], 1);
4717 mine_transaction(&nodes[1], &commitment_tx[0]);
4718 check_added_monitors!(nodes[1], 1);
4719 let events = nodes[1].node.get_and_clear_pending_msg_events();
4721 MessageSendEvent::UpdateHTLCs { .. } => {},
4722 _ => panic!("Unexpected event"),
4725 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4726 _ => panic!("Unexepected event"),
4729 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4730 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4731 assert_eq!(node_txn.len(), 3);
4732 check_spends!(node_txn[0], commitment_tx[0]);
4733 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4734 check_spends!(node_txn[1], chan_1.3);
4735 check_spends!(node_txn[2], node_txn[1]);
4737 mine_transaction(&nodes[1], &node_txn[0]);
4738 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4740 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4741 assert_eq!(spend_txn.len(), 1);
4742 check_spends!(spend_txn[0], node_txn[0]);
4746 fn test_static_spendable_outputs_timeout_tx() {
4747 let chanmon_cfgs = create_chanmon_cfgs(2);
4748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4750 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4752 // Create some initial channels
4753 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4755 // Rebalance the network a bit by relaying one payment through all the channels ...
4756 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4758 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4760 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4761 assert_eq!(commitment_tx[0].input.len(), 1);
4762 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4764 // Settle A's commitment tx on B' chain
4765 mine_transaction(&nodes[1], &commitment_tx[0]);
4766 check_added_monitors!(nodes[1], 1);
4767 let events = nodes[1].node.get_and_clear_pending_msg_events();
4769 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4770 _ => panic!("Unexpected event"),
4772 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4774 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4775 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4776 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4777 check_spends!(node_txn[0], chan_1.3.clone());
4778 check_spends!(node_txn[1], commitment_tx[0].clone());
4779 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4781 mine_transaction(&nodes[1], &node_txn[1]);
4782 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4783 expect_payment_failed!(nodes[1], our_payment_hash, true);
4785 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4786 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4787 check_spends!(spend_txn[0], commitment_tx[0]);
4788 check_spends!(spend_txn[1], node_txn[1]);
4789 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4793 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4794 let chanmon_cfgs = create_chanmon_cfgs(2);
4795 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4796 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4797 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4799 // Create some initial channels
4800 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4802 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4803 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4804 assert_eq!(revoked_local_txn[0].input.len(), 1);
4805 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4807 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4809 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4810 check_closed_broadcast!(nodes[1], true);
4811 check_added_monitors!(nodes[1], 1);
4813 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4814 assert_eq!(node_txn.len(), 2);
4815 assert_eq!(node_txn[0].input.len(), 2);
4816 check_spends!(node_txn[0], revoked_local_txn[0]);
4818 mine_transaction(&nodes[1], &node_txn[0]);
4819 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4821 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4822 assert_eq!(spend_txn.len(), 1);
4823 check_spends!(spend_txn[0], node_txn[0]);
4827 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4828 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4829 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4834 // Create some initial channels
4835 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4837 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4838 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4839 assert_eq!(revoked_local_txn[0].input.len(), 1);
4840 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4842 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4844 // A will generate HTLC-Timeout from revoked commitment tx
4845 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4846 check_closed_broadcast!(nodes[0], true);
4847 check_added_monitors!(nodes[0], 1);
4848 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4850 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4851 assert_eq!(revoked_htlc_txn.len(), 2);
4852 check_spends!(revoked_htlc_txn[0], chan_1.3);
4853 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4854 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4855 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4856 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4858 // B will generate justice tx from A's revoked commitment/HTLC tx
4859 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4860 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4861 check_closed_broadcast!(nodes[1], true);
4862 check_added_monitors!(nodes[1], 1);
4864 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4865 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4866 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4867 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4868 // transactions next...
4869 assert_eq!(node_txn[0].input.len(), 3);
4870 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4872 assert_eq!(node_txn[1].input.len(), 2);
4873 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4874 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4875 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4877 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4878 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4881 assert_eq!(node_txn[2].input.len(), 1);
4882 check_spends!(node_txn[2], chan_1.3);
4884 mine_transaction(&nodes[1], &node_txn[1]);
4885 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4887 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4888 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4889 assert_eq!(spend_txn.len(), 1);
4890 assert_eq!(spend_txn[0].input.len(), 1);
4891 check_spends!(spend_txn[0], node_txn[1]);
4895 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4896 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4897 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4898 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4899 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4900 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4902 // Create some initial channels
4903 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4905 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4906 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4907 assert_eq!(revoked_local_txn[0].input.len(), 1);
4908 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4910 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4911 assert_eq!(revoked_local_txn[0].output.len(), 2);
4913 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4915 // B will generate HTLC-Success from revoked commitment tx
4916 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4917 check_closed_broadcast!(nodes[1], true);
4918 check_added_monitors!(nodes[1], 1);
4919 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4921 assert_eq!(revoked_htlc_txn.len(), 2);
4922 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4923 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4924 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4926 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4927 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4928 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4930 // A will generate justice tx from B's revoked commitment/HTLC tx
4931 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4932 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4933 check_closed_broadcast!(nodes[0], true);
4934 check_added_monitors!(nodes[0], 1);
4936 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4937 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4939 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4940 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4941 // transactions next...
4942 assert_eq!(node_txn[0].input.len(), 2);
4943 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4944 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4945 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4947 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4948 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4951 assert_eq!(node_txn[1].input.len(), 1);
4952 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4954 check_spends!(node_txn[2], chan_1.3);
4956 mine_transaction(&nodes[0], &node_txn[1]);
4957 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4959 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4960 // didn't try to generate any new transactions.
4962 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4963 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4964 assert_eq!(spend_txn.len(), 3);
4965 assert_eq!(spend_txn[0].input.len(), 1);
4966 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4967 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4968 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4969 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4973 fn test_onchain_to_onchain_claim() {
4974 // Test that in case of channel closure, we detect the state of output and claim HTLC
4975 // on downstream peer's remote commitment tx.
4976 // First, have C claim an HTLC against its own latest commitment transaction.
4977 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4979 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4982 let chanmon_cfgs = create_chanmon_cfgs(3);
4983 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4984 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4985 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4987 // Create some initial channels
4988 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4989 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4991 // Ensure all nodes are at the same height
4992 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4993 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4994 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4995 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4997 // Rebalance the network a bit by relaying one payment through all the channels ...
4998 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4999 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5001 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5002 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5003 check_spends!(commitment_tx[0], chan_2.3);
5004 nodes[2].node.claim_funds(payment_preimage);
5005 check_added_monitors!(nodes[2], 1);
5006 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5007 assert!(updates.update_add_htlcs.is_empty());
5008 assert!(updates.update_fail_htlcs.is_empty());
5009 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5010 assert!(updates.update_fail_malformed_htlcs.is_empty());
5012 mine_transaction(&nodes[2], &commitment_tx[0]);
5013 check_closed_broadcast!(nodes[2], true);
5014 check_added_monitors!(nodes[2], 1);
5016 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5017 assert_eq!(c_txn.len(), 3);
5018 assert_eq!(c_txn[0], c_txn[2]);
5019 assert_eq!(commitment_tx[0], c_txn[1]);
5020 check_spends!(c_txn[1], chan_2.3);
5021 check_spends!(c_txn[2], c_txn[1]);
5022 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5023 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5024 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5025 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5027 // 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
5028 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5029 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5030 check_added_monitors!(nodes[1], 1);
5031 expect_payment_forwarded!(nodes[1], Some(1000), true);
5033 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5034 // ChannelMonitor: claim tx
5035 assert_eq!(b_txn.len(), 1);
5036 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5039 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5040 assert_eq!(msg_events.len(), 3);
5041 check_added_monitors!(nodes[1], 1);
5042 match msg_events[0] {
5043 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5044 _ => panic!("Unexpected event"),
5046 match msg_events[1] {
5047 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5048 _ => panic!("Unexpected event"),
5050 match msg_events[2] {
5051 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, .. } } => {
5052 assert!(update_add_htlcs.is_empty());
5053 assert!(update_fail_htlcs.is_empty());
5054 assert_eq!(update_fulfill_htlcs.len(), 1);
5055 assert!(update_fail_malformed_htlcs.is_empty());
5056 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5058 _ => panic!("Unexpected event"),
5060 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5061 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5062 mine_transaction(&nodes[1], &commitment_tx[0]);
5063 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5064 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5065 assert_eq!(b_txn.len(), 3);
5066 check_spends!(b_txn[1], chan_1.3);
5067 check_spends!(b_txn[2], b_txn[1]);
5068 check_spends!(b_txn[0], commitment_tx[0]);
5069 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5070 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5071 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5073 check_closed_broadcast!(nodes[1], true);
5074 check_added_monitors!(nodes[1], 1);
5078 fn test_duplicate_payment_hash_one_failure_one_success() {
5079 // Topology : A --> B --> C --> D
5080 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5081 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5082 // we forward one of the payments onwards to D.
5083 let chanmon_cfgs = create_chanmon_cfgs(4);
5084 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5085 // When this test was written, the default base fee floated based on the HTLC count.
5086 // It is now fixed, so we simply set the fee to the expected value here.
5087 let mut config = test_default_channel_config();
5088 config.channel_options.forwarding_fee_base_msat = 196;
5089 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5090 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5091 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5093 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5094 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5095 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5097 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5098 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5099 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5100 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5101 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5103 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5105 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5106 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5107 // script push size limit so that the below script length checks match
5108 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5109 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
5110 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5111 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5113 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5114 assert_eq!(commitment_txn[0].input.len(), 1);
5115 check_spends!(commitment_txn[0], chan_2.3);
5117 mine_transaction(&nodes[1], &commitment_txn[0]);
5118 check_closed_broadcast!(nodes[1], true);
5119 check_added_monitors!(nodes[1], 1);
5120 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5122 let htlc_timeout_tx;
5123 { // Extract one of the two HTLC-Timeout transaction
5124 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5125 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5126 assert_eq!(node_txn.len(), 4);
5127 check_spends!(node_txn[0], chan_2.3);
5129 check_spends!(node_txn[1], commitment_txn[0]);
5130 assert_eq!(node_txn[1].input.len(), 1);
5131 check_spends!(node_txn[2], commitment_txn[0]);
5132 assert_eq!(node_txn[2].input.len(), 1);
5133 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5134 check_spends!(node_txn[3], commitment_txn[0]);
5135 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5137 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5138 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5139 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5140 htlc_timeout_tx = node_txn[1].clone();
5143 nodes[2].node.claim_funds(our_payment_preimage);
5144 mine_transaction(&nodes[2], &commitment_txn[0]);
5145 check_added_monitors!(nodes[2], 2);
5146 let events = nodes[2].node.get_and_clear_pending_msg_events();
5148 MessageSendEvent::UpdateHTLCs { .. } => {},
5149 _ => panic!("Unexpected event"),
5152 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5153 _ => panic!("Unexepected event"),
5155 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5156 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)
5157 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5158 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5159 assert_eq!(htlc_success_txn[0].input.len(), 1);
5160 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5161 assert_eq!(htlc_success_txn[1].input.len(), 1);
5162 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5163 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5164 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5165 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5166 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5167 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5169 mine_transaction(&nodes[1], &htlc_timeout_tx);
5170 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5171 expect_pending_htlcs_forwardable!(nodes[1]);
5172 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5173 assert!(htlc_updates.update_add_htlcs.is_empty());
5174 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5175 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5176 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5177 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5178 check_added_monitors!(nodes[1], 1);
5180 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5181 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5183 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5184 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, true);
5186 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5188 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5189 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5190 // and nodes[2] fee) is rounded down and then claimed in full.
5191 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5192 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5193 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5194 assert!(updates.update_add_htlcs.is_empty());
5195 assert!(updates.update_fail_htlcs.is_empty());
5196 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5197 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5198 assert!(updates.update_fail_malformed_htlcs.is_empty());
5199 check_added_monitors!(nodes[1], 1);
5201 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5202 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5204 let events = nodes[0].node.get_and_clear_pending_events();
5206 Event::PaymentSent { ref payment_preimage } => {
5207 assert_eq!(*payment_preimage, our_payment_preimage);
5209 _ => panic!("Unexpected event"),
5214 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5215 let chanmon_cfgs = create_chanmon_cfgs(2);
5216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5218 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5220 // Create some initial channels
5221 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5223 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5224 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5225 assert_eq!(local_txn.len(), 1);
5226 assert_eq!(local_txn[0].input.len(), 1);
5227 check_spends!(local_txn[0], chan_1.3);
5229 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5230 nodes[1].node.claim_funds(payment_preimage);
5231 check_added_monitors!(nodes[1], 1);
5232 mine_transaction(&nodes[1], &local_txn[0]);
5233 check_added_monitors!(nodes[1], 1);
5234 let events = nodes[1].node.get_and_clear_pending_msg_events();
5236 MessageSendEvent::UpdateHTLCs { .. } => {},
5237 _ => panic!("Unexpected event"),
5240 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5241 _ => panic!("Unexepected event"),
5244 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5245 assert_eq!(node_txn.len(), 3);
5246 assert_eq!(node_txn[0], node_txn[2]);
5247 assert_eq!(node_txn[1], local_txn[0]);
5248 assert_eq!(node_txn[0].input.len(), 1);
5249 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5250 check_spends!(node_txn[0], local_txn[0]);
5254 mine_transaction(&nodes[1], &node_tx);
5255 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5257 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5258 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5259 assert_eq!(spend_txn.len(), 1);
5260 assert_eq!(spend_txn[0].input.len(), 1);
5261 check_spends!(spend_txn[0], node_tx);
5262 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5265 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5266 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5267 // unrevoked commitment transaction.
5268 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5269 // a remote RAA before they could be failed backwards (and combinations thereof).
5270 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5271 // use the same payment hashes.
5272 // Thus, we use a six-node network:
5277 // And test where C fails back to A/B when D announces its latest commitment transaction
5278 let chanmon_cfgs = create_chanmon_cfgs(6);
5279 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5280 // When this test was written, the default base fee floated based on the HTLC count.
5281 // It is now fixed, so we simply set the fee to the expected value here.
5282 let mut config = test_default_channel_config();
5283 config.channel_options.forwarding_fee_base_msat = 196;
5284 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5285 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5286 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5287 let logger = test_utils::TestLogger::new();
5289 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5290 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5291 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5292 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5293 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5295 // Rebalance and check output sanity...
5296 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5297 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5298 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5300 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5302 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
5304 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
5305 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5306 let our_node_id = &nodes[1].node.get_our_node_id();
5307 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5309 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, 0).unwrap()); // not added < dust limit + HTLC tx fee
5311 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, 0).unwrap()); // not added < dust limit + HTLC tx fee
5313 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5315 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5316 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5318 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, 0).unwrap());
5320 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, 0).unwrap());
5323 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5325 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5326 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, 0).unwrap()); // not added < dust limit + HTLC tx fee
5329 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
5331 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5332 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, 0).unwrap());
5334 // Double-check that six of the new HTLC were added
5335 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5336 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5337 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5338 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5340 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5341 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5342 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5343 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5344 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5345 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5346 check_added_monitors!(nodes[4], 0);
5347 expect_pending_htlcs_forwardable!(nodes[4]);
5348 check_added_monitors!(nodes[4], 1);
5350 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5351 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5352 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5353 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5354 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5355 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5357 // Fail 3rd below-dust and 7th above-dust HTLCs
5358 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5359 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5360 check_added_monitors!(nodes[5], 0);
5361 expect_pending_htlcs_forwardable!(nodes[5]);
5362 check_added_monitors!(nodes[5], 1);
5364 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5365 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5366 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5367 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5369 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5371 expect_pending_htlcs_forwardable!(nodes[3]);
5372 check_added_monitors!(nodes[3], 1);
5373 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5374 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5375 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5376 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5377 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5378 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5379 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5380 if deliver_last_raa {
5381 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5383 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5386 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5387 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5388 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5389 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5391 // We now broadcast the latest commitment transaction, which *should* result in failures for
5392 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5393 // the non-broadcast above-dust HTLCs.
5395 // Alternatively, we may broadcast the previous commitment transaction, which should only
5396 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5397 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5399 if announce_latest {
5400 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5402 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5404 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5405 check_closed_broadcast!(nodes[2], true);
5406 expect_pending_htlcs_forwardable!(nodes[2]);
5407 check_added_monitors!(nodes[2], 3);
5409 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5410 assert_eq!(cs_msgs.len(), 2);
5411 let mut a_done = false;
5412 for msg in cs_msgs {
5414 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5415 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5416 // should be failed-backwards here.
5417 let target = if *node_id == nodes[0].node.get_our_node_id() {
5418 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5419 for htlc in &updates.update_fail_htlcs {
5420 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 });
5422 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5427 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5428 for htlc in &updates.update_fail_htlcs {
5429 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5431 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5432 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5435 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5436 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5437 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5438 if announce_latest {
5439 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5440 if *node_id == nodes[0].node.get_our_node_id() {
5441 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5444 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5446 _ => panic!("Unexpected event"),
5450 let as_events = nodes[0].node.get_and_clear_pending_events();
5451 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5452 let mut as_failds = HashSet::new();
5453 for event in as_events.iter() {
5454 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5455 assert!(as_failds.insert(*payment_hash));
5456 if *payment_hash != payment_hash_2 {
5457 assert_eq!(*rejected_by_dest, deliver_last_raa);
5459 assert!(!rejected_by_dest);
5461 } else { panic!("Unexpected event"); }
5463 assert!(as_failds.contains(&payment_hash_1));
5464 assert!(as_failds.contains(&payment_hash_2));
5465 if announce_latest {
5466 assert!(as_failds.contains(&payment_hash_3));
5467 assert!(as_failds.contains(&payment_hash_5));
5469 assert!(as_failds.contains(&payment_hash_6));
5471 let bs_events = nodes[1].node.get_and_clear_pending_events();
5472 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5473 let mut bs_failds = HashSet::new();
5474 for event in bs_events.iter() {
5475 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5476 assert!(bs_failds.insert(*payment_hash));
5477 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5478 assert_eq!(*rejected_by_dest, deliver_last_raa);
5480 assert!(!rejected_by_dest);
5482 } else { panic!("Unexpected event"); }
5484 assert!(bs_failds.contains(&payment_hash_1));
5485 assert!(bs_failds.contains(&payment_hash_2));
5486 if announce_latest {
5487 assert!(bs_failds.contains(&payment_hash_4));
5489 assert!(bs_failds.contains(&payment_hash_5));
5491 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5492 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5493 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5494 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5495 // PaymentFailureNetworkUpdates.
5496 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5497 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5498 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5499 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5500 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5502 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5503 _ => panic!("Unexpected event"),
5509 fn test_fail_backwards_latest_remote_announce_a() {
5510 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5514 fn test_fail_backwards_latest_remote_announce_b() {
5515 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5519 fn test_fail_backwards_previous_remote_announce() {
5520 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5521 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5522 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5526 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5527 let chanmon_cfgs = create_chanmon_cfgs(2);
5528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5532 // Create some initial channels
5533 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5535 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5536 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5537 assert_eq!(local_txn[0].input.len(), 1);
5538 check_spends!(local_txn[0], chan_1.3);
5540 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5541 mine_transaction(&nodes[0], &local_txn[0]);
5542 check_closed_broadcast!(nodes[0], true);
5543 check_added_monitors!(nodes[0], 1);
5544 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5546 let htlc_timeout = {
5547 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5548 assert_eq!(node_txn.len(), 2);
5549 check_spends!(node_txn[0], chan_1.3);
5550 assert_eq!(node_txn[1].input.len(), 1);
5551 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5552 check_spends!(node_txn[1], local_txn[0]);
5556 mine_transaction(&nodes[0], &htlc_timeout);
5557 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5558 expect_payment_failed!(nodes[0], our_payment_hash, true);
5560 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5561 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5562 assert_eq!(spend_txn.len(), 3);
5563 check_spends!(spend_txn[0], local_txn[0]);
5564 assert_eq!(spend_txn[1].input.len(), 1);
5565 check_spends!(spend_txn[1], htlc_timeout);
5566 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5567 assert_eq!(spend_txn[2].input.len(), 2);
5568 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5569 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5570 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5574 fn test_key_derivation_params() {
5575 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5576 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5577 // let us re-derive the channel key set to then derive a delayed_payment_key.
5579 let chanmon_cfgs = create_chanmon_cfgs(3);
5581 // We manually create the node configuration to backup the seed.
5582 let seed = [42; 32];
5583 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5584 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);
5585 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, node_seed: seed, features: InitFeatures::known() };
5586 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5587 node_cfgs.remove(0);
5588 node_cfgs.insert(0, node);
5590 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5591 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5593 // Create some initial channels
5594 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5596 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5597 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5598 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5600 // Ensure all nodes are at the same height
5601 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5602 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5603 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5604 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5606 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5607 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5608 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5609 assert_eq!(local_txn_1[0].input.len(), 1);
5610 check_spends!(local_txn_1[0], chan_1.3);
5612 // We check funding pubkey are unique
5613 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]));
5614 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]));
5615 if from_0_funding_key_0 == from_1_funding_key_0
5616 || from_0_funding_key_0 == from_1_funding_key_1
5617 || from_0_funding_key_1 == from_1_funding_key_0
5618 || from_0_funding_key_1 == from_1_funding_key_1 {
5619 panic!("Funding pubkeys aren't unique");
5622 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5623 mine_transaction(&nodes[0], &local_txn_1[0]);
5624 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5625 check_closed_broadcast!(nodes[0], true);
5626 check_added_monitors!(nodes[0], 1);
5628 let htlc_timeout = {
5629 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5630 assert_eq!(node_txn[1].input.len(), 1);
5631 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5632 check_spends!(node_txn[1], local_txn_1[0]);
5636 mine_transaction(&nodes[0], &htlc_timeout);
5637 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5638 expect_payment_failed!(nodes[0], our_payment_hash, true);
5640 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5641 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5642 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5643 assert_eq!(spend_txn.len(), 3);
5644 check_spends!(spend_txn[0], local_txn_1[0]);
5645 assert_eq!(spend_txn[1].input.len(), 1);
5646 check_spends!(spend_txn[1], htlc_timeout);
5647 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5648 assert_eq!(spend_txn[2].input.len(), 2);
5649 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5650 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5651 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5655 fn test_static_output_closing_tx() {
5656 let chanmon_cfgs = create_chanmon_cfgs(2);
5657 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5658 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5659 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5661 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5663 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5664 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5666 mine_transaction(&nodes[0], &closing_tx);
5667 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5669 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5670 assert_eq!(spend_txn.len(), 1);
5671 check_spends!(spend_txn[0], closing_tx);
5673 mine_transaction(&nodes[1], &closing_tx);
5674 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5676 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5677 assert_eq!(spend_txn.len(), 1);
5678 check_spends!(spend_txn[0], closing_tx);
5681 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5682 let chanmon_cfgs = create_chanmon_cfgs(2);
5683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5685 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5686 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5688 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5690 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5691 // present in B's local commitment transaction, but none of A's commitment transactions.
5692 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5693 check_added_monitors!(nodes[1], 1);
5695 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5696 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5697 let events = nodes[0].node.get_and_clear_pending_events();
5698 assert_eq!(events.len(), 1);
5700 Event::PaymentSent { payment_preimage } => {
5701 assert_eq!(payment_preimage, our_payment_preimage);
5703 _ => panic!("Unexpected event"),
5706 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5707 check_added_monitors!(nodes[0], 1);
5708 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5709 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5710 check_added_monitors!(nodes[1], 1);
5712 let starting_block = nodes[1].best_block_info();
5713 let mut block = Block {
5714 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5717 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5718 connect_block(&nodes[1], &block);
5719 block.header.prev_blockhash = block.block_hash();
5721 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5722 check_closed_broadcast!(nodes[1], true);
5723 check_added_monitors!(nodes[1], 1);
5726 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5727 let chanmon_cfgs = create_chanmon_cfgs(2);
5728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5731 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5732 let logger = test_utils::TestLogger::new();
5734 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
5735 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5736 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5737 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5738 check_added_monitors!(nodes[0], 1);
5740 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5742 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5743 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5744 // to "time out" the HTLC.
5746 let starting_block = nodes[1].best_block_info();
5747 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5749 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5750 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5751 header.prev_blockhash = header.block_hash();
5753 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5754 check_closed_broadcast!(nodes[0], true);
5755 check_added_monitors!(nodes[0], 1);
5758 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5759 let chanmon_cfgs = create_chanmon_cfgs(3);
5760 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5761 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5762 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5763 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5765 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5766 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5767 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5768 // actually revoked.
5769 let htlc_value = if use_dust { 50000 } else { 3000000 };
5770 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5771 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5772 expect_pending_htlcs_forwardable!(nodes[1]);
5773 check_added_monitors!(nodes[1], 1);
5775 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5776 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5777 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5778 check_added_monitors!(nodes[0], 1);
5779 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5780 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5781 check_added_monitors!(nodes[1], 1);
5782 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5783 check_added_monitors!(nodes[1], 1);
5784 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5786 if check_revoke_no_close {
5787 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5788 check_added_monitors!(nodes[0], 1);
5791 let starting_block = nodes[1].best_block_info();
5792 let mut block = Block {
5793 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5796 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5797 connect_block(&nodes[0], &block);
5798 block.header.prev_blockhash = block.block_hash();
5800 if !check_revoke_no_close {
5801 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5802 check_closed_broadcast!(nodes[0], true);
5803 check_added_monitors!(nodes[0], 1);
5805 expect_payment_failed!(nodes[0], our_payment_hash, true);
5809 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5810 // There are only a few cases to test here:
5811 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5812 // broadcastable commitment transactions result in channel closure,
5813 // * its included in an unrevoked-but-previous remote commitment transaction,
5814 // * its included in the latest remote or local commitment transactions.
5815 // We test each of the three possible commitment transactions individually and use both dust and
5817 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5818 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5819 // tested for at least one of the cases in other tests.
5821 fn htlc_claim_single_commitment_only_a() {
5822 do_htlc_claim_local_commitment_only(true);
5823 do_htlc_claim_local_commitment_only(false);
5825 do_htlc_claim_current_remote_commitment_only(true);
5826 do_htlc_claim_current_remote_commitment_only(false);
5830 fn htlc_claim_single_commitment_only_b() {
5831 do_htlc_claim_previous_remote_commitment_only(true, false);
5832 do_htlc_claim_previous_remote_commitment_only(false, false);
5833 do_htlc_claim_previous_remote_commitment_only(true, true);
5834 do_htlc_claim_previous_remote_commitment_only(false, true);
5839 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5840 let chanmon_cfgs = create_chanmon_cfgs(2);
5841 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5842 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5843 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5844 //Force duplicate channel ids
5845 for node in nodes.iter() {
5846 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5849 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5850 let channel_value_satoshis=10000;
5851 let push_msat=10001;
5852 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5853 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5854 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5856 //Create a second channel with a channel_id collision
5857 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5861 fn bolt2_open_channel_sending_node_checks_part2() {
5862 let chanmon_cfgs = create_chanmon_cfgs(2);
5863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5865 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5867 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5868 let channel_value_satoshis=2^24;
5869 let push_msat=10001;
5870 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5872 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5873 let channel_value_satoshis=10000;
5874 // Test when push_msat is equal to 1000 * funding_satoshis.
5875 let push_msat=1000*channel_value_satoshis+1;
5876 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5878 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5879 let channel_value_satoshis=10000;
5880 let push_msat=10001;
5881 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
5882 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5883 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5885 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5886 // 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
5887 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5889 // 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.
5890 assert!(BREAKDOWN_TIMEOUT>0);
5891 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5893 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5894 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5895 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5897 // 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.
5898 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5899 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5900 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5901 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5902 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5906 fn bolt2_open_channel_sane_dust_limit() {
5907 let chanmon_cfgs = create_chanmon_cfgs(2);
5908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5912 let channel_value_satoshis=1000000;
5913 let push_msat=10001;
5914 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5915 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5916 node0_to_1_send_open_channel.dust_limit_satoshis = 661;
5917 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5919 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5920 let events = nodes[1].node.get_and_clear_pending_msg_events();
5921 let err_msg = match events[0] {
5922 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5925 _ => panic!("Unexpected event"),
5927 assert_eq!(err_msg.data, "dust_limit_satoshis (661) is greater than the implementation limit (660)");
5930 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5931 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5932 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5933 // is no longer affordable once it's freed.
5935 fn test_fail_holding_cell_htlc_upon_free() {
5936 let chanmon_cfgs = create_chanmon_cfgs(2);
5937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5939 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5940 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5941 let logger = test_utils::TestLogger::new();
5943 // First nodes[0] generates an update_fee, setting the channel's
5944 // pending_update_fee.
5946 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5947 *feerate_lock += 20;
5949 nodes[0].node.timer_tick_occurred();
5950 check_added_monitors!(nodes[0], 1);
5952 let events = nodes[0].node.get_and_clear_pending_msg_events();
5953 assert_eq!(events.len(), 1);
5954 let (update_msg, commitment_signed) = match events[0] {
5955 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5956 (update_fee.as_ref(), commitment_signed)
5958 _ => panic!("Unexpected event"),
5961 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5963 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5964 let channel_reserve = chan_stat.channel_reserve_msat;
5965 let feerate = get_feerate!(nodes[0], chan.2);
5967 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5968 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
5969 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5970 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5971 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
5973 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5974 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5975 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5976 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5978 // Flush the pending fee update.
5979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5980 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5981 check_added_monitors!(nodes[1], 1);
5982 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5983 check_added_monitors!(nodes[0], 1);
5985 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5986 // HTLC, but now that the fee has been raised the payment will now fail, causing
5987 // us to surface its failure to the user.
5988 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5989 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5990 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);
5991 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 {}",
5992 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5993 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5995 // Check that the payment failed to be sent out.
5996 let events = nodes[0].node.get_and_clear_pending_events();
5997 assert_eq!(events.len(), 1);
5999 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6000 assert_eq!(our_payment_hash.clone(), *payment_hash);
6001 assert_eq!(*rejected_by_dest, false);
6002 assert_eq!(*error_code, None);
6003 assert_eq!(*error_data, None);
6005 _ => panic!("Unexpected event"),
6009 // Test that if multiple HTLCs are released from the holding cell and one is
6010 // valid but the other is no longer valid upon release, the valid HTLC can be
6011 // successfully completed while the other one fails as expected.
6013 fn test_free_and_fail_holding_cell_htlcs() {
6014 let chanmon_cfgs = create_chanmon_cfgs(2);
6015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6017 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6018 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6019 let logger = test_utils::TestLogger::new();
6021 // First nodes[0] generates an update_fee, setting the channel's
6022 // pending_update_fee.
6024 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6025 *feerate_lock += 200;
6027 nodes[0].node.timer_tick_occurred();
6028 check_added_monitors!(nodes[0], 1);
6030 let events = nodes[0].node.get_and_clear_pending_msg_events();
6031 assert_eq!(events.len(), 1);
6032 let (update_msg, commitment_signed) = match events[0] {
6033 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6034 (update_fee.as_ref(), commitment_signed)
6036 _ => panic!("Unexpected event"),
6039 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6041 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6042 let channel_reserve = chan_stat.channel_reserve_msat;
6043 let feerate = get_feerate!(nodes[0], chan.2);
6045 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6046 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6048 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6049 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6050 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6051 let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6052 let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6054 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6055 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6056 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6057 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6058 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6059 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6060 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6062 // Flush the pending fee update.
6063 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6064 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6065 check_added_monitors!(nodes[1], 1);
6066 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6068 check_added_monitors!(nodes[0], 2);
6070 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6071 // but now that the fee has been raised the second payment will now fail, causing us
6072 // to surface its failure to the user. The first payment should succeed.
6073 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6074 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6075 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);
6076 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 {}",
6077 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6078 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6080 // Check that the second payment failed to be sent out.
6081 let events = nodes[0].node.get_and_clear_pending_events();
6082 assert_eq!(events.len(), 1);
6084 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6085 assert_eq!(payment_hash_2.clone(), *payment_hash);
6086 assert_eq!(*rejected_by_dest, false);
6087 assert_eq!(*error_code, None);
6088 assert_eq!(*error_data, None);
6090 _ => panic!("Unexpected event"),
6093 // Complete the first payment and the RAA from the fee update.
6094 let (payment_event, send_raa_event) = {
6095 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6096 assert_eq!(msgs.len(), 2);
6097 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6099 let raa = match send_raa_event {
6100 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6101 _ => panic!("Unexpected event"),
6103 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6104 check_added_monitors!(nodes[1], 1);
6105 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6106 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6107 let events = nodes[1].node.get_and_clear_pending_events();
6108 assert_eq!(events.len(), 1);
6110 Event::PendingHTLCsForwardable { .. } => {},
6111 _ => panic!("Unexpected event"),
6113 nodes[1].node.process_pending_htlc_forwards();
6114 let events = nodes[1].node.get_and_clear_pending_events();
6115 assert_eq!(events.len(), 1);
6117 Event::PaymentReceived { .. } => {},
6118 _ => panic!("Unexpected event"),
6120 nodes[1].node.claim_funds(payment_preimage_1);
6121 check_added_monitors!(nodes[1], 1);
6122 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6123 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6124 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6125 let events = nodes[0].node.get_and_clear_pending_events();
6126 assert_eq!(events.len(), 1);
6128 Event::PaymentSent { ref payment_preimage } => {
6129 assert_eq!(*payment_preimage, payment_preimage_1);
6131 _ => panic!("Unexpected event"),
6135 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6136 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6137 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6140 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6141 let chanmon_cfgs = create_chanmon_cfgs(3);
6142 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6143 // When this test was written, the default base fee floated based on the HTLC count.
6144 // It is now fixed, so we simply set the fee to the expected value here.
6145 let mut config = test_default_channel_config();
6146 config.channel_options.forwarding_fee_base_msat = 196;
6147 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6148 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6149 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6150 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6151 let logger = test_utils::TestLogger::new();
6153 // First nodes[1] generates an update_fee, setting the channel's
6154 // pending_update_fee.
6156 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6157 *feerate_lock += 20;
6159 nodes[1].node.timer_tick_occurred();
6160 check_added_monitors!(nodes[1], 1);
6162 let events = nodes[1].node.get_and_clear_pending_msg_events();
6163 assert_eq!(events.len(), 1);
6164 let (update_msg, commitment_signed) = match events[0] {
6165 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6166 (update_fee.as_ref(), commitment_signed)
6168 _ => panic!("Unexpected event"),
6171 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6173 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6174 let channel_reserve = chan_stat.channel_reserve_msat;
6175 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6177 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6179 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6180 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6181 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6182 let payment_event = {
6183 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6184 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6185 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6186 check_added_monitors!(nodes[0], 1);
6188 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6189 assert_eq!(events.len(), 1);
6191 SendEvent::from_event(events.remove(0))
6193 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6194 check_added_monitors!(nodes[1], 0);
6195 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6196 expect_pending_htlcs_forwardable!(nodes[1]);
6198 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6199 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6201 // Flush the pending fee update.
6202 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6203 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6204 check_added_monitors!(nodes[2], 1);
6205 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6206 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6207 check_added_monitors!(nodes[1], 2);
6209 // A final RAA message is generated to finalize the fee update.
6210 let events = nodes[1].node.get_and_clear_pending_msg_events();
6211 assert_eq!(events.len(), 1);
6213 let raa_msg = match &events[0] {
6214 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6217 _ => panic!("Unexpected event"),
6220 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6221 check_added_monitors!(nodes[2], 1);
6222 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6224 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6225 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6226 assert_eq!(process_htlc_forwards_event.len(), 1);
6227 match &process_htlc_forwards_event[0] {
6228 &Event::PendingHTLCsForwardable { .. } => {},
6229 _ => panic!("Unexpected event"),
6232 // In response, we call ChannelManager's process_pending_htlc_forwards
6233 nodes[1].node.process_pending_htlc_forwards();
6234 check_added_monitors!(nodes[1], 1);
6236 // This causes the HTLC to be failed backwards.
6237 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6238 assert_eq!(fail_event.len(), 1);
6239 let (fail_msg, commitment_signed) = match &fail_event[0] {
6240 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6241 assert_eq!(updates.update_add_htlcs.len(), 0);
6242 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6243 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6244 assert_eq!(updates.update_fail_htlcs.len(), 1);
6245 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6247 _ => panic!("Unexpected event"),
6250 // Pass the failure messages back to nodes[0].
6251 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6252 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6254 // Complete the HTLC failure+removal process.
6255 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6256 check_added_monitors!(nodes[0], 1);
6257 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6258 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6259 check_added_monitors!(nodes[1], 2);
6260 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6261 assert_eq!(final_raa_event.len(), 1);
6262 let raa = match &final_raa_event[0] {
6263 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6264 _ => panic!("Unexpected event"),
6266 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6267 expect_payment_failure_chan_update!(nodes[0], chan_1_2.0.contents.short_channel_id, false);
6268 expect_payment_failed!(nodes[0], our_payment_hash, false);
6269 check_added_monitors!(nodes[0], 1);
6272 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6273 // 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.
6274 //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.
6277 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6278 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6279 let chanmon_cfgs = create_chanmon_cfgs(2);
6280 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6281 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6282 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6283 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6285 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6286 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6287 let logger = test_utils::TestLogger::new();
6288 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6289 route.paths[0][0].fee_msat = 100;
6291 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6292 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6293 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6294 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6298 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6299 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6300 let chanmon_cfgs = create_chanmon_cfgs(2);
6301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6303 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6304 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6305 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6307 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6308 let logger = test_utils::TestLogger::new();
6309 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6310 route.paths[0][0].fee_msat = 0;
6311 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6312 assert_eq!(err, "Cannot send 0-msat HTLC"));
6314 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6315 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6319 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6320 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6321 let chanmon_cfgs = create_chanmon_cfgs(2);
6322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6325 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6327 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6328 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6329 let logger = test_utils::TestLogger::new();
6330 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6331 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6332 check_added_monitors!(nodes[0], 1);
6333 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6334 updates.update_add_htlcs[0].amount_msat = 0;
6336 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6337 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6338 check_closed_broadcast!(nodes[1], true).unwrap();
6339 check_added_monitors!(nodes[1], 1);
6343 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6344 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6345 //It is enforced when constructing a route.
6346 let chanmon_cfgs = create_chanmon_cfgs(2);
6347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6349 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6350 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6351 let logger = test_utils::TestLogger::new();
6353 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6355 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6356 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000000, 500000001, &logger).unwrap();
6357 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6358 assert_eq!(err, &"Channel CLTV overflowed?"));
6362 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6363 //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.
6364 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6365 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6366 let chanmon_cfgs = create_chanmon_cfgs(2);
6367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6370 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6371 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6373 let logger = test_utils::TestLogger::new();
6374 for i in 0..max_accepted_htlcs {
6375 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6376 let payment_event = {
6377 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6378 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6379 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6380 check_added_monitors!(nodes[0], 1);
6382 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6383 assert_eq!(events.len(), 1);
6384 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6385 assert_eq!(htlcs[0].htlc_id, i);
6389 SendEvent::from_event(events.remove(0))
6391 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6392 check_added_monitors!(nodes[1], 0);
6393 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6395 expect_pending_htlcs_forwardable!(nodes[1]);
6396 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6398 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6399 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6400 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6401 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6402 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6404 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6405 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6409 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6410 //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.
6411 let chanmon_cfgs = create_chanmon_cfgs(2);
6412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6414 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6415 let channel_value = 100000;
6416 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6417 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6419 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6421 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6422 // Manually create a route over our max in flight (which our router normally automatically
6424 let route = Route { paths: vec![vec![RouteHop {
6425 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6426 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6427 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6429 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6430 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)));
6432 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6433 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);
6435 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6438 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6440 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6441 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6442 let chanmon_cfgs = create_chanmon_cfgs(2);
6443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6445 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6446 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6447 let htlc_minimum_msat: u64;
6449 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6450 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6451 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6454 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6455 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6456 let logger = test_utils::TestLogger::new();
6457 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6458 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6459 check_added_monitors!(nodes[0], 1);
6460 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6461 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6463 assert!(nodes[1].node.list_channels().is_empty());
6464 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6465 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()));
6466 check_added_monitors!(nodes[1], 1);
6470 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6471 //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
6472 let chanmon_cfgs = create_chanmon_cfgs(2);
6473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6475 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6476 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6477 let logger = test_utils::TestLogger::new();
6479 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6480 let channel_reserve = chan_stat.channel_reserve_msat;
6481 let feerate = get_feerate!(nodes[0], chan.2);
6482 // The 2* and +1 are for the fee spike reserve.
6483 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6485 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6486 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6487 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6488 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6489 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6490 check_added_monitors!(nodes[0], 1);
6491 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6493 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6494 // at this time channel-initiatee receivers are not required to enforce that senders
6495 // respect the fee_spike_reserve.
6496 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6497 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6499 assert!(nodes[1].node.list_channels().is_empty());
6500 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6501 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6502 check_added_monitors!(nodes[1], 1);
6506 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6507 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6508 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6509 let chanmon_cfgs = create_chanmon_cfgs(2);
6510 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6511 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6512 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6513 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6514 let logger = test_utils::TestLogger::new();
6516 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6517 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6519 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6520 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6522 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6523 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6524 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6525 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6527 let mut msg = msgs::UpdateAddHTLC {
6531 payment_hash: our_payment_hash,
6532 cltv_expiry: htlc_cltv,
6533 onion_routing_packet: onion_packet.clone(),
6536 for i in 0..super::channel::OUR_MAX_HTLCS {
6537 msg.htlc_id = i as u64;
6538 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6540 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6541 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6543 assert!(nodes[1].node.list_channels().is_empty());
6544 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6545 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6546 check_added_monitors!(nodes[1], 1);
6550 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6551 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6552 let chanmon_cfgs = create_chanmon_cfgs(2);
6553 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6554 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6555 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6556 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6557 let logger = test_utils::TestLogger::new();
6559 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6560 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6561 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6562 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6563 check_added_monitors!(nodes[0], 1);
6564 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6565 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6568 assert!(nodes[1].node.list_channels().is_empty());
6569 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6570 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6571 check_added_monitors!(nodes[1], 1);
6575 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6576 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6577 let chanmon_cfgs = create_chanmon_cfgs(2);
6578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6580 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6581 let logger = test_utils::TestLogger::new();
6583 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6584 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6585 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6586 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6587 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6588 check_added_monitors!(nodes[0], 1);
6589 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6590 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6591 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6593 assert!(nodes[1].node.list_channels().is_empty());
6594 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6595 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6596 check_added_monitors!(nodes[1], 1);
6600 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6601 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6602 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6603 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6604 let chanmon_cfgs = create_chanmon_cfgs(2);
6605 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6607 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6608 let logger = test_utils::TestLogger::new();
6610 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6611 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6612 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6613 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6614 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6615 check_added_monitors!(nodes[0], 1);
6616 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6617 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6619 //Disconnect and Reconnect
6620 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6621 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6622 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6623 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6624 assert_eq!(reestablish_1.len(), 1);
6625 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6626 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6627 assert_eq!(reestablish_2.len(), 1);
6628 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6629 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6630 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6631 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6634 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6635 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6636 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6637 check_added_monitors!(nodes[1], 1);
6638 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6640 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6642 assert!(nodes[1].node.list_channels().is_empty());
6643 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6644 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6645 check_added_monitors!(nodes[1], 1);
6649 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6650 //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.
6652 let chanmon_cfgs = create_chanmon_cfgs(2);
6653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6655 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6656 let logger = test_utils::TestLogger::new();
6657 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6658 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6659 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6660 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6661 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6663 check_added_monitors!(nodes[0], 1);
6664 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6665 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6667 let update_msg = msgs::UpdateFulfillHTLC{
6670 payment_preimage: our_payment_preimage,
6673 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6675 assert!(nodes[0].node.list_channels().is_empty());
6676 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6677 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()));
6678 check_added_monitors!(nodes[0], 1);
6682 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6683 //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.
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6690 let logger = test_utils::TestLogger::new();
6692 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6693 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6694 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6695 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6696 check_added_monitors!(nodes[0], 1);
6697 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6698 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6700 let update_msg = msgs::UpdateFailHTLC{
6703 reason: msgs::OnionErrorPacket { data: Vec::new()},
6706 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6708 assert!(nodes[0].node.list_channels().is_empty());
6709 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6710 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()));
6711 check_added_monitors!(nodes[0], 1);
6715 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6716 //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.
6718 let chanmon_cfgs = create_chanmon_cfgs(2);
6719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6721 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6722 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6723 let logger = test_utils::TestLogger::new();
6725 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6726 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6727 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6728 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6729 check_added_monitors!(nodes[0], 1);
6730 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6731 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6732 let update_msg = msgs::UpdateFailMalformedHTLC{
6735 sha256_of_onion: [1; 32],
6736 failure_code: 0x8000,
6739 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6741 assert!(nodes[0].node.list_channels().is_empty());
6742 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6743 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()));
6744 check_added_monitors!(nodes[0], 1);
6748 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6749 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6751 let chanmon_cfgs = create_chanmon_cfgs(2);
6752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6755 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6757 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6759 nodes[1].node.claim_funds(our_payment_preimage);
6760 check_added_monitors!(nodes[1], 1);
6762 let events = nodes[1].node.get_and_clear_pending_msg_events();
6763 assert_eq!(events.len(), 1);
6764 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6766 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, .. } } => {
6767 assert!(update_add_htlcs.is_empty());
6768 assert_eq!(update_fulfill_htlcs.len(), 1);
6769 assert!(update_fail_htlcs.is_empty());
6770 assert!(update_fail_malformed_htlcs.is_empty());
6771 assert!(update_fee.is_none());
6772 update_fulfill_htlcs[0].clone()
6774 _ => panic!("Unexpected event"),
6778 update_fulfill_msg.htlc_id = 1;
6780 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6782 assert!(nodes[0].node.list_channels().is_empty());
6783 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6784 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6785 check_added_monitors!(nodes[0], 1);
6789 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6790 //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.
6792 let chanmon_cfgs = create_chanmon_cfgs(2);
6793 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6794 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6795 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6796 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6798 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6800 nodes[1].node.claim_funds(our_payment_preimage);
6801 check_added_monitors!(nodes[1], 1);
6803 let events = nodes[1].node.get_and_clear_pending_msg_events();
6804 assert_eq!(events.len(), 1);
6805 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6807 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, .. } } => {
6808 assert!(update_add_htlcs.is_empty());
6809 assert_eq!(update_fulfill_htlcs.len(), 1);
6810 assert!(update_fail_htlcs.is_empty());
6811 assert!(update_fail_malformed_htlcs.is_empty());
6812 assert!(update_fee.is_none());
6813 update_fulfill_htlcs[0].clone()
6815 _ => panic!("Unexpected event"),
6819 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6821 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6823 assert!(nodes[0].node.list_channels().is_empty());
6824 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6825 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6826 check_added_monitors!(nodes[0], 1);
6830 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6831 //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.
6833 let chanmon_cfgs = create_chanmon_cfgs(2);
6834 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6835 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6836 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6837 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6838 let logger = test_utils::TestLogger::new();
6840 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6841 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6842 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6843 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6844 check_added_monitors!(nodes[0], 1);
6846 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6847 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6849 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6850 check_added_monitors!(nodes[1], 0);
6851 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6853 let events = nodes[1].node.get_and_clear_pending_msg_events();
6855 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6857 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, .. } } => {
6858 assert!(update_add_htlcs.is_empty());
6859 assert!(update_fulfill_htlcs.is_empty());
6860 assert!(update_fail_htlcs.is_empty());
6861 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6862 assert!(update_fee.is_none());
6863 update_fail_malformed_htlcs[0].clone()
6865 _ => panic!("Unexpected event"),
6868 update_msg.failure_code &= !0x8000;
6869 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6871 assert!(nodes[0].node.list_channels().is_empty());
6872 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6873 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6874 check_added_monitors!(nodes[0], 1);
6878 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6879 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6880 // * 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.
6882 let chanmon_cfgs = create_chanmon_cfgs(3);
6883 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6884 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6885 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6886 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6887 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6888 let logger = test_utils::TestLogger::new();
6890 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6893 let mut payment_event = {
6894 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6895 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6896 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6897 check_added_monitors!(nodes[0], 1);
6898 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6899 assert_eq!(events.len(), 1);
6900 SendEvent::from_event(events.remove(0))
6902 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6903 check_added_monitors!(nodes[1], 0);
6904 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6905 expect_pending_htlcs_forwardable!(nodes[1]);
6906 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6907 assert_eq!(events_2.len(), 1);
6908 check_added_monitors!(nodes[1], 1);
6909 payment_event = SendEvent::from_event(events_2.remove(0));
6910 assert_eq!(payment_event.msgs.len(), 1);
6913 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6914 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6915 check_added_monitors!(nodes[2], 0);
6916 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6918 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6919 assert_eq!(events_3.len(), 1);
6920 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6922 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 } } => {
6923 assert!(update_add_htlcs.is_empty());
6924 assert!(update_fulfill_htlcs.is_empty());
6925 assert!(update_fail_htlcs.is_empty());
6926 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6927 assert!(update_fee.is_none());
6928 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6930 _ => panic!("Unexpected event"),
6934 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6936 check_added_monitors!(nodes[1], 0);
6937 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6938 expect_pending_htlcs_forwardable!(nodes[1]);
6939 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6940 assert_eq!(events_4.len(), 1);
6942 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6944 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, .. } } => {
6945 assert!(update_add_htlcs.is_empty());
6946 assert!(update_fulfill_htlcs.is_empty());
6947 assert_eq!(update_fail_htlcs.len(), 1);
6948 assert!(update_fail_malformed_htlcs.is_empty());
6949 assert!(update_fee.is_none());
6951 _ => panic!("Unexpected event"),
6954 check_added_monitors!(nodes[1], 1);
6957 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6958 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6959 // 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
6960 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6962 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6963 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6964 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6965 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6966 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6967 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6969 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6971 // We route 2 dust-HTLCs between A and B
6972 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6973 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6974 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6976 // Cache one local commitment tx as previous
6977 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6979 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6980 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6981 check_added_monitors!(nodes[1], 0);
6982 expect_pending_htlcs_forwardable!(nodes[1]);
6983 check_added_monitors!(nodes[1], 1);
6985 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6986 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6988 check_added_monitors!(nodes[0], 1);
6990 // Cache one local commitment tx as lastest
6991 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6993 let events = nodes[0].node.get_and_clear_pending_msg_events();
6995 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6996 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6998 _ => panic!("Unexpected event"),
7001 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7002 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7004 _ => panic!("Unexpected event"),
7007 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7008 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7009 if announce_latest {
7010 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7012 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7015 check_closed_broadcast!(nodes[0], true);
7016 check_added_monitors!(nodes[0], 1);
7018 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7019 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7020 let events = nodes[0].node.get_and_clear_pending_events();
7021 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7022 assert_eq!(events.len(), 2);
7023 let mut first_failed = false;
7024 for event in events {
7026 Event::PaymentFailed { payment_hash, .. } => {
7027 if payment_hash == payment_hash_1 {
7028 assert!(!first_failed);
7029 first_failed = true;
7031 assert_eq!(payment_hash, payment_hash_2);
7034 _ => panic!("Unexpected event"),
7040 fn test_failure_delay_dust_htlc_local_commitment() {
7041 do_test_failure_delay_dust_htlc_local_commitment(true);
7042 do_test_failure_delay_dust_htlc_local_commitment(false);
7045 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7046 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7047 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7048 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7049 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7050 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7051 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7053 let chanmon_cfgs = create_chanmon_cfgs(3);
7054 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7055 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7056 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7057 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7059 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7061 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7062 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7064 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7065 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7067 // We revoked bs_commitment_tx
7069 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7070 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7073 let mut timeout_tx = Vec::new();
7075 // We fail dust-HTLC 1 by broadcast of local commitment tx
7076 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7077 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7078 expect_payment_failed!(nodes[0], dust_hash, true);
7080 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7081 check_closed_broadcast!(nodes[0], true);
7082 check_added_monitors!(nodes[0], 1);
7083 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7084 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7085 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7086 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7087 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7088 mine_transaction(&nodes[0], &timeout_tx[0]);
7089 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7090 expect_payment_failed!(nodes[0], non_dust_hash, true);
7092 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7093 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7094 check_closed_broadcast!(nodes[0], true);
7095 check_added_monitors!(nodes[0], 1);
7096 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7097 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7098 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7100 expect_payment_failed!(nodes[0], dust_hash, true);
7101 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7102 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7103 mine_transaction(&nodes[0], &timeout_tx[0]);
7104 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7105 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7106 expect_payment_failed!(nodes[0], non_dust_hash, true);
7108 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7110 let events = nodes[0].node.get_and_clear_pending_events();
7111 assert_eq!(events.len(), 2);
7114 Event::PaymentFailed { payment_hash, .. } => {
7115 if payment_hash == dust_hash { first = true; }
7116 else { first = false; }
7118 _ => panic!("Unexpected event"),
7121 Event::PaymentFailed { payment_hash, .. } => {
7122 if first { assert_eq!(payment_hash, non_dust_hash); }
7123 else { assert_eq!(payment_hash, dust_hash); }
7125 _ => panic!("Unexpected event"),
7132 fn test_sweep_outbound_htlc_failure_update() {
7133 do_test_sweep_outbound_htlc_failure_update(false, true);
7134 do_test_sweep_outbound_htlc_failure_update(false, false);
7135 do_test_sweep_outbound_htlc_failure_update(true, false);
7139 fn test_user_configurable_csv_delay() {
7140 // We test our channel constructors yield errors when we pass them absurd csv delay
7142 let mut low_our_to_self_config = UserConfig::default();
7143 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7144 let mut high_their_to_self_config = UserConfig::default();
7145 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7146 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7147 let chanmon_cfgs = create_chanmon_cfgs(2);
7148 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7149 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7150 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7152 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7153 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) {
7155 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())); },
7156 _ => panic!("Unexpected event"),
7158 } else { assert!(false) }
7160 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7161 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7162 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7163 open_channel.to_self_delay = 200;
7164 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) {
7166 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())); },
7167 _ => panic!("Unexpected event"),
7169 } else { assert!(false); }
7171 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7172 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7173 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()));
7174 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7175 accept_channel.to_self_delay = 200;
7176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7177 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7179 &ErrorAction::SendErrorMessage { ref msg } => {
7180 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()));
7182 _ => { assert!(false); }
7184 } else { assert!(false); }
7186 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7187 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7188 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7189 open_channel.to_self_delay = 200;
7190 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) {
7192 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())); },
7193 _ => panic!("Unexpected event"),
7195 } else { assert!(false); }
7199 fn test_data_loss_protect() {
7200 // We want to be sure that :
7201 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7202 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7203 // * we close channel in case of detecting other being fallen behind
7204 // * we are able to claim our own outputs thanks to to_remote being static
7205 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7211 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7212 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7213 // during signing due to revoked tx
7214 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7215 let keys_manager = &chanmon_cfgs[0].keys_manager;
7218 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7219 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7220 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7222 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7224 // Cache node A state before any channel update
7225 let previous_node_state = nodes[0].node.encode();
7226 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7227 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7229 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7230 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7232 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7233 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7235 // Restore node A from previous state
7236 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7237 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7238 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7239 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7240 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7241 persister = test_utils::TestPersister::new();
7242 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7244 let mut channel_monitors = HashMap::new();
7245 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7246 <(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 {
7247 keys_manager: keys_manager,
7248 fee_estimator: &fee_estimator,
7249 chain_monitor: &monitor,
7251 tx_broadcaster: &tx_broadcaster,
7252 default_config: UserConfig::default(),
7256 nodes[0].node = &node_state_0;
7257 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7258 nodes[0].chain_monitor = &monitor;
7259 nodes[0].chain_source = &chain_source;
7261 check_added_monitors!(nodes[0], 1);
7263 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7264 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7266 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7268 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7269 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7270 check_added_monitors!(nodes[0], 1);
7273 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7274 assert_eq!(node_txn.len(), 0);
7277 let mut reestablish_1 = Vec::with_capacity(1);
7278 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7279 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7280 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7281 reestablish_1.push(msg.clone());
7282 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7283 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7285 &ErrorAction::SendErrorMessage { ref msg } => {
7286 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");
7288 _ => panic!("Unexpected event!"),
7291 panic!("Unexpected event")
7295 // Check we close channel detecting A is fallen-behind
7296 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7297 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7298 check_added_monitors!(nodes[1], 1);
7301 // Check A is able to claim to_remote output
7302 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7303 assert_eq!(node_txn.len(), 1);
7304 check_spends!(node_txn[0], chan.3);
7305 assert_eq!(node_txn[0].output.len(), 2);
7306 mine_transaction(&nodes[0], &node_txn[0]);
7307 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7308 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7309 assert_eq!(spend_txn.len(), 1);
7310 check_spends!(spend_txn[0], node_txn[0]);
7314 fn test_check_htlc_underpaying() {
7315 // Send payment through A -> B but A is maliciously
7316 // sending a probe payment (i.e less than expected value0
7317 // to B, B should refuse payment.
7319 let chanmon_cfgs = create_chanmon_cfgs(2);
7320 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7321 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7322 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7324 // Create some initial channels
7325 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7327 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7328 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7329 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7330 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7331 check_added_monitors!(nodes[0], 1);
7333 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7334 assert_eq!(events.len(), 1);
7335 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7336 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7337 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7339 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7340 // and then will wait a second random delay before failing the HTLC back:
7341 expect_pending_htlcs_forwardable!(nodes[1]);
7342 expect_pending_htlcs_forwardable!(nodes[1]);
7344 // Node 3 is expecting payment of 100_000 but received 10_000,
7345 // it should fail htlc like we didn't know the preimage.
7346 nodes[1].node.process_pending_htlc_forwards();
7348 let events = nodes[1].node.get_and_clear_pending_msg_events();
7349 assert_eq!(events.len(), 1);
7350 let (update_fail_htlc, commitment_signed) = match events[0] {
7351 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 } } => {
7352 assert!(update_add_htlcs.is_empty());
7353 assert!(update_fulfill_htlcs.is_empty());
7354 assert_eq!(update_fail_htlcs.len(), 1);
7355 assert!(update_fail_malformed_htlcs.is_empty());
7356 assert!(update_fee.is_none());
7357 (update_fail_htlcs[0].clone(), commitment_signed)
7359 _ => panic!("Unexpected event"),
7361 check_added_monitors!(nodes[1], 1);
7363 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7364 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7366 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7367 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7368 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7369 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7373 fn test_announce_disable_channels() {
7374 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7375 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7377 let chanmon_cfgs = create_chanmon_cfgs(2);
7378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7380 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7382 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7383 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7384 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7387 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7388 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7390 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7391 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7392 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7393 assert_eq!(msg_events.len(), 3);
7394 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7395 for e in msg_events {
7397 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7398 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7399 // Check that each channel gets updated exactly once
7400 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7401 panic!("Generated ChannelUpdate for wrong chan!");
7404 _ => panic!("Unexpected event"),
7408 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7409 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7410 assert_eq!(reestablish_1.len(), 3);
7411 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7412 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7413 assert_eq!(reestablish_2.len(), 3);
7415 // Reestablish chan_1
7416 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7417 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7418 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7419 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7420 // Reestablish chan_2
7421 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7422 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7423 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7424 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7425 // Reestablish chan_3
7426 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7427 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7428 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7429 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7431 nodes[0].node.timer_tick_occurred();
7432 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7433 nodes[0].node.timer_tick_occurred();
7434 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7435 assert_eq!(msg_events.len(), 3);
7436 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7437 for e in msg_events {
7439 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7440 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7441 // Check that each channel gets updated exactly once
7442 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7443 panic!("Generated ChannelUpdate for wrong chan!");
7446 _ => panic!("Unexpected event"),
7452 fn test_priv_forwarding_rejection() {
7453 // If we have a private channel with outbound liquidity, and
7454 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7455 // to forward through that channel.
7456 let chanmon_cfgs = create_chanmon_cfgs(3);
7457 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7458 let mut no_announce_cfg = test_default_channel_config();
7459 no_announce_cfg.channel_options.announced_channel = false;
7460 no_announce_cfg.accept_forwards_to_priv_channels = false;
7461 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7462 let persister: test_utils::TestPersister;
7463 let new_chain_monitor: test_utils::TestChainMonitor;
7464 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7465 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7467 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7469 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7470 // not send for private channels.
7471 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7472 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7473 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7474 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7475 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7477 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7478 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7479 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()));
7480 check_added_monitors!(nodes[2], 1);
7482 nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id()));
7483 check_added_monitors!(nodes[1], 1);
7485 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7486 confirm_transaction_at(&nodes[1], &tx, conf_height);
7487 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7488 confirm_transaction_at(&nodes[2], &tx, conf_height);
7489 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7490 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7491 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()));
7492 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7493 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7494 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7496 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7497 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7498 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7500 // We should always be able to forward through nodes[1] as long as its out through a public
7502 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7504 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7505 // to nodes[2], which should be rejected:
7506 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7507 let route = get_route(&nodes[0].node.get_our_node_id(),
7508 &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
7509 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
7510 &[&RouteHint(vec![RouteHintHop {
7511 src_node_id: nodes[1].node.get_our_node_id(),
7512 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7513 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7514 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7515 htlc_minimum_msat: None,
7516 htlc_maximum_msat: None,
7517 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7519 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7520 check_added_monitors!(nodes[0], 1);
7521 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7522 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7523 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7525 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7526 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7527 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7528 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7529 assert!(htlc_fail_updates.update_fee.is_none());
7531 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7532 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7533 expect_payment_failed!(nodes[0], our_payment_hash, false);
7534 expect_payment_failure_chan_update!(nodes[0], nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7536 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7537 // to true. Sadly there is currently no way to change it at runtime.
7539 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7540 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7542 let nodes_1_serialized = nodes[1].node.encode();
7543 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7544 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7546 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7547 let mut mon_iter = mons.iter();
7548 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7549 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7552 persister = test_utils::TestPersister::new();
7553 let keys_manager = &chanmon_cfgs[1].keys_manager;
7554 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);
7555 nodes[1].chain_monitor = &new_chain_monitor;
7557 let mut monitor_a_read = &monitor_a_serialized.0[..];
7558 let mut monitor_b_read = &monitor_b_serialized.0[..];
7559 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7560 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7561 assert!(monitor_a_read.is_empty());
7562 assert!(monitor_b_read.is_empty());
7564 no_announce_cfg.accept_forwards_to_priv_channels = true;
7566 let mut nodes_1_read = &nodes_1_serialized[..];
7567 let (_, nodes_1_deserialized_tmp) = {
7568 let mut channel_monitors = HashMap::new();
7569 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7570 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7571 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7572 default_config: no_announce_cfg,
7574 fee_estimator: node_cfgs[1].fee_estimator,
7575 chain_monitor: nodes[1].chain_monitor,
7576 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7577 logger: nodes[1].logger,
7581 assert!(nodes_1_read.is_empty());
7582 nodes_1_deserialized = nodes_1_deserialized_tmp;
7584 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7585 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7586 check_added_monitors!(nodes[1], 2);
7587 nodes[1].node = &nodes_1_deserialized;
7589 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7590 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7591 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7592 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7593 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7594 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7595 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7596 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7598 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7599 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7600 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7601 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7602 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7603 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7604 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7605 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7607 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7608 check_added_monitors!(nodes[0], 1);
7609 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7610 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7614 fn test_bump_penalty_txn_on_revoked_commitment() {
7615 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7616 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7618 let chanmon_cfgs = create_chanmon_cfgs(2);
7619 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7620 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7621 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7623 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7624 let logger = test_utils::TestLogger::new();
7626 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7627 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7628 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7629 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7631 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7632 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7633 assert_eq!(revoked_txn[0].output.len(), 4);
7634 assert_eq!(revoked_txn[0].input.len(), 1);
7635 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7636 let revoked_txid = revoked_txn[0].txid();
7638 let mut penalty_sum = 0;
7639 for outp in revoked_txn[0].output.iter() {
7640 if outp.script_pubkey.is_v0_p2wsh() {
7641 penalty_sum += outp.value;
7645 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7646 let header_114 = connect_blocks(&nodes[1], 14);
7648 // Actually revoke tx by claiming a HTLC
7649 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7650 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7651 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7652 check_added_monitors!(nodes[1], 1);
7654 // One or more justice tx should have been broadcast, check it
7658 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7659 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7660 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7661 assert_eq!(node_txn[0].output.len(), 1);
7662 check_spends!(node_txn[0], revoked_txn[0]);
7663 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7664 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7665 penalty_1 = node_txn[0].txid();
7669 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7670 connect_blocks(&nodes[1], 15);
7671 let mut penalty_2 = penalty_1;
7672 let mut feerate_2 = 0;
7674 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7675 assert_eq!(node_txn.len(), 1);
7676 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7677 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7678 assert_eq!(node_txn[0].output.len(), 1);
7679 check_spends!(node_txn[0], revoked_txn[0]);
7680 penalty_2 = node_txn[0].txid();
7681 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7682 assert_ne!(penalty_2, penalty_1);
7683 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7684 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7685 // Verify 25% bump heuristic
7686 assert!(feerate_2 * 100 >= feerate_1 * 125);
7690 assert_ne!(feerate_2, 0);
7692 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7693 connect_blocks(&nodes[1], 1);
7695 let mut feerate_3 = 0;
7697 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7698 assert_eq!(node_txn.len(), 1);
7699 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7700 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7701 assert_eq!(node_txn[0].output.len(), 1);
7702 check_spends!(node_txn[0], revoked_txn[0]);
7703 penalty_3 = node_txn[0].txid();
7704 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7705 assert_ne!(penalty_3, penalty_2);
7706 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7707 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7708 // Verify 25% bump heuristic
7709 assert!(feerate_3 * 100 >= feerate_2 * 125);
7713 assert_ne!(feerate_3, 0);
7715 nodes[1].node.get_and_clear_pending_events();
7716 nodes[1].node.get_and_clear_pending_msg_events();
7720 fn test_bump_penalty_txn_on_revoked_htlcs() {
7721 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7722 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7724 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7725 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7726 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7727 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7728 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7730 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7731 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7732 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
7733 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7734 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7735 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph.read().unwrap(),
7736 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7737 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7739 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7740 assert_eq!(revoked_local_txn[0].input.len(), 1);
7741 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7743 // Revoke local commitment tx
7744 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7746 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7747 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7748 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7749 check_closed_broadcast!(nodes[1], true);
7750 check_added_monitors!(nodes[1], 1);
7751 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7753 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7754 assert_eq!(revoked_htlc_txn.len(), 3);
7755 check_spends!(revoked_htlc_txn[1], chan.3);
7757 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7758 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7759 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7761 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7762 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7763 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7764 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7766 // Broadcast set of revoked txn on A
7767 let hash_128 = connect_blocks(&nodes[0], 40);
7768 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7769 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7770 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7771 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7772 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7777 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7778 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7779 // Verify claim tx are spending revoked HTLC txn
7781 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7782 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7783 // which are included in the same block (they are broadcasted because we scan the
7784 // transactions linearly and generate claims as we go, they likely should be removed in the
7786 assert_eq!(node_txn[0].input.len(), 1);
7787 check_spends!(node_txn[0], revoked_local_txn[0]);
7788 assert_eq!(node_txn[1].input.len(), 1);
7789 check_spends!(node_txn[1], revoked_local_txn[0]);
7790 assert_eq!(node_txn[2].input.len(), 1);
7791 check_spends!(node_txn[2], revoked_local_txn[0]);
7793 // Each of the three justice transactions claim a separate (single) output of the three
7794 // available, which we check here:
7795 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7796 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7797 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7799 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7800 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7802 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7803 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7804 // a remote commitment tx has already been confirmed).
7805 check_spends!(node_txn[3], chan.3);
7807 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7808 // output, checked above).
7809 assert_eq!(node_txn[4].input.len(), 2);
7810 assert_eq!(node_txn[4].output.len(), 1);
7811 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7813 first = node_txn[4].txid();
7814 // Store both feerates for later comparison
7815 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7816 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7817 penalty_txn = vec![node_txn[2].clone()];
7821 // Connect one more block to see if bumped penalty are issued for HTLC txn
7822 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7823 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7824 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7825 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7827 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7828 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7830 check_spends!(node_txn[0], revoked_local_txn[0]);
7831 check_spends!(node_txn[1], revoked_local_txn[0]);
7832 // Note that these are both bogus - they spend outputs already claimed in block 129:
7833 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7834 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7836 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7837 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7843 // Few more blocks to confirm penalty txn
7844 connect_blocks(&nodes[0], 4);
7845 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7846 let header_144 = connect_blocks(&nodes[0], 9);
7848 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7849 assert_eq!(node_txn.len(), 1);
7851 assert_eq!(node_txn[0].input.len(), 2);
7852 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7853 // Verify bumped tx is different and 25% bump heuristic
7854 assert_ne!(first, node_txn[0].txid());
7855 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7856 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7857 assert!(feerate_2 * 100 > feerate_1 * 125);
7858 let txn = vec![node_txn[0].clone()];
7862 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7863 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7864 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7865 connect_blocks(&nodes[0], 20);
7867 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7868 // We verify than no new transaction has been broadcast because previously
7869 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7870 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7871 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7872 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7873 // up bumped justice generation.
7874 assert_eq!(node_txn.len(), 0);
7877 check_closed_broadcast!(nodes[0], true);
7878 check_added_monitors!(nodes[0], 1);
7882 fn test_bump_penalty_txn_on_remote_commitment() {
7883 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7884 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7887 // Provide preimage for one
7888 // Check aggregation
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);
7895 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7896 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7897 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7899 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7900 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7901 assert_eq!(remote_txn[0].output.len(), 4);
7902 assert_eq!(remote_txn[0].input.len(), 1);
7903 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7905 // Claim a HTLC without revocation (provide B monitor with preimage)
7906 nodes[1].node.claim_funds(payment_preimage);
7907 mine_transaction(&nodes[1], &remote_txn[0]);
7908 check_added_monitors!(nodes[1], 2);
7909 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7911 // One or more claim tx should have been broadcast, check it
7915 let feerate_timeout;
7916 let feerate_preimage;
7918 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7919 // 9 transactions including:
7920 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7921 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7922 // 2 * HTLC-Success (one RBF bump we'll check later)
7924 assert_eq!(node_txn.len(), 8);
7925 assert_eq!(node_txn[0].input.len(), 1);
7926 assert_eq!(node_txn[6].input.len(), 1);
7927 check_spends!(node_txn[0], remote_txn[0]);
7928 check_spends!(node_txn[6], remote_txn[0]);
7929 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7930 preimage_bump = node_txn[3].clone();
7932 check_spends!(node_txn[1], chan.3);
7933 check_spends!(node_txn[2], node_txn[1]);
7934 assert_eq!(node_txn[1], node_txn[4]);
7935 assert_eq!(node_txn[2], node_txn[5]);
7937 timeout = node_txn[6].txid();
7938 let index = node_txn[6].input[0].previous_output.vout;
7939 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7940 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7942 preimage = node_txn[0].txid();
7943 let index = node_txn[0].input[0].previous_output.vout;
7944 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7945 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7949 assert_ne!(feerate_timeout, 0);
7950 assert_ne!(feerate_preimage, 0);
7952 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7953 connect_blocks(&nodes[1], 15);
7955 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7956 assert_eq!(node_txn.len(), 1);
7957 assert_eq!(node_txn[0].input.len(), 1);
7958 assert_eq!(preimage_bump.input.len(), 1);
7959 check_spends!(node_txn[0], remote_txn[0]);
7960 check_spends!(preimage_bump, remote_txn[0]);
7962 let index = preimage_bump.input[0].previous_output.vout;
7963 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7964 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7965 assert!(new_feerate * 100 > feerate_timeout * 125);
7966 assert_ne!(timeout, preimage_bump.txid());
7968 let index = node_txn[0].input[0].previous_output.vout;
7969 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7970 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7971 assert!(new_feerate * 100 > feerate_preimage * 125);
7972 assert_ne!(preimage, node_txn[0].txid());
7977 nodes[1].node.get_and_clear_pending_events();
7978 nodes[1].node.get_and_clear_pending_msg_events();
7982 fn test_counterparty_raa_skip_no_crash() {
7983 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7984 // commitment transaction, we would have happily carried on and provided them the next
7985 // commitment transaction based on one RAA forward. This would probably eventually have led to
7986 // channel closure, but it would not have resulted in funds loss. Still, our
7987 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7988 // check simply that the channel is closed in response to such an RAA, but don't check whether
7989 // we decide to punish our counterparty for revoking their funds (as we don't currently
7991 let chanmon_cfgs = create_chanmon_cfgs(2);
7992 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7993 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7994 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7995 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7997 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7998 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8000 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8002 // Make signer believe we got a counterparty signature, so that it allows the revocation
8003 keys.get_enforcement_state().last_holder_commitment -= 1;
8004 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8006 // Must revoke without gaps
8007 keys.get_enforcement_state().last_holder_commitment -= 1;
8008 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8010 keys.get_enforcement_state().last_holder_commitment -= 1;
8011 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8012 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8014 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8015 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8016 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8017 check_added_monitors!(nodes[1], 1);
8021 fn test_bump_txn_sanitize_tracking_maps() {
8022 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8023 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8025 let chanmon_cfgs = create_chanmon_cfgs(2);
8026 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8028 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8030 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8031 // Lock HTLC in both directions
8032 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8033 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8035 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8036 assert_eq!(revoked_local_txn[0].input.len(), 1);
8037 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8039 // Revoke local commitment tx
8040 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8042 // Broadcast set of revoked txn on A
8043 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8044 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8045 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8047 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8048 check_closed_broadcast!(nodes[0], true);
8049 check_added_monitors!(nodes[0], 1);
8051 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8052 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8053 check_spends!(node_txn[0], revoked_local_txn[0]);
8054 check_spends!(node_txn[1], revoked_local_txn[0]);
8055 check_spends!(node_txn[2], revoked_local_txn[0]);
8056 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8060 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8061 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8062 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8064 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8065 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8066 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8067 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8073 fn test_override_channel_config() {
8074 let chanmon_cfgs = create_chanmon_cfgs(2);
8075 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8076 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8077 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8079 // Node0 initiates a channel to node1 using the override config.
8080 let mut override_config = UserConfig::default();
8081 override_config.own_channel_config.our_to_self_delay = 200;
8083 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8085 // Assert the channel created by node0 is using the override config.
8086 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8087 assert_eq!(res.channel_flags, 0);
8088 assert_eq!(res.to_self_delay, 200);
8092 fn test_override_0msat_htlc_minimum() {
8093 let mut zero_config = UserConfig::default();
8094 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8095 let chanmon_cfgs = create_chanmon_cfgs(2);
8096 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8097 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8098 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8100 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8101 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8102 assert_eq!(res.htlc_minimum_msat, 1);
8104 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8105 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8106 assert_eq!(res.htlc_minimum_msat, 1);
8110 fn test_simple_mpp() {
8111 // Simple test of sending a multi-path payment.
8112 let chanmon_cfgs = create_chanmon_cfgs(4);
8113 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8114 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8115 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8117 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8118 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8119 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8120 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8121 let logger = test_utils::TestLogger::new();
8123 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8124 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8125 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8126 let path = route.paths[0].clone();
8127 route.paths.push(path);
8128 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8129 route.paths[0][0].short_channel_id = chan_1_id;
8130 route.paths[0][1].short_channel_id = chan_3_id;
8131 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8132 route.paths[1][0].short_channel_id = chan_2_id;
8133 route.paths[1][1].short_channel_id = chan_4_id;
8134 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8135 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8139 fn test_preimage_storage() {
8140 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8141 let chanmon_cfgs = create_chanmon_cfgs(2);
8142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8144 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8146 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8149 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8151 let logger = test_utils::TestLogger::new();
8152 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8153 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8154 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8155 check_added_monitors!(nodes[0], 1);
8156 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8157 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8158 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8159 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8161 // Note that after leaving the above scope we have no knowledge of any arguments or return
8162 // values from previous calls.
8163 expect_pending_htlcs_forwardable!(nodes[1]);
8164 let events = nodes[1].node.get_and_clear_pending_events();
8165 assert_eq!(events.len(), 1);
8167 Event::PaymentReceived { ref purpose, .. } => {
8169 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8170 assert_eq!(*user_payment_id, 42);
8171 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8173 _ => panic!("expected PaymentPurpose::InvoicePayment")
8176 _ => panic!("Unexpected event"),
8181 fn test_secret_timeout() {
8182 // Simple test of payment secret storage time outs
8183 let chanmon_cfgs = create_chanmon_cfgs(2);
8184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8186 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8188 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8190 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8192 // We should fail to register the same payment hash twice, at least until we've connected a
8193 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8194 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8195 assert_eq!(err, "Duplicate payment hash");
8196 } else { panic!(); }
8198 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8200 header: BlockHeader {
8202 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8203 merkle_root: Default::default(),
8204 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8208 connect_block(&nodes[1], &block);
8209 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8210 assert_eq!(err, "Duplicate payment hash");
8211 } else { panic!(); }
8213 // If we then connect the second block, we should be able to register the same payment hash
8214 // again with a different user_payment_id (this time getting a new payment secret).
8215 block.header.prev_blockhash = block.header.block_hash();
8216 block.header.time += 1;
8217 connect_block(&nodes[1], &block);
8218 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8219 assert_ne!(payment_secret_1, our_payment_secret);
8222 let logger = test_utils::TestLogger::new();
8223 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8224 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8225 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8226 check_added_monitors!(nodes[0], 1);
8227 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8228 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8230 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8232 // Note that after leaving the above scope we have no knowledge of any arguments or return
8233 // values from previous calls.
8234 expect_pending_htlcs_forwardable!(nodes[1]);
8235 let events = nodes[1].node.get_and_clear_pending_events();
8236 assert_eq!(events.len(), 1);
8238 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8239 assert!(payment_preimage.is_none());
8240 assert_eq!(user_payment_id, 42);
8241 assert_eq!(payment_secret, our_payment_secret);
8242 // We don't actually have the payment preimage with which to claim this payment!
8244 _ => panic!("Unexpected event"),
8249 fn test_bad_secret_hash() {
8250 // Simple test of unregistered payment hash/invalid payment secret handling
8251 let chanmon_cfgs = create_chanmon_cfgs(2);
8252 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8253 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8254 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8256 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8258 let random_payment_hash = PaymentHash([42; 32]);
8259 let random_payment_secret = PaymentSecret([43; 32]);
8260 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8262 let logger = test_utils::TestLogger::new();
8263 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8264 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8266 // All the below cases should end up being handled exactly identically, so we macro the
8267 // resulting events.
8268 macro_rules! handle_unknown_invalid_payment_data {
8270 check_added_monitors!(nodes[0], 1);
8271 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8272 let payment_event = SendEvent::from_event(events.pop().unwrap());
8273 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8274 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8276 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8277 // again to process the pending backwards-failure of the HTLC
8278 expect_pending_htlcs_forwardable!(nodes[1]);
8279 expect_pending_htlcs_forwardable!(nodes[1]);
8280 check_added_monitors!(nodes[1], 1);
8282 // We should fail the payment back
8283 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8284 match events.pop().unwrap() {
8285 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8286 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8287 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8289 _ => panic!("Unexpected event"),
8294 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8295 // Error data is the HTLC value (100,000) and current block height
8296 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8298 // Send a payment with the right payment hash but the wrong payment secret
8299 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8300 handle_unknown_invalid_payment_data!();
8301 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8303 // Send a payment with a random payment hash, but the right payment secret
8304 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8305 handle_unknown_invalid_payment_data!();
8306 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8308 // Send a payment with a random payment hash and random payment secret
8309 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8310 handle_unknown_invalid_payment_data!();
8311 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8315 fn test_update_err_monitor_lockdown() {
8316 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8317 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8318 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8320 // This scenario may happen in a watchtower setup, where watchtower process a block height
8321 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8322 // commitment at same time.
8324 let chanmon_cfgs = create_chanmon_cfgs(2);
8325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8327 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8329 // Create some initial channel
8330 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8331 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8333 // Rebalance the network to generate htlc in the two directions
8334 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8336 // Route a HTLC from node 0 to node 1 (but don't settle)
8337 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8339 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8340 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8341 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8342 let persister = test_utils::TestPersister::new();
8344 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8345 let monitor = monitors.get(&outpoint).unwrap();
8346 let mut w = test_utils::TestVecWriter(Vec::new());
8347 monitor.write(&mut w).unwrap();
8348 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8349 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8350 assert!(new_monitor == *monitor);
8351 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);
8352 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8355 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8356 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8357 // transaction lock time requirements here.
8358 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8359 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8361 // Try to update ChannelMonitor
8362 assert!(nodes[1].node.claim_funds(preimage));
8363 check_added_monitors!(nodes[1], 1);
8364 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8365 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8366 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8367 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8368 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8369 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8370 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8371 } else { assert!(false); }
8372 } else { assert!(false); };
8373 // Our local monitor is in-sync and hasn't processed yet timeout
8374 check_added_monitors!(nodes[0], 1);
8375 let events = nodes[0].node.get_and_clear_pending_events();
8376 assert_eq!(events.len(), 1);
8380 fn test_concurrent_monitor_claim() {
8381 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8382 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8383 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8384 // state N+1 confirms. Alice claims output from state N+1.
8386 let chanmon_cfgs = create_chanmon_cfgs(2);
8387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8389 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8391 // Create some initial channel
8392 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8393 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8395 // Rebalance the network to generate htlc in the two directions
8396 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8398 // Route a HTLC from node 0 to node 1 (but don't settle)
8399 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8401 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8402 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8403 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8404 let persister = test_utils::TestPersister::new();
8405 let watchtower_alice = {
8406 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8407 let monitor = monitors.get(&outpoint).unwrap();
8408 let mut w = test_utils::TestVecWriter(Vec::new());
8409 monitor.write(&mut w).unwrap();
8410 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8411 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8412 assert!(new_monitor == *monitor);
8413 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);
8414 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8417 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8418 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8419 // transaction lock time requirements here.
8420 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8421 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8423 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8425 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8426 assert_eq!(txn.len(), 2);
8430 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8431 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8432 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8433 let persister = test_utils::TestPersister::new();
8434 let watchtower_bob = {
8435 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8436 let monitor = monitors.get(&outpoint).unwrap();
8437 let mut w = test_utils::TestVecWriter(Vec::new());
8438 monitor.write(&mut w).unwrap();
8439 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8440 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8441 assert!(new_monitor == *monitor);
8442 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);
8443 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8446 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8447 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8449 // Route another payment to generate another update with still previous HTLC pending
8450 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8452 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8453 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8454 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8456 check_added_monitors!(nodes[1], 1);
8458 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8459 assert_eq!(updates.update_add_htlcs.len(), 1);
8460 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8461 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8462 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8463 // Watchtower Alice should already have seen the block and reject the update
8464 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8465 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8466 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8467 } else { assert!(false); }
8468 } else { assert!(false); };
8469 // Our local monitor is in-sync and hasn't processed yet timeout
8470 check_added_monitors!(nodes[0], 1);
8472 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8473 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8474 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8476 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8479 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8480 assert_eq!(txn.len(), 2);
8481 bob_state_y = txn[0].clone();
8485 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8486 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8487 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);
8489 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8490 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8491 // the onchain detection of the HTLC output
8492 assert_eq!(htlc_txn.len(), 2);
8493 check_spends!(htlc_txn[0], bob_state_y);
8494 check_spends!(htlc_txn[1], bob_state_y);
8499 fn test_pre_lockin_no_chan_closed_update() {
8500 // Test that if a peer closes a channel in response to a funding_created message we don't
8501 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8504 // Doing so would imply a channel monitor update before the initial channel monitor
8505 // registration, violating our API guarantees.
8507 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8508 // then opening a second channel with the same funding output as the first (which is not
8509 // rejected because the first channel does not exist in the ChannelManager) and closing it
8510 // before receiving funding_signed.
8511 let chanmon_cfgs = create_chanmon_cfgs(2);
8512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8516 // Create an initial channel
8517 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8518 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8519 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8520 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8521 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8523 // Move the first channel through the funding flow...
8524 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8526 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8527 check_added_monitors!(nodes[0], 0);
8529 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8530 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8531 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8532 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8536 fn test_htlc_no_detection() {
8537 // This test is a mutation to underscore the detection logic bug we had
8538 // before #653. HTLC value routed is above the remaining balance, thus
8539 // inverting HTLC and `to_remote` output. HTLC will come second and
8540 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8541 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8542 // outputs order detection for correct spending children filtring.
8544 let chanmon_cfgs = create_chanmon_cfgs(2);
8545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8549 // Create some initial channels
8550 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8552 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8553 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8554 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8555 assert_eq!(local_txn[0].input.len(), 1);
8556 assert_eq!(local_txn[0].output.len(), 3);
8557 check_spends!(local_txn[0], chan_1.3);
8559 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8560 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8561 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8562 // We deliberately connect the local tx twice as this should provoke a failure calling
8563 // this test before #653 fix.
8564 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);
8565 check_closed_broadcast!(nodes[0], true);
8566 check_added_monitors!(nodes[0], 1);
8567 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8569 let htlc_timeout = {
8570 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8571 assert_eq!(node_txn[1].input.len(), 1);
8572 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8573 check_spends!(node_txn[1], local_txn[0]);
8577 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8578 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8579 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8580 expect_payment_failed!(nodes[0], our_payment_hash, true);
8583 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8584 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8585 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8586 // Carol, Alice would be the upstream node, and Carol the downstream.)
8588 // Steps of the test:
8589 // 1) Alice sends a HTLC to Carol through Bob.
8590 // 2) Carol doesn't settle the HTLC.
8591 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8592 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8593 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8594 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8595 // 5) Carol release the preimage to Bob off-chain.
8596 // 6) Bob claims the offered output on the broadcasted commitment.
8597 let chanmon_cfgs = create_chanmon_cfgs(3);
8598 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8599 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8600 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8602 // Create some initial channels
8603 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8604 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8606 // Steps (1) and (2):
8607 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8608 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8610 // Check that Alice's commitment transaction now contains an output for this HTLC.
8611 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8612 check_spends!(alice_txn[0], chan_ab.3);
8613 assert_eq!(alice_txn[0].output.len(), 2);
8614 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8615 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8616 assert_eq!(alice_txn.len(), 2);
8618 // Steps (3) and (4):
8619 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8620 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8621 let mut force_closing_node = 0; // Alice force-closes
8622 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8623 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8624 check_closed_broadcast!(nodes[force_closing_node], true);
8625 check_added_monitors!(nodes[force_closing_node], 1);
8626 if go_onchain_before_fulfill {
8627 let txn_to_broadcast = match broadcast_alice {
8628 true => alice_txn.clone(),
8629 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8631 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8632 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8633 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8634 if broadcast_alice {
8635 check_closed_broadcast!(nodes[1], true);
8636 check_added_monitors!(nodes[1], 1);
8638 assert_eq!(bob_txn.len(), 1);
8639 check_spends!(bob_txn[0], chan_ab.3);
8643 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8644 // process of removing the HTLC from their commitment transactions.
8645 assert!(nodes[2].node.claim_funds(payment_preimage));
8646 check_added_monitors!(nodes[2], 1);
8647 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8648 assert!(carol_updates.update_add_htlcs.is_empty());
8649 assert!(carol_updates.update_fail_htlcs.is_empty());
8650 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8651 assert!(carol_updates.update_fee.is_none());
8652 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8654 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8655 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8656 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8657 if !go_onchain_before_fulfill && broadcast_alice {
8658 let events = nodes[1].node.get_and_clear_pending_msg_events();
8659 assert_eq!(events.len(), 1);
8661 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8662 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8664 _ => panic!("Unexpected event"),
8667 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8668 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8669 // Carol<->Bob's updated commitment transaction info.
8670 check_added_monitors!(nodes[1], 2);
8672 let events = nodes[1].node.get_and_clear_pending_msg_events();
8673 assert_eq!(events.len(), 2);
8674 let bob_revocation = match events[0] {
8675 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8676 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8679 _ => panic!("Unexpected event"),
8681 let bob_updates = match events[1] {
8682 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8683 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8686 _ => panic!("Unexpected event"),
8689 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8690 check_added_monitors!(nodes[2], 1);
8691 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8692 check_added_monitors!(nodes[2], 1);
8694 let events = nodes[2].node.get_and_clear_pending_msg_events();
8695 assert_eq!(events.len(), 1);
8696 let carol_revocation = match events[0] {
8697 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8698 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8701 _ => panic!("Unexpected event"),
8703 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8704 check_added_monitors!(nodes[1], 1);
8706 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8707 // here's where we put said channel's commitment tx on-chain.
8708 let mut txn_to_broadcast = alice_txn.clone();
8709 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8710 if !go_onchain_before_fulfill {
8711 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8712 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8713 // If Bob was the one to force-close, he will have already passed these checks earlier.
8714 if broadcast_alice {
8715 check_closed_broadcast!(nodes[1], true);
8716 check_added_monitors!(nodes[1], 1);
8718 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8719 if broadcast_alice {
8720 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8721 // new block being connected. The ChannelManager being notified triggers a monitor update,
8722 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8723 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8725 assert_eq!(bob_txn.len(), 3);
8726 check_spends!(bob_txn[1], chan_ab.3);
8728 assert_eq!(bob_txn.len(), 2);
8729 check_spends!(bob_txn[0], chan_ab.3);
8734 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8735 // broadcasted commitment transaction.
8737 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8738 if go_onchain_before_fulfill {
8739 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8740 assert_eq!(bob_txn.len(), 2);
8742 let script_weight = match broadcast_alice {
8743 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8744 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8746 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8747 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8748 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8749 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8750 if broadcast_alice && !go_onchain_before_fulfill {
8751 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8752 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8754 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8755 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8761 fn test_onchain_htlc_settlement_after_close() {
8762 do_test_onchain_htlc_settlement_after_close(true, true);
8763 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8764 do_test_onchain_htlc_settlement_after_close(true, false);
8765 do_test_onchain_htlc_settlement_after_close(false, false);
8769 fn test_duplicate_chan_id() {
8770 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8771 // already open we reject it and keep the old channel.
8773 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8774 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8775 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8776 // updating logic for the existing channel.
8777 let chanmon_cfgs = create_chanmon_cfgs(2);
8778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8780 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8782 // Create an initial channel
8783 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8784 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8785 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8786 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()));
8788 // Try to create a second channel with the same temporary_channel_id as the first and check
8789 // that it is rejected.
8790 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8792 let events = nodes[1].node.get_and_clear_pending_msg_events();
8793 assert_eq!(events.len(), 1);
8795 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8796 // Technically, at this point, nodes[1] would be justified in thinking both the
8797 // first (valid) and second (invalid) channels are closed, given they both have
8798 // the same non-temporary channel_id. However, currently we do not, so we just
8799 // move forward with it.
8800 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8801 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8803 _ => panic!("Unexpected event"),
8807 // Move the first channel through the funding flow...
8808 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8810 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8811 check_added_monitors!(nodes[0], 0);
8813 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8814 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8816 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8817 assert_eq!(added_monitors.len(), 1);
8818 assert_eq!(added_monitors[0].0, funding_output);
8819 added_monitors.clear();
8821 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8823 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8824 let channel_id = funding_outpoint.to_channel_id();
8826 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8829 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8830 // Technically this is allowed by the spec, but we don't support it and there's little reason
8831 // to. Still, it shouldn't cause any other issues.
8832 open_chan_msg.temporary_channel_id = channel_id;
8833 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8835 let events = nodes[1].node.get_and_clear_pending_msg_events();
8836 assert_eq!(events.len(), 1);
8838 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8839 // Technically, at this point, nodes[1] would be justified in thinking both
8840 // channels are closed, but currently we do not, so we just move forward with it.
8841 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8842 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8844 _ => panic!("Unexpected event"),
8848 // Now try to create a second channel which has a duplicate funding output.
8849 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8850 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8851 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8852 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()));
8853 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8855 let funding_created = {
8856 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8857 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8858 let logger = test_utils::TestLogger::new();
8859 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8861 check_added_monitors!(nodes[0], 0);
8862 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8863 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8864 // still needs to be cleared here.
8865 check_added_monitors!(nodes[1], 1);
8867 // ...still, nodes[1] will reject the duplicate channel.
8869 let events = nodes[1].node.get_and_clear_pending_msg_events();
8870 assert_eq!(events.len(), 1);
8872 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8873 // Technically, at this point, nodes[1] would be justified in thinking both
8874 // channels are closed, but currently we do not, so we just move forward with it.
8875 assert_eq!(msg.channel_id, channel_id);
8876 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8878 _ => panic!("Unexpected event"),
8882 // finally, finish creating the original channel and send a payment over it to make sure
8883 // everything is functional.
8884 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8886 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8887 assert_eq!(added_monitors.len(), 1);
8888 assert_eq!(added_monitors[0].0, funding_output);
8889 added_monitors.clear();
8892 let events_4 = nodes[0].node.get_and_clear_pending_events();
8893 assert_eq!(events_4.len(), 0);
8894 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8895 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8897 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8898 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8899 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8900 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8904 fn test_error_chans_closed() {
8905 // Test that we properly handle error messages, closing appropriate channels.
8907 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8908 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8909 // we can test various edge cases around it to ensure we don't regress.
8910 let chanmon_cfgs = create_chanmon_cfgs(3);
8911 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8912 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8913 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8915 // Create some initial channels
8916 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8917 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8918 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8920 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8921 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8922 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8924 // Closing a channel from a different peer has no effect
8925 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8926 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8928 // Closing one channel doesn't impact others
8929 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8930 check_added_monitors!(nodes[0], 1);
8931 check_closed_broadcast!(nodes[0], false);
8932 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8933 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8934 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);
8935 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);
8937 // A null channel ID should close all channels
8938 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8939 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8940 check_added_monitors!(nodes[0], 2);
8941 let events = nodes[0].node.get_and_clear_pending_msg_events();
8942 assert_eq!(events.len(), 2);
8944 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8945 assert_eq!(msg.contents.flags & 2, 2);
8947 _ => panic!("Unexpected event"),
8950 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8951 assert_eq!(msg.contents.flags & 2, 2);
8953 _ => panic!("Unexpected event"),
8955 // Note that at this point users of a standard PeerHandler will end up calling
8956 // peer_disconnected with no_connection_possible set to false, duplicating the
8957 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8958 // users with their own peer handling logic. We duplicate the call here, however.
8959 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8960 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8962 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8963 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8964 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8968 fn test_invalid_funding_tx() {
8969 // Test that we properly handle invalid funding transactions sent to us from a peer.
8971 // Previously, all other major lightning implementations had failed to properly sanitize
8972 // funding transactions from their counterparties, leading to a multi-implementation critical
8973 // security vulnerability (though we always sanitized properly, we've previously had
8974 // un-released crashes in the sanitization process).
8975 let chanmon_cfgs = create_chanmon_cfgs(2);
8976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8978 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8980 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8981 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()));
8982 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()));
8984 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8985 for output in tx.output.iter_mut() {
8986 // Make the confirmed funding transaction have a bogus script_pubkey
8987 output.script_pubkey = bitcoin::Script::new();
8990 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8991 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()));
8992 check_added_monitors!(nodes[1], 1);
8994 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()));
8995 check_added_monitors!(nodes[0], 1);
8997 let events_1 = nodes[0].node.get_and_clear_pending_events();
8998 assert_eq!(events_1.len(), 0);
9000 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9001 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9002 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9004 confirm_transaction_at(&nodes[1], &tx, 1);
9005 check_added_monitors!(nodes[1], 1);
9006 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9007 assert_eq!(events_2.len(), 1);
9008 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9009 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9010 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9011 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9012 } else { panic!(); }
9013 } else { panic!(); }
9014 assert_eq!(nodes[1].node.list_channels().len(), 0);
9017 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9018 // In the first version of the chain::Confirm interface, after a refactor was made to not
9019 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9020 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9021 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9022 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9023 // spending transaction until height N+1 (or greater). This was due to the way
9024 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9025 // spending transaction at the height the input transaction was confirmed at, not whether we
9026 // should broadcast a spending transaction at the current height.
9027 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9028 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9029 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9030 // until we learned about an additional block.
9032 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9033 // aren't broadcasting transactions too early (ie not broadcasting them at all).
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 mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9038 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9040 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9041 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9042 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9043 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9044 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9046 nodes[1].node.force_close_channel(&channel_id).unwrap();
9047 check_closed_broadcast!(nodes[1], true);
9048 check_added_monitors!(nodes[1], 1);
9049 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9050 assert_eq!(node_txn.len(), 1);
9052 let conf_height = nodes[1].best_block_info().1;
9053 if !test_height_before_timelock {
9054 connect_blocks(&nodes[1], 24 * 6);
9056 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9057 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9058 if test_height_before_timelock {
9059 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9060 // generate any events or broadcast any transactions
9061 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9062 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9064 // We should broadcast an HTLC transaction spending our funding transaction first
9065 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9066 assert_eq!(spending_txn.len(), 2);
9067 assert_eq!(spending_txn[0], node_txn[0]);
9068 check_spends!(spending_txn[1], node_txn[0]);
9069 // We should also generate a SpendableOutputs event with the to_self output (as its
9071 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9072 assert_eq!(descriptor_spend_txn.len(), 1);
9074 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9075 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9076 // additional block built on top of the current chain.
9077 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9078 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9079 expect_pending_htlcs_forwardable!(nodes[1]);
9080 check_added_monitors!(nodes[1], 1);
9082 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9083 assert!(updates.update_add_htlcs.is_empty());
9084 assert!(updates.update_fulfill_htlcs.is_empty());
9085 assert_eq!(updates.update_fail_htlcs.len(), 1);
9086 assert!(updates.update_fail_malformed_htlcs.is_empty());
9087 assert!(updates.update_fee.is_none());
9088 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9089 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9090 expect_payment_failed!(nodes[0], payment_hash, false);
9091 expect_payment_failure_chan_update!(nodes[0], chan_announce.contents.short_channel_id, true);
9096 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9097 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9098 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9102 fn test_keysend_payments_to_public_node() {
9103 let chanmon_cfgs = create_chanmon_cfgs(2);
9104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9106 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9108 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9109 let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
9110 let payer_pubkey = nodes[0].node.get_our_node_id();
9111 let payee_pubkey = nodes[1].node.get_our_node_id();
9112 let route = get_route(&payer_pubkey, &network_graph, &payee_pubkey, None,
9113 None, &vec![], 10000, 40,
9114 nodes[0].logger).unwrap();
9116 let test_preimage = PaymentPreimage([42; 32]);
9117 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9118 check_added_monitors!(nodes[0], 1);
9119 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9120 assert_eq!(events.len(), 1);
9121 let event = events.pop().unwrap();
9122 let path = vec![&nodes[1]];
9123 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9124 claim_payment(&nodes[0], &path, test_preimage);
9128 fn test_keysend_payments_to_private_node() {
9129 let chanmon_cfgs = create_chanmon_cfgs(2);
9130 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9132 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9134 let payer_pubkey = nodes[0].node.get_our_node_id();
9135 let payee_pubkey = nodes[1].node.get_our_node_id();
9136 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9137 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9139 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9140 let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
9141 let first_hops = nodes[0].node.list_usable_channels();
9142 let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9143 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9144 nodes[0].logger).unwrap();
9146 let test_preimage = PaymentPreimage([42; 32]);
9147 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9148 check_added_monitors!(nodes[0], 1);
9149 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9150 assert_eq!(events.len(), 1);
9151 let event = events.pop().unwrap();
9152 let path = vec![&nodes[1]];
9153 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9154 claim_payment(&nodes[0], &path, test_preimage);
9157 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, at_forward: bool, on_holder_tx: bool) {
9158 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat` policy.
9160 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9161 // trimmed-to-dust HTLC outbound balance and this new payment as included on next counterparty
9162 // commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the update.
9163 // At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC inbound
9164 // and trimmed-to-dust HTLC outbound balance and this new received HTLC as included on next
9165 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail the update.
9166 // Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel might be
9167 // available again for HTLC processing once the dust bandwidth has cleared up.
9169 let chanmon_cfgs = create_chanmon_cfgs(2);
9170 let mut config = test_default_channel_config();
9171 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(config)]);
9174 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9176 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9177 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9178 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9179 open_channel.max_accepted_htlcs = 60;
9180 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9181 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9183 accept_channel.dust_limit_satoshis = 660;
9185 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9187 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9190 if let Some(mut chan) = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9191 chan.holder_dust_limit_satoshis = 660;
9195 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9196 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()));
9197 check_added_monitors!(nodes[1], 1);
9199 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()));
9200 check_added_monitors!(nodes[0], 1);
9202 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9203 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9204 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9207 if dust_outbound_balance {
9209 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 2_300_000);
9210 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9214 route_payment(&nodes[0], &[&nodes[1]], 2_300_000);
9218 if dust_outbound_balance {
9220 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 200_000); // + 177_000 msat of HTLC-success tx at 253 sats/kWU
9221 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9225 route_payment(&nodes[0], &[&nodes[1]], 200_000); // + 167_000 msat of HTLC-timeout tx at 253 sats/kWU
9231 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { 2_300_000 } else { 200_000 });
9232 let mut config = UserConfig::default();
9234 unwrap_send_err!(nodes[1].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", 6_900_000, config.channel_options.max_dust_htlc_exposure_msat)));
9236 unwrap_send_err!(nodes[1].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", 5_200_000, config.channel_options.max_dust_htlc_exposure_msat)));
9239 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1 ], if on_holder_tx { 2_300_000 } else { 200_000 });
9240 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9241 check_added_monitors!(nodes[0], 1);
9242 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9243 assert_eq!(events.len(), 1);
9244 let payment_event = SendEvent::from_event(events.remove(0));
9245 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9247 nodes[1].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", 6_900_000, config.channel_options.max_dust_htlc_exposure_msat), 1);
9249 nodes[1].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", 5_200_000, config.channel_options.max_dust_htlc_exposure_msat), 1);
9253 let _ = nodes[1].node.get_and_clear_pending_msg_events();
9254 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9255 added_monitors.clear();
9259 fn test_max_dust_htlc_exposure() {
9260 do_test_max_dust_htlc_exposure(true, true, true);
9261 do_test_max_dust_htlc_exposure(false, true, true);
9262 do_test_max_dust_htlc_exposure(false, false, true);
9263 do_test_max_dust_htlc_exposure(false, false, false);
9264 do_test_max_dust_htlc_exposure(true, true, false);
9265 do_test_max_dust_htlc_exposure(true, false, false);
9266 do_test_max_dust_htlc_exposure(true, false, true);
9267 do_test_max_dust_htlc_exposure(false, true, false);