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 let pubkeys = chan_signer.pubkeys();
1305 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1306 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1307 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1309 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1310 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1311 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1312 let chan_signer = remote_chan.get_signer();
1313 let pubkeys = chan_signer.pubkeys();
1314 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1315 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1318 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1319 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1320 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1322 // Build the remote commitment transaction so we can sign it, and then later use the
1323 // signature for the commitment_signed message.
1324 let local_chan_balance = 1313;
1326 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1328 amount_msat: 3460001,
1329 cltv_expiry: htlc_cltv,
1331 transaction_output_index: Some(1),
1334 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1337 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1338 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1339 let local_chan_signer = local_chan.get_signer();
1340 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1344 commit_tx_keys.clone(),
1346 &mut vec![(accepted_htlc_info, ())],
1347 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1349 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1352 let commit_signed_msg = msgs::CommitmentSigned {
1355 htlc_signatures: res.1
1358 // Send the commitment_signed message to the nodes[1].
1359 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1360 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1362 // Send the RAA to nodes[1].
1363 let raa_msg = msgs::RevokeAndACK {
1365 per_commitment_secret: local_secret,
1366 next_per_commitment_point: next_local_point
1368 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1370 let events = nodes[1].node.get_and_clear_pending_msg_events();
1371 assert_eq!(events.len(), 1);
1372 // Make sure the HTLC failed in the way we expect.
1374 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1375 assert_eq!(update_fail_htlcs.len(), 1);
1376 update_fail_htlcs[0].clone()
1378 _ => panic!("Unexpected event"),
1380 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1381 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1383 check_added_monitors!(nodes[1], 2);
1387 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1388 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1389 // Set the fee rate for the channel very high, to the point where the fundee
1390 // sending any above-dust amount would result in a channel reserve violation.
1391 // In this test we check that we would be prevented from sending an HTLC in
1393 let feerate_per_kw = 253;
1394 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1395 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1398 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1400 let mut push_amt = 100_000_000;
1401 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1402 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1404 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1406 // Sending exactly enough to hit the reserve amount should be accepted
1407 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1409 // However one more HTLC should be significantly over the reserve amount and fail.
1410 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1411 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1412 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1413 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1414 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);
1418 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1419 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1420 // Set the fee rate for the channel very high, to the point where the funder
1421 // receiving 1 update_add_htlc would result in them closing the channel due
1422 // to channel reserve violation. This close could also happen if the fee went
1423 // up a more realistic amount, but many HTLCs were outstanding at the time of
1424 // the update_add_htlc.
1425 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1426 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1430 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1432 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1433 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1434 let secp_ctx = Secp256k1::new();
1435 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1436 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1437 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1438 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1439 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1440 let msg = msgs::UpdateAddHTLC {
1443 amount_msat: htlc_msat + 1,
1444 payment_hash: payment_hash,
1445 cltv_expiry: htlc_cltv,
1446 onion_routing_packet: onion_packet,
1449 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1450 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1451 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);
1452 assert_eq!(nodes[0].node.list_channels().len(), 0);
1453 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1454 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1455 check_added_monitors!(nodes[0], 1);
1459 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1460 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1461 // calculating our commitment transaction fee (this was previously broken).
1462 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1463 let feerate_per_kw = 253;
1464 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1465 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1469 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1471 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1472 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1473 // transaction fee with 0 HTLCs (183 sats)).
1474 let mut push_amt = 100_000_000;
1475 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1476 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1477 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1479 let dust_amt = crate::ln::channel::MIN_DUST_LIMIT_SATOSHIS * 1000
1480 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1481 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1482 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1483 // commitment transaction fee.
1484 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1486 // One more than the dust amt should fail, however.
1487 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1488 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1489 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1493 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1494 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1495 // calculating our counterparty's commitment transaction fee (this was previously broken).
1496 let chanmon_cfgs = create_chanmon_cfgs(2);
1497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1499 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1500 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1502 let payment_amt = 46000; // Dust amount
1503 // In the previous code, these first four payments would succeed.
1504 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1505 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1506 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1507 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1509 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1510 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1511 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1512 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1513 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1514 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1516 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1517 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1518 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1519 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1523 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1524 let chanmon_cfgs = create_chanmon_cfgs(3);
1525 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1526 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1527 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1528 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1529 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1532 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1533 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1534 let feerate = get_feerate!(nodes[0], chan.2);
1536 // Add a 2* and +1 for the fee spike reserve.
1537 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1538 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;
1539 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1541 // Add a pending HTLC.
1542 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1543 let payment_event_1 = {
1544 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1545 check_added_monitors!(nodes[0], 1);
1547 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1548 assert_eq!(events.len(), 1);
1549 SendEvent::from_event(events.remove(0))
1551 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1553 // Attempt to trigger a channel reserve violation --> payment failure.
1554 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1555 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;
1556 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1557 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1559 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1560 let secp_ctx = Secp256k1::new();
1561 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1562 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1563 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1564 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1565 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1566 let msg = msgs::UpdateAddHTLC {
1569 amount_msat: htlc_msat + 1,
1570 payment_hash: our_payment_hash_1,
1571 cltv_expiry: htlc_cltv,
1572 onion_routing_packet: onion_packet,
1575 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1576 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1577 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1578 assert_eq!(nodes[1].node.list_channels().len(), 1);
1579 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1580 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1581 check_added_monitors!(nodes[1], 1);
1585 fn test_inbound_outbound_capacity_is_not_zero() {
1586 let chanmon_cfgs = create_chanmon_cfgs(2);
1587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1589 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1590 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1591 let channels0 = node_chanmgrs[0].list_channels();
1592 let channels1 = node_chanmgrs[1].list_channels();
1593 assert_eq!(channels0.len(), 1);
1594 assert_eq!(channels1.len(), 1);
1596 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1597 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1598 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1600 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1601 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1604 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1605 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1609 fn test_channel_reserve_holding_cell_htlcs() {
1610 let chanmon_cfgs = create_chanmon_cfgs(3);
1611 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1612 // When this test was written, the default base fee floated based on the HTLC count.
1613 // It is now fixed, so we simply set the fee to the expected value here.
1614 let mut config = test_default_channel_config();
1615 config.channel_options.forwarding_fee_base_msat = 239;
1616 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1617 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1618 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1619 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1621 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1622 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1624 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1625 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1627 macro_rules! expect_forward {
1629 let mut events = $node.node.get_and_clear_pending_msg_events();
1630 assert_eq!(events.len(), 1);
1631 check_added_monitors!($node, 1);
1632 let payment_event = SendEvent::from_event(events.remove(0));
1637 let feemsat = 239; // set above
1638 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1639 let feerate = get_feerate!(nodes[0], chan_1.2);
1641 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1643 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1645 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1646 route.paths[0].last_mut().unwrap().fee_msat += 1;
1647 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1648 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1649 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)));
1650 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1651 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);
1654 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1655 // nodes[0]'s wealth
1657 let amt_msat = recv_value_0 + total_fee_msat;
1658 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1659 // Also, ensure that each payment has enough to be over the dust limit to
1660 // ensure it'll be included in each commit tx fee calculation.
1661 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1662 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1663 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1666 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1668 let (stat01_, stat11_, stat12_, stat22_) = (
1669 get_channel_value_stat!(nodes[0], chan_1.2),
1670 get_channel_value_stat!(nodes[1], chan_1.2),
1671 get_channel_value_stat!(nodes[1], chan_2.2),
1672 get_channel_value_stat!(nodes[2], chan_2.2),
1675 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1676 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1677 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1678 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1679 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1682 // adding pending output.
1683 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1684 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1685 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1686 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1687 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1688 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1689 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1690 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1691 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1693 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1694 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1695 let amt_msat_1 = recv_value_1 + total_fee_msat;
1697 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);
1698 let payment_event_1 = {
1699 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1700 check_added_monitors!(nodes[0], 1);
1702 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1703 assert_eq!(events.len(), 1);
1704 SendEvent::from_event(events.remove(0))
1706 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1708 // channel reserve test with htlc pending output > 0
1709 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1711 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1712 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1713 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1714 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1717 // split the rest to test holding cell
1718 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1719 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1720 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1721 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1723 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1724 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);
1727 // now see if they go through on both sides
1728 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);
1729 // but this will stuck in the holding cell
1730 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1731 check_added_monitors!(nodes[0], 0);
1732 let events = nodes[0].node.get_and_clear_pending_events();
1733 assert_eq!(events.len(), 0);
1735 // test with outbound holding cell amount > 0
1737 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1738 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1739 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1740 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1741 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);
1744 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);
1745 // this will also stuck in the holding cell
1746 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1747 check_added_monitors!(nodes[0], 0);
1748 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1749 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1751 // flush the pending htlc
1752 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1753 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1754 check_added_monitors!(nodes[1], 1);
1756 // the pending htlc should be promoted to committed
1757 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1758 check_added_monitors!(nodes[0], 1);
1759 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1761 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1762 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1763 // No commitment_signed so get_event_msg's assert(len == 1) passes
1764 check_added_monitors!(nodes[0], 1);
1766 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1767 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1768 check_added_monitors!(nodes[1], 1);
1770 expect_pending_htlcs_forwardable!(nodes[1]);
1772 let ref payment_event_11 = expect_forward!(nodes[1]);
1773 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1774 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1776 expect_pending_htlcs_forwardable!(nodes[2]);
1777 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1779 // flush the htlcs in the holding cell
1780 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1781 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1782 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1783 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1784 expect_pending_htlcs_forwardable!(nodes[1]);
1786 let ref payment_event_3 = expect_forward!(nodes[1]);
1787 assert_eq!(payment_event_3.msgs.len(), 2);
1788 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1789 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1791 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1792 expect_pending_htlcs_forwardable!(nodes[2]);
1794 let events = nodes[2].node.get_and_clear_pending_events();
1795 assert_eq!(events.len(), 2);
1797 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1798 assert_eq!(our_payment_hash_21, *payment_hash);
1799 assert_eq!(recv_value_21, amt);
1801 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1802 assert!(payment_preimage.is_none());
1803 assert_eq!(our_payment_secret_21, *payment_secret);
1805 _ => panic!("expected PaymentPurpose::InvoicePayment")
1808 _ => panic!("Unexpected event"),
1811 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1812 assert_eq!(our_payment_hash_22, *payment_hash);
1813 assert_eq!(recv_value_22, amt);
1815 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1816 assert!(payment_preimage.is_none());
1817 assert_eq!(our_payment_secret_22, *payment_secret);
1819 _ => panic!("expected PaymentPurpose::InvoicePayment")
1822 _ => panic!("Unexpected event"),
1825 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1826 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1827 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1829 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1830 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1831 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1833 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1834 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);
1835 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1836 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1837 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1839 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1840 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1844 fn channel_reserve_in_flight_removes() {
1845 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1846 // can send to its counterparty, but due to update ordering, the other side may not yet have
1847 // considered those HTLCs fully removed.
1848 // This tests that we don't count HTLCs which will not be included in the next remote
1849 // commitment transaction towards the reserve value (as it implies no commitment transaction
1850 // will be generated which violates the remote reserve value).
1851 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1853 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1854 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1855 // you only consider the value of the first HTLC, it may not),
1856 // * start routing a third HTLC from A to B,
1857 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1858 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1859 // * deliver the first fulfill from B
1860 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1862 // * deliver A's response CS and RAA.
1863 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1864 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1865 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1866 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1867 let chanmon_cfgs = create_chanmon_cfgs(2);
1868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1870 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1871 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1872 let logger = test_utils::TestLogger::new();
1874 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1875 // Route the first two HTLCs.
1876 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1877 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1879 // Start routing the third HTLC (this is just used to get everyone in the right state).
1880 let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
1882 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1883 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();
1884 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1885 check_added_monitors!(nodes[0], 1);
1886 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1887 assert_eq!(events.len(), 1);
1888 SendEvent::from_event(events.remove(0))
1891 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1892 // initial fulfill/CS.
1893 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1894 check_added_monitors!(nodes[1], 1);
1895 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1897 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1898 // remove the second HTLC when we send the HTLC back from B to A.
1899 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1900 check_added_monitors!(nodes[1], 1);
1901 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1903 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1904 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1905 check_added_monitors!(nodes[0], 1);
1906 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1907 expect_payment_sent!(nodes[0], payment_preimage_1);
1909 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1910 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1911 check_added_monitors!(nodes[1], 1);
1912 // B is already AwaitingRAA, so cant generate a CS here
1913 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1915 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1916 check_added_monitors!(nodes[1], 1);
1917 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1920 check_added_monitors!(nodes[0], 1);
1921 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1923 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1924 check_added_monitors!(nodes[1], 1);
1925 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1927 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1928 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1929 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1930 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1931 // on-chain as necessary).
1932 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1933 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1934 check_added_monitors!(nodes[0], 1);
1935 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936 expect_payment_sent!(nodes[0], payment_preimage_2);
1938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1939 check_added_monitors!(nodes[1], 1);
1940 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1942 expect_pending_htlcs_forwardable!(nodes[1]);
1943 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1945 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1946 // resolve the second HTLC from A's point of view.
1947 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1948 check_added_monitors!(nodes[0], 1);
1949 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1951 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1952 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1953 let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
1955 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1956 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();
1957 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1958 check_added_monitors!(nodes[1], 1);
1959 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1960 assert_eq!(events.len(), 1);
1961 SendEvent::from_event(events.remove(0))
1964 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1965 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1966 check_added_monitors!(nodes[0], 1);
1967 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1969 // Now just resolve all the outstanding messages/HTLCs for completeness...
1971 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1972 check_added_monitors!(nodes[1], 1);
1973 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1975 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1976 check_added_monitors!(nodes[1], 1);
1978 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1979 check_added_monitors!(nodes[0], 1);
1980 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1982 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1983 check_added_monitors!(nodes[1], 1);
1984 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1986 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1987 check_added_monitors!(nodes[0], 1);
1989 expect_pending_htlcs_forwardable!(nodes[0]);
1990 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
1992 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1993 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1997 fn channel_monitor_network_test() {
1998 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1999 // tests that ChannelMonitor is able to recover from various states.
2000 let chanmon_cfgs = create_chanmon_cfgs(5);
2001 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2002 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2003 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2005 // Create some initial channels
2006 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2007 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2008 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2009 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2011 // Make sure all nodes are at the same starting height
2012 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2013 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2014 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2015 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2016 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2018 // Rebalance the network a bit by relaying one payment through all the channels...
2019 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2020 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2021 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2022 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2024 // Simple case with no pending HTLCs:
2025 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2026 check_added_monitors!(nodes[1], 1);
2027 check_closed_broadcast!(nodes[1], false);
2029 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2030 assert_eq!(node_txn.len(), 1);
2031 mine_transaction(&nodes[0], &node_txn[0]);
2032 check_added_monitors!(nodes[0], 1);
2033 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2035 check_closed_broadcast!(nodes[0], true);
2036 assert_eq!(nodes[0].node.list_channels().len(), 0);
2037 assert_eq!(nodes[1].node.list_channels().len(), 1);
2039 // One pending HTLC is discarded by the force-close:
2040 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2042 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2043 // broadcasted until we reach the timelock time).
2044 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2045 check_closed_broadcast!(nodes[1], false);
2046 check_added_monitors!(nodes[1], 1);
2048 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2049 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2050 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2051 mine_transaction(&nodes[2], &node_txn[0]);
2052 check_added_monitors!(nodes[2], 1);
2053 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2055 check_closed_broadcast!(nodes[2], true);
2056 assert_eq!(nodes[1].node.list_channels().len(), 0);
2057 assert_eq!(nodes[2].node.list_channels().len(), 1);
2059 macro_rules! claim_funds {
2060 ($node: expr, $prev_node: expr, $preimage: expr) => {
2062 assert!($node.node.claim_funds($preimage));
2063 check_added_monitors!($node, 1);
2065 let events = $node.node.get_and_clear_pending_msg_events();
2066 assert_eq!(events.len(), 1);
2068 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2069 assert!(update_add_htlcs.is_empty());
2070 assert!(update_fail_htlcs.is_empty());
2071 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2073 _ => panic!("Unexpected event"),
2079 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2080 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2081 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2082 check_added_monitors!(nodes[2], 1);
2083 check_closed_broadcast!(nodes[2], false);
2084 let node2_commitment_txid;
2086 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2087 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2088 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2089 node2_commitment_txid = node_txn[0].txid();
2091 // Claim the payment on nodes[3], giving it knowledge of the preimage
2092 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2093 mine_transaction(&nodes[3], &node_txn[0]);
2094 check_added_monitors!(nodes[3], 1);
2095 check_preimage_claim(&nodes[3], &node_txn);
2097 check_closed_broadcast!(nodes[3], true);
2098 assert_eq!(nodes[2].node.list_channels().len(), 0);
2099 assert_eq!(nodes[3].node.list_channels().len(), 1);
2101 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2102 // confusing us in the following tests.
2103 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2105 // One pending HTLC to time out:
2106 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2107 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2110 let (close_chan_update_1, close_chan_update_2) = {
2111 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2112 let events = nodes[3].node.get_and_clear_pending_msg_events();
2113 assert_eq!(events.len(), 2);
2114 let close_chan_update_1 = match events[0] {
2115 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2118 _ => panic!("Unexpected event"),
2121 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2122 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2124 _ => panic!("Unexpected event"),
2126 check_added_monitors!(nodes[3], 1);
2128 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2130 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2131 node_txn.retain(|tx| {
2132 if tx.input[0].previous_output.txid == node2_commitment_txid {
2138 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2140 // Claim the payment on nodes[4], giving it knowledge of the preimage
2141 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2143 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2144 let events = nodes[4].node.get_and_clear_pending_msg_events();
2145 assert_eq!(events.len(), 2);
2146 let close_chan_update_2 = match events[0] {
2147 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2150 _ => panic!("Unexpected event"),
2153 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2154 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2156 _ => panic!("Unexpected event"),
2158 check_added_monitors!(nodes[4], 1);
2159 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2161 mine_transaction(&nodes[4], &node_txn[0]);
2162 check_preimage_claim(&nodes[4], &node_txn);
2163 (close_chan_update_1, close_chan_update_2)
2165 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2166 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2167 assert_eq!(nodes[3].node.list_channels().len(), 0);
2168 assert_eq!(nodes[4].node.list_channels().len(), 0);
2170 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2174 fn test_justice_tx() {
2175 // Test justice txn built on revoked HTLC-Success tx, against both sides
2176 let mut alice_config = UserConfig::default();
2177 alice_config.channel_options.announced_channel = true;
2178 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2179 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2180 let mut bob_config = UserConfig::default();
2181 bob_config.channel_options.announced_channel = true;
2182 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2183 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2184 let user_cfgs = [Some(alice_config), Some(bob_config)];
2185 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2186 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2187 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2190 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2191 // Create some new channels:
2192 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2194 // A pending HTLC which will be revoked:
2195 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2196 // Get the will-be-revoked local txn from nodes[0]
2197 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2198 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2199 assert_eq!(revoked_local_txn[0].input.len(), 1);
2200 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2201 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2202 assert_eq!(revoked_local_txn[1].input.len(), 1);
2203 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2204 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2205 // Revoke the old state
2206 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2209 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2211 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2212 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2213 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2215 check_spends!(node_txn[0], revoked_local_txn[0]);
2216 node_txn.swap_remove(0);
2217 node_txn.truncate(1);
2219 check_added_monitors!(nodes[1], 1);
2220 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2222 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2223 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2224 // Verify broadcast of revoked HTLC-timeout
2225 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2226 check_added_monitors!(nodes[0], 1);
2227 // Broadcast revoked HTLC-timeout on node 1
2228 mine_transaction(&nodes[1], &node_txn[1]);
2229 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2231 get_announce_close_broadcast_events(&nodes, 0, 1);
2233 assert_eq!(nodes[0].node.list_channels().len(), 0);
2234 assert_eq!(nodes[1].node.list_channels().len(), 0);
2236 // We test justice_tx build by A on B's revoked HTLC-Success tx
2237 // Create some new channels:
2238 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2240 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2244 // A pending HTLC which will be revoked:
2245 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2246 // Get the will-be-revoked local txn from B
2247 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2248 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2249 assert_eq!(revoked_local_txn[0].input.len(), 1);
2250 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2251 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2252 // Revoke the old state
2253 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2255 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2257 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2258 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2259 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2261 check_spends!(node_txn[0], revoked_local_txn[0]);
2262 node_txn.swap_remove(0);
2264 check_added_monitors!(nodes[0], 1);
2265 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2267 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2268 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2269 check_added_monitors!(nodes[1], 1);
2270 mine_transaction(&nodes[0], &node_txn[1]);
2271 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2273 get_announce_close_broadcast_events(&nodes, 0, 1);
2274 assert_eq!(nodes[0].node.list_channels().len(), 0);
2275 assert_eq!(nodes[1].node.list_channels().len(), 0);
2279 fn revoked_output_claim() {
2280 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2281 // transaction is broadcast by its counterparty
2282 let chanmon_cfgs = create_chanmon_cfgs(2);
2283 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2284 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2285 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2286 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2287 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2288 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2289 assert_eq!(revoked_local_txn.len(), 1);
2290 // Only output is the full channel value back to nodes[0]:
2291 assert_eq!(revoked_local_txn[0].output.len(), 1);
2292 // Send a payment through, updating everyone's latest commitment txn
2293 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2295 // Inform nodes[1] that nodes[0] broadcast a stale tx
2296 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2297 check_added_monitors!(nodes[1], 1);
2298 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2299 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2301 check_spends!(node_txn[0], revoked_local_txn[0]);
2302 check_spends!(node_txn[1], chan_1.3);
2304 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2305 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2306 get_announce_close_broadcast_events(&nodes, 0, 1);
2307 check_added_monitors!(nodes[0], 1)
2311 fn claim_htlc_outputs_shared_tx() {
2312 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2313 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2314 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2315 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2316 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2317 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2319 // Create some new channel:
2320 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2322 // Rebalance the network to generate htlc in the two directions
2323 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2324 // 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
2325 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2326 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2328 // Get the will-be-revoked local txn from node[0]
2329 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2330 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2331 assert_eq!(revoked_local_txn[0].input.len(), 1);
2332 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2333 assert_eq!(revoked_local_txn[1].input.len(), 1);
2334 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2335 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2336 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2338 //Revoke the old state
2339 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2342 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2343 check_added_monitors!(nodes[0], 1);
2344 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2345 check_added_monitors!(nodes[1], 1);
2346 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2347 expect_payment_failed!(nodes[1], payment_hash_2, true);
2349 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2350 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2352 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2353 check_spends!(node_txn[0], revoked_local_txn[0]);
2355 let mut witness_lens = BTreeSet::new();
2356 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2357 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2358 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2359 assert_eq!(witness_lens.len(), 3);
2360 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2361 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2362 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2364 // Next nodes[1] broadcasts its current local tx state:
2365 assert_eq!(node_txn[1].input.len(), 1);
2366 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2368 get_announce_close_broadcast_events(&nodes, 0, 1);
2369 assert_eq!(nodes[0].node.list_channels().len(), 0);
2370 assert_eq!(nodes[1].node.list_channels().len(), 0);
2374 fn claim_htlc_outputs_single_tx() {
2375 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2376 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2377 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2380 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2382 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2384 // Rebalance the network to generate htlc in the two directions
2385 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2386 // 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
2387 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2388 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2389 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2391 // Get the will-be-revoked local txn from node[0]
2392 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2394 //Revoke the old state
2395 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2398 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2399 check_added_monitors!(nodes[0], 1);
2400 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2401 check_added_monitors!(nodes[1], 1);
2402 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2404 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2405 expect_payment_failed!(nodes[1], payment_hash_2, true);
2407 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2408 assert_eq!(node_txn.len(), 9);
2409 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2410 // ChannelManager: local commmitment + local HTLC-timeout (2)
2411 // 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)
2412 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2414 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2415 assert_eq!(node_txn[0].input.len(), 1);
2416 check_spends!(node_txn[0], chan_1.3);
2417 assert_eq!(node_txn[1].input.len(), 1);
2418 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2419 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2420 check_spends!(node_txn[1], node_txn[0]);
2422 // Justice transactions are indices 1-2-4
2423 assert_eq!(node_txn[2].input.len(), 1);
2424 assert_eq!(node_txn[3].input.len(), 1);
2425 assert_eq!(node_txn[4].input.len(), 1);
2427 check_spends!(node_txn[2], revoked_local_txn[0]);
2428 check_spends!(node_txn[3], revoked_local_txn[0]);
2429 check_spends!(node_txn[4], revoked_local_txn[0]);
2431 let mut witness_lens = BTreeSet::new();
2432 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2433 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2434 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2435 assert_eq!(witness_lens.len(), 3);
2436 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2437 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2438 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2440 get_announce_close_broadcast_events(&nodes, 0, 1);
2441 assert_eq!(nodes[0].node.list_channels().len(), 0);
2442 assert_eq!(nodes[1].node.list_channels().len(), 0);
2446 fn test_htlc_on_chain_success() {
2447 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2448 // the preimage backward accordingly. So here we test that ChannelManager is
2449 // broadcasting the right event to other nodes in payment path.
2450 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2451 // A --------------------> B ----------------------> C (preimage)
2452 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2453 // commitment transaction was broadcast.
2454 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2456 // B should be able to claim via preimage if A then broadcasts its local tx.
2457 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2458 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2459 // PaymentSent event).
2461 let chanmon_cfgs = create_chanmon_cfgs(3);
2462 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2463 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2464 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2466 // Create some initial channels
2467 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2468 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2470 // Ensure all nodes are at the same height
2471 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2472 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2473 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2474 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2476 // Rebalance the network a bit by relaying one payment through all the channels...
2477 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2478 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2480 let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2481 let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2483 // Broadcast legit commitment tx from C on B's chain
2484 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2485 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2486 assert_eq!(commitment_tx.len(), 1);
2487 check_spends!(commitment_tx[0], chan_2.3);
2488 nodes[2].node.claim_funds(our_payment_preimage);
2489 nodes[2].node.claim_funds(our_payment_preimage_2);
2490 check_added_monitors!(nodes[2], 2);
2491 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2492 assert!(updates.update_add_htlcs.is_empty());
2493 assert!(updates.update_fail_htlcs.is_empty());
2494 assert!(updates.update_fail_malformed_htlcs.is_empty());
2495 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2497 mine_transaction(&nodes[2], &commitment_tx[0]);
2498 check_closed_broadcast!(nodes[2], true);
2499 check_added_monitors!(nodes[2], 1);
2500 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)
2501 assert_eq!(node_txn.len(), 5);
2502 assert_eq!(node_txn[0], node_txn[3]);
2503 assert_eq!(node_txn[1], node_txn[4]);
2504 assert_eq!(node_txn[2], commitment_tx[0]);
2505 check_spends!(node_txn[0], commitment_tx[0]);
2506 check_spends!(node_txn[1], commitment_tx[0]);
2507 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2508 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2509 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2510 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2511 assert_eq!(node_txn[0].lock_time, 0);
2512 assert_eq!(node_txn[1].lock_time, 0);
2514 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2515 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2516 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2517 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2519 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2520 assert_eq!(added_monitors.len(), 1);
2521 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2522 added_monitors.clear();
2524 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2525 assert_eq!(forwarded_events.len(), 2);
2526 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[0] {
2527 } else { panic!(); }
2528 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2529 } else { panic!(); }
2530 let events = nodes[1].node.get_and_clear_pending_msg_events();
2532 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2533 assert_eq!(added_monitors.len(), 2);
2534 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2535 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2536 added_monitors.clear();
2538 assert_eq!(events.len(), 3);
2540 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2541 _ => panic!("Unexpected event"),
2544 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2545 _ => panic!("Unexpected event"),
2549 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, .. } } => {
2550 assert!(update_add_htlcs.is_empty());
2551 assert!(update_fail_htlcs.is_empty());
2552 assert_eq!(update_fulfill_htlcs.len(), 1);
2553 assert!(update_fail_malformed_htlcs.is_empty());
2554 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2556 _ => panic!("Unexpected event"),
2558 macro_rules! check_tx_local_broadcast {
2559 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2560 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2561 assert_eq!(node_txn.len(), 3);
2562 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2563 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2564 check_spends!(node_txn[1], $commitment_tx);
2565 check_spends!(node_txn[2], $commitment_tx);
2566 assert_ne!(node_txn[1].lock_time, 0);
2567 assert_ne!(node_txn[2].lock_time, 0);
2569 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2570 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2571 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2572 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2574 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2575 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2576 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2577 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2579 check_spends!(node_txn[0], $chan_tx);
2580 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2584 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2585 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2586 // timeout-claim of the output that nodes[2] just claimed via success.
2587 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2589 // Broadcast legit commitment tx from A on B's chain
2590 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2591 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2592 check_spends!(node_a_commitment_tx[0], chan_1.3);
2593 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2594 check_closed_broadcast!(nodes[1], true);
2595 check_added_monitors!(nodes[1], 1);
2596 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2597 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2598 let commitment_spend =
2599 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2600 check_spends!(node_txn[1], commitment_tx[0]);
2601 check_spends!(node_txn[2], commitment_tx[0]);
2602 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2605 check_spends!(node_txn[0], commitment_tx[0]);
2606 check_spends!(node_txn[1], commitment_tx[0]);
2607 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2611 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2612 assert_eq!(commitment_spend.input.len(), 2);
2613 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2614 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2615 assert_eq!(commitment_spend.lock_time, 0);
2616 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2617 check_spends!(node_txn[3], chan_1.3);
2618 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2619 check_spends!(node_txn[4], node_txn[3]);
2620 check_spends!(node_txn[5], node_txn[3]);
2621 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2622 // we already checked the same situation with A.
2624 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2625 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2626 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2627 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2628 check_closed_broadcast!(nodes[0], true);
2629 check_added_monitors!(nodes[0], 1);
2630 let events = nodes[0].node.get_and_clear_pending_events();
2631 assert_eq!(events.len(), 2);
2632 let mut first_claimed = false;
2633 for event in events {
2635 Event::PaymentSent { payment_preimage } => {
2636 if payment_preimage == our_payment_preimage {
2637 assert!(!first_claimed);
2638 first_claimed = true;
2640 assert_eq!(payment_preimage, our_payment_preimage_2);
2643 _ => panic!("Unexpected event"),
2646 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2649 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2650 // Test that in case of a unilateral close onchain, we detect the state of output and
2651 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2652 // broadcasting the right event to other nodes in payment path.
2653 // A ------------------> B ----------------------> C (timeout)
2654 // B's commitment tx C's commitment tx
2656 // B's HTLC timeout tx B's timeout tx
2658 let chanmon_cfgs = create_chanmon_cfgs(3);
2659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2661 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2662 *nodes[0].connect_style.borrow_mut() = connect_style;
2663 *nodes[1].connect_style.borrow_mut() = connect_style;
2664 *nodes[2].connect_style.borrow_mut() = connect_style;
2666 // Create some intial channels
2667 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2668 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2670 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2671 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2672 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2674 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2676 // Broadcast legit commitment tx from C on B's chain
2677 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2678 check_spends!(commitment_tx[0], chan_2.3);
2679 nodes[2].node.fail_htlc_backwards(&payment_hash);
2680 check_added_monitors!(nodes[2], 0);
2681 expect_pending_htlcs_forwardable!(nodes[2]);
2682 check_added_monitors!(nodes[2], 1);
2684 let events = nodes[2].node.get_and_clear_pending_msg_events();
2685 assert_eq!(events.len(), 1);
2687 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, .. } } => {
2688 assert!(update_add_htlcs.is_empty());
2689 assert!(!update_fail_htlcs.is_empty());
2690 assert!(update_fulfill_htlcs.is_empty());
2691 assert!(update_fail_malformed_htlcs.is_empty());
2692 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2694 _ => panic!("Unexpected event"),
2696 mine_transaction(&nodes[2], &commitment_tx[0]);
2697 check_closed_broadcast!(nodes[2], true);
2698 check_added_monitors!(nodes[2], 1);
2699 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2700 assert_eq!(node_txn.len(), 1);
2701 check_spends!(node_txn[0], chan_2.3);
2702 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2704 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2705 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2706 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2707 mine_transaction(&nodes[1], &commitment_tx[0]);
2710 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2711 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2712 assert_eq!(node_txn[0], node_txn[3]);
2713 assert_eq!(node_txn[1], node_txn[4]);
2715 check_spends!(node_txn[2], commitment_tx[0]);
2716 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2718 check_spends!(node_txn[0], chan_2.3);
2719 check_spends!(node_txn[1], node_txn[0]);
2720 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2721 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2723 timeout_tx = node_txn[2].clone();
2727 mine_transaction(&nodes[1], &timeout_tx);
2728 check_added_monitors!(nodes[1], 1);
2729 check_closed_broadcast!(nodes[1], true);
2731 // B will rebroadcast a fee-bumped timeout transaction here.
2732 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2733 assert_eq!(node_txn.len(), 1);
2734 check_spends!(node_txn[0], commitment_tx[0]);
2737 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2739 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2740 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2741 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2742 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2743 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2744 if node_txn.len() == 1 {
2745 check_spends!(node_txn[0], chan_2.3);
2747 assert_eq!(node_txn.len(), 0);
2751 expect_pending_htlcs_forwardable!(nodes[1]);
2752 check_added_monitors!(nodes[1], 1);
2753 let events = nodes[1].node.get_and_clear_pending_msg_events();
2754 assert_eq!(events.len(), 1);
2756 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, .. } } => {
2757 assert!(update_add_htlcs.is_empty());
2758 assert!(!update_fail_htlcs.is_empty());
2759 assert!(update_fulfill_htlcs.is_empty());
2760 assert!(update_fail_malformed_htlcs.is_empty());
2761 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2763 _ => panic!("Unexpected event"),
2766 // Broadcast legit commitment tx from B on A's chain
2767 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2768 check_spends!(commitment_tx[0], chan_1.3);
2770 mine_transaction(&nodes[0], &commitment_tx[0]);
2771 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2773 check_closed_broadcast!(nodes[0], true);
2774 check_added_monitors!(nodes[0], 1);
2775 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2776 assert_eq!(node_txn.len(), 2);
2777 check_spends!(node_txn[0], chan_1.3);
2778 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2779 check_spends!(node_txn[1], commitment_tx[0]);
2780 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2784 fn test_htlc_on_chain_timeout() {
2785 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2786 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2787 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2791 fn test_simple_commitment_revoked_fail_backward() {
2792 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2793 // and fail backward accordingly.
2795 let chanmon_cfgs = create_chanmon_cfgs(3);
2796 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2797 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2798 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2800 // Create some initial channels
2801 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2802 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2804 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2805 // Get the will-be-revoked local txn from nodes[2]
2806 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2807 // Revoke the old state
2808 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2810 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2812 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2813 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2814 check_added_monitors!(nodes[1], 1);
2815 check_closed_broadcast!(nodes[1], true);
2817 expect_pending_htlcs_forwardable!(nodes[1]);
2818 check_added_monitors!(nodes[1], 1);
2819 let events = nodes[1].node.get_and_clear_pending_msg_events();
2820 assert_eq!(events.len(), 1);
2822 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, .. } } => {
2823 assert!(update_add_htlcs.is_empty());
2824 assert_eq!(update_fail_htlcs.len(), 1);
2825 assert!(update_fulfill_htlcs.is_empty());
2826 assert!(update_fail_malformed_htlcs.is_empty());
2827 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2829 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2830 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2831 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, true);
2832 expect_payment_failed!(nodes[0], payment_hash, false);
2834 _ => panic!("Unexpected event"),
2838 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2839 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2840 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2841 // commitment transaction anymore.
2842 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2843 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2844 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2845 // technically disallowed and we should probably handle it reasonably.
2846 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2847 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2849 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2850 // commitment_signed (implying it will be in the latest remote commitment transaction).
2851 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2852 // and once they revoke the previous commitment transaction (allowing us to send a new
2853 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2854 let chanmon_cfgs = create_chanmon_cfgs(3);
2855 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2856 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2857 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2859 // Create some initial channels
2860 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2861 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2863 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 });
2864 // Get the will-be-revoked local txn from nodes[2]
2865 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2866 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2867 // Revoke the old state
2868 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2870 let value = if use_dust {
2871 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2872 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2873 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2876 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2877 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2878 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2880 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2881 expect_pending_htlcs_forwardable!(nodes[2]);
2882 check_added_monitors!(nodes[2], 1);
2883 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2884 assert!(updates.update_add_htlcs.is_empty());
2885 assert!(updates.update_fulfill_htlcs.is_empty());
2886 assert!(updates.update_fail_malformed_htlcs.is_empty());
2887 assert_eq!(updates.update_fail_htlcs.len(), 1);
2888 assert!(updates.update_fee.is_none());
2889 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2890 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2891 // Drop the last RAA from 3 -> 2
2893 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2894 expect_pending_htlcs_forwardable!(nodes[2]);
2895 check_added_monitors!(nodes[2], 1);
2896 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2897 assert!(updates.update_add_htlcs.is_empty());
2898 assert!(updates.update_fulfill_htlcs.is_empty());
2899 assert!(updates.update_fail_malformed_htlcs.is_empty());
2900 assert_eq!(updates.update_fail_htlcs.len(), 1);
2901 assert!(updates.update_fee.is_none());
2902 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2903 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2904 check_added_monitors!(nodes[1], 1);
2905 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2906 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2907 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2908 check_added_monitors!(nodes[2], 1);
2910 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2911 expect_pending_htlcs_forwardable!(nodes[2]);
2912 check_added_monitors!(nodes[2], 1);
2913 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2914 assert!(updates.update_add_htlcs.is_empty());
2915 assert!(updates.update_fulfill_htlcs.is_empty());
2916 assert!(updates.update_fail_malformed_htlcs.is_empty());
2917 assert_eq!(updates.update_fail_htlcs.len(), 1);
2918 assert!(updates.update_fee.is_none());
2919 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2920 // At this point first_payment_hash has dropped out of the latest two commitment
2921 // transactions that nodes[1] is tracking...
2922 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2923 check_added_monitors!(nodes[1], 1);
2924 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2925 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2926 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2927 check_added_monitors!(nodes[2], 1);
2929 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2930 // on nodes[2]'s RAA.
2931 let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
2932 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2933 let logger = test_utils::TestLogger::new();
2934 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();
2935 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2936 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2937 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2938 check_added_monitors!(nodes[1], 0);
2941 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2942 // One monitor for the new revocation preimage, no second on as we won't generate a new
2943 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2944 check_added_monitors!(nodes[1], 1);
2945 let events = nodes[1].node.get_and_clear_pending_events();
2946 assert_eq!(events.len(), 1);
2948 Event::PendingHTLCsForwardable { .. } => { },
2949 _ => panic!("Unexpected event"),
2951 // Deliberately don't process the pending fail-back so they all fail back at once after
2952 // block connection just like the !deliver_bs_raa case
2955 let mut failed_htlcs = HashSet::new();
2956 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2958 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2959 check_added_monitors!(nodes[1], 1);
2960 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2962 let events = nodes[1].node.get_and_clear_pending_events();
2963 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2965 Event::PaymentFailed { ref payment_hash, .. } => {
2966 assert_eq!(*payment_hash, fourth_payment_hash);
2968 _ => panic!("Unexpected event"),
2970 if !deliver_bs_raa {
2972 Event::PendingHTLCsForwardable { .. } => { },
2973 _ => panic!("Unexpected event"),
2976 nodes[1].node.process_pending_htlc_forwards();
2977 check_added_monitors!(nodes[1], 1);
2979 let events = nodes[1].node.get_and_clear_pending_msg_events();
2980 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
2981 match events[if deliver_bs_raa { 1 } else { 0 }] {
2982 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2983 _ => panic!("Unexpected event"),
2985 match events[if deliver_bs_raa { 2 } else { 1 }] {
2986 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
2987 assert_eq!(channel_id, chan_2.2);
2988 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
2990 _ => panic!("Unexpected event"),
2994 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, .. } } => {
2995 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2996 assert_eq!(update_add_htlcs.len(), 1);
2997 assert!(update_fulfill_htlcs.is_empty());
2998 assert!(update_fail_htlcs.is_empty());
2999 assert!(update_fail_malformed_htlcs.is_empty());
3001 _ => panic!("Unexpected event"),
3004 match events[if deliver_bs_raa { 3 } else { 2 }] {
3005 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, .. } } => {
3006 assert!(update_add_htlcs.is_empty());
3007 assert_eq!(update_fail_htlcs.len(), 3);
3008 assert!(update_fulfill_htlcs.is_empty());
3009 assert!(update_fail_malformed_htlcs.is_empty());
3010 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3012 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3013 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3014 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3016 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3018 let events = nodes[0].node.get_and_clear_pending_msg_events();
3019 // If we delivered B's RAA we got an unknown preimage error, not something
3020 // that we should update our routing table for.
3021 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3022 for event in events {
3024 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3025 _ => panic!("Unexpected event"),
3028 let events = nodes[0].node.get_and_clear_pending_events();
3029 assert_eq!(events.len(), 3);
3031 Event::PaymentFailed { ref payment_hash, .. } => {
3032 assert!(failed_htlcs.insert(payment_hash.0));
3034 _ => panic!("Unexpected event"),
3037 Event::PaymentFailed { ref payment_hash, .. } => {
3038 assert!(failed_htlcs.insert(payment_hash.0));
3040 _ => panic!("Unexpected event"),
3043 Event::PaymentFailed { ref payment_hash, .. } => {
3044 assert!(failed_htlcs.insert(payment_hash.0));
3046 _ => panic!("Unexpected event"),
3049 _ => panic!("Unexpected event"),
3052 assert!(failed_htlcs.contains(&first_payment_hash.0));
3053 assert!(failed_htlcs.contains(&second_payment_hash.0));
3054 assert!(failed_htlcs.contains(&third_payment_hash.0));
3058 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3059 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3060 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3061 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3062 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3066 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3067 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3068 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3069 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3070 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3074 fn fail_backward_pending_htlc_upon_channel_failure() {
3075 let chanmon_cfgs = create_chanmon_cfgs(2);
3076 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3077 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3078 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3079 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3080 let logger = test_utils::TestLogger::new();
3082 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3084 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3085 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3086 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();
3087 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3088 check_added_monitors!(nodes[0], 1);
3090 let payment_event = {
3091 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3092 assert_eq!(events.len(), 1);
3093 SendEvent::from_event(events.remove(0))
3095 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3096 assert_eq!(payment_event.msgs.len(), 1);
3099 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3100 let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3102 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3103 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();
3104 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3105 check_added_monitors!(nodes[0], 0);
3107 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3110 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3112 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3114 let secp_ctx = Secp256k1::new();
3115 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3116 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3117 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3118 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();
3119 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3120 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3121 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3123 // Send a 0-msat update_add_htlc to fail the channel.
3124 let update_add_htlc = msgs::UpdateAddHTLC {
3130 onion_routing_packet,
3132 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3135 // Check that Alice fails backward the pending HTLC from the second payment.
3136 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3137 check_closed_broadcast!(nodes[0], true);
3138 check_added_monitors!(nodes[0], 1);
3142 fn test_htlc_ignore_latest_remote_commitment() {
3143 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3144 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3145 let chanmon_cfgs = create_chanmon_cfgs(2);
3146 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3147 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3148 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3149 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3151 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3152 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3153 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3154 check_closed_broadcast!(nodes[0], true);
3155 check_added_monitors!(nodes[0], 1);
3157 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3158 assert_eq!(node_txn.len(), 3);
3159 assert_eq!(node_txn[0], node_txn[1]);
3161 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3162 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3163 check_closed_broadcast!(nodes[1], true);
3164 check_added_monitors!(nodes[1], 1);
3166 // Duplicate the connect_block call since this may happen due to other listeners
3167 // registering new transactions
3168 header.prev_blockhash = header.block_hash();
3169 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3173 fn test_force_close_fail_back() {
3174 // Check which HTLCs are failed-backwards on channel force-closure
3175 let chanmon_cfgs = create_chanmon_cfgs(3);
3176 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3177 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3178 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3179 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3180 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3181 let logger = test_utils::TestLogger::new();
3183 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3185 let mut payment_event = {
3186 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3187 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();
3188 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3189 check_added_monitors!(nodes[0], 1);
3191 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3192 assert_eq!(events.len(), 1);
3193 SendEvent::from_event(events.remove(0))
3196 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3197 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3199 expect_pending_htlcs_forwardable!(nodes[1]);
3201 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3202 assert_eq!(events_2.len(), 1);
3203 payment_event = SendEvent::from_event(events_2.remove(0));
3204 assert_eq!(payment_event.msgs.len(), 1);
3206 check_added_monitors!(nodes[1], 1);
3207 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3208 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3209 check_added_monitors!(nodes[2], 1);
3210 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3212 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3213 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3214 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3216 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3217 check_closed_broadcast!(nodes[2], true);
3218 check_added_monitors!(nodes[2], 1);
3220 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3221 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3222 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3223 // back to nodes[1] upon timeout otherwise.
3224 assert_eq!(node_txn.len(), 1);
3228 mine_transaction(&nodes[1], &tx);
3230 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3231 check_closed_broadcast!(nodes[1], true);
3232 check_added_monitors!(nodes[1], 1);
3234 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3236 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3237 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3238 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3240 mine_transaction(&nodes[2], &tx);
3241 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3242 assert_eq!(node_txn.len(), 1);
3243 assert_eq!(node_txn[0].input.len(), 1);
3244 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3245 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3246 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3248 check_spends!(node_txn[0], tx);
3252 fn test_dup_events_on_peer_disconnect() {
3253 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3254 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3255 // as we used to generate the event immediately upon receipt of the payment preimage in the
3256 // update_fulfill_htlc message.
3258 let chanmon_cfgs = create_chanmon_cfgs(2);
3259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3261 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3262 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3264 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3266 assert!(nodes[1].node.claim_funds(payment_preimage));
3267 check_added_monitors!(nodes[1], 1);
3268 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3269 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3270 expect_payment_sent!(nodes[0], payment_preimage);
3272 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3273 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3275 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3276 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3280 fn test_simple_peer_disconnect() {
3281 // Test that we can reconnect when there are no lost messages
3282 let chanmon_cfgs = create_chanmon_cfgs(3);
3283 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3284 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3285 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3286 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3287 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3289 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3290 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3291 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3293 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3294 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3295 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3296 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3298 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3299 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3300 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3302 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3303 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3304 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3305 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3307 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3308 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3310 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3311 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3313 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3315 let events = nodes[0].node.get_and_clear_pending_events();
3316 assert_eq!(events.len(), 2);
3318 Event::PaymentSent { payment_preimage } => {
3319 assert_eq!(payment_preimage, payment_preimage_3);
3321 _ => panic!("Unexpected event"),
3324 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3325 assert_eq!(payment_hash, payment_hash_5);
3326 assert!(rejected_by_dest);
3328 _ => panic!("Unexpected event"),
3332 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3333 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3336 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3337 // Test that we can reconnect when in-flight HTLC updates get dropped
3338 let chanmon_cfgs = create_chanmon_cfgs(2);
3339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3343 let mut as_funding_locked = None;
3344 if messages_delivered == 0 {
3345 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3346 as_funding_locked = Some(funding_locked);
3347 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3348 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3349 // it before the channel_reestablish message.
3351 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3354 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3356 let logger = test_utils::TestLogger::new();
3357 let payment_event = {
3358 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3359 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3360 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3361 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3362 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3363 check_added_monitors!(nodes[0], 1);
3365 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3366 assert_eq!(events.len(), 1);
3367 SendEvent::from_event(events.remove(0))
3369 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3371 if messages_delivered < 2 {
3372 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3375 if messages_delivered >= 3 {
3376 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3377 check_added_monitors!(nodes[1], 1);
3378 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3380 if messages_delivered >= 4 {
3381 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3382 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3383 check_added_monitors!(nodes[0], 1);
3385 if messages_delivered >= 5 {
3386 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3387 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3388 // No commitment_signed so get_event_msg's assert(len == 1) passes
3389 check_added_monitors!(nodes[0], 1);
3391 if messages_delivered >= 6 {
3392 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3393 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3394 check_added_monitors!(nodes[1], 1);
3401 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3402 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3403 if messages_delivered < 3 {
3404 if simulate_broken_lnd {
3405 // lnd has a long-standing bug where they send a funding_locked prior to a
3406 // channel_reestablish if you reconnect prior to funding_locked time.
3408 // Here we simulate that behavior, delivering a funding_locked immediately on
3409 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3410 // in `reconnect_nodes` but we currently don't fail based on that.
3412 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3413 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3415 // Even if the funding_locked messages get exchanged, as long as nothing further was
3416 // received on either side, both sides will need to resend them.
3417 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3418 } else if messages_delivered == 3 {
3419 // nodes[0] still wants its RAA + commitment_signed
3420 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3421 } else if messages_delivered == 4 {
3422 // nodes[0] still wants its commitment_signed
3423 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3424 } else if messages_delivered == 5 {
3425 // nodes[1] still wants its final RAA
3426 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3427 } else if messages_delivered == 6 {
3428 // Everything was delivered...
3429 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3432 let events_1 = nodes[1].node.get_and_clear_pending_events();
3433 assert_eq!(events_1.len(), 1);
3435 Event::PendingHTLCsForwardable { .. } => { },
3436 _ => panic!("Unexpected event"),
3439 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3440 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3441 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3443 nodes[1].node.process_pending_htlc_forwards();
3445 let events_2 = nodes[1].node.get_and_clear_pending_events();
3446 assert_eq!(events_2.len(), 1);
3448 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3449 assert_eq!(payment_hash_1, *payment_hash);
3450 assert_eq!(amt, 1000000);
3452 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3453 assert!(payment_preimage.is_none());
3454 assert_eq!(payment_secret_1, *payment_secret);
3456 _ => panic!("expected PaymentPurpose::InvoicePayment")
3459 _ => panic!("Unexpected event"),
3462 nodes[1].node.claim_funds(payment_preimage_1);
3463 check_added_monitors!(nodes[1], 1);
3465 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3466 assert_eq!(events_3.len(), 1);
3467 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3468 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3469 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3470 assert!(updates.update_add_htlcs.is_empty());
3471 assert!(updates.update_fail_htlcs.is_empty());
3472 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3473 assert!(updates.update_fail_malformed_htlcs.is_empty());
3474 assert!(updates.update_fee.is_none());
3475 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3477 _ => panic!("Unexpected event"),
3480 if messages_delivered >= 1 {
3481 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3483 let events_4 = nodes[0].node.get_and_clear_pending_events();
3484 assert_eq!(events_4.len(), 1);
3486 Event::PaymentSent { ref payment_preimage } => {
3487 assert_eq!(payment_preimage_1, *payment_preimage);
3489 _ => panic!("Unexpected event"),
3492 if messages_delivered >= 2 {
3493 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3494 check_added_monitors!(nodes[0], 1);
3495 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3497 if messages_delivered >= 3 {
3498 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3499 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3500 check_added_monitors!(nodes[1], 1);
3502 if messages_delivered >= 4 {
3503 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3504 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3505 // No commitment_signed so get_event_msg's assert(len == 1) passes
3506 check_added_monitors!(nodes[1], 1);
3508 if messages_delivered >= 5 {
3509 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3510 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3511 check_added_monitors!(nodes[0], 1);
3518 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3519 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3520 if messages_delivered < 2 {
3521 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3522 if messages_delivered < 1 {
3523 let events_4 = nodes[0].node.get_and_clear_pending_events();
3524 assert_eq!(events_4.len(), 1);
3526 Event::PaymentSent { ref payment_preimage } => {
3527 assert_eq!(payment_preimage_1, *payment_preimage);
3529 _ => panic!("Unexpected event"),
3532 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3534 } else if messages_delivered == 2 {
3535 // nodes[0] still wants its RAA + commitment_signed
3536 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3537 } else if messages_delivered == 3 {
3538 // nodes[0] still wants its commitment_signed
3539 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3540 } else if messages_delivered == 4 {
3541 // nodes[1] still wants its final RAA
3542 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3543 } else if messages_delivered == 5 {
3544 // Everything was delivered...
3545 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3548 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3549 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3550 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3552 // Channel should still work fine...
3553 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3554 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3555 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3556 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3557 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3558 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3562 fn test_drop_messages_peer_disconnect_a() {
3563 do_test_drop_messages_peer_disconnect(0, true);
3564 do_test_drop_messages_peer_disconnect(0, false);
3565 do_test_drop_messages_peer_disconnect(1, false);
3566 do_test_drop_messages_peer_disconnect(2, false);
3570 fn test_drop_messages_peer_disconnect_b() {
3571 do_test_drop_messages_peer_disconnect(3, false);
3572 do_test_drop_messages_peer_disconnect(4, false);
3573 do_test_drop_messages_peer_disconnect(5, false);
3574 do_test_drop_messages_peer_disconnect(6, false);
3578 fn test_funding_peer_disconnect() {
3579 // Test that we can lock in our funding tx while disconnected
3580 let chanmon_cfgs = create_chanmon_cfgs(2);
3581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3583 let persister: test_utils::TestPersister;
3584 let new_chain_monitor: test_utils::TestChainMonitor;
3585 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3586 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3587 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592 confirm_transaction(&nodes[0], &tx);
3593 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3594 assert_eq!(events_1.len(), 1);
3596 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3597 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3599 _ => panic!("Unexpected event"),
3602 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3604 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3605 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3607 confirm_transaction(&nodes[1], &tx);
3608 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3609 assert_eq!(events_2.len(), 2);
3610 let funding_locked = match events_2[0] {
3611 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3612 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3615 _ => panic!("Unexpected event"),
3617 let bs_announcement_sigs = match events_2[1] {
3618 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3619 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3622 _ => panic!("Unexpected event"),
3625 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3627 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3628 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3629 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3630 assert_eq!(events_3.len(), 2);
3631 let as_announcement_sigs = match events_3[0] {
3632 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3633 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3636 _ => panic!("Unexpected event"),
3638 let (as_announcement, as_update) = match events_3[1] {
3639 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3640 (msg.clone(), update_msg.clone())
3642 _ => panic!("Unexpected event"),
3645 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3646 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3647 assert_eq!(events_4.len(), 1);
3648 let (_, bs_update) = match events_4[0] {
3649 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3650 (msg.clone(), update_msg.clone())
3652 _ => panic!("Unexpected event"),
3655 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3656 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3657 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3659 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3660 let logger = test_utils::TestLogger::new();
3661 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();
3662 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3663 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3665 // Check that after deserialization and reconnection we can still generate an identical
3666 // channel_announcement from the cached signatures.
3667 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3669 let nodes_0_serialized = nodes[0].node.encode();
3670 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3671 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3673 persister = test_utils::TestPersister::new();
3674 let keys_manager = &chanmon_cfgs[0].keys_manager;
3675 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);
3676 nodes[0].chain_monitor = &new_chain_monitor;
3677 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3678 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3679 &mut chan_0_monitor_read, keys_manager).unwrap();
3680 assert!(chan_0_monitor_read.is_empty());
3682 let mut nodes_0_read = &nodes_0_serialized[..];
3683 let (_, nodes_0_deserialized_tmp) = {
3684 let mut channel_monitors = HashMap::new();
3685 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3686 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3687 default_config: UserConfig::default(),
3689 fee_estimator: node_cfgs[0].fee_estimator,
3690 chain_monitor: nodes[0].chain_monitor,
3691 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3692 logger: nodes[0].logger,
3696 nodes_0_deserialized = nodes_0_deserialized_tmp;
3697 assert!(nodes_0_read.is_empty());
3699 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3700 nodes[0].node = &nodes_0_deserialized;
3701 check_added_monitors!(nodes[0], 1);
3703 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3705 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3706 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3707 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3708 let mut found_announcement = false;
3709 for event in msgs.iter() {
3711 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3712 if *msg == as_announcement { found_announcement = true; }
3714 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3715 _ => panic!("Unexpected event"),
3718 assert!(found_announcement);
3722 fn test_drop_messages_peer_disconnect_dual_htlc() {
3723 // Test that we can handle reconnecting when both sides of a channel have pending
3724 // commitment_updates when we disconnect.
3725 let chanmon_cfgs = create_chanmon_cfgs(2);
3726 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3727 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3728 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3729 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3730 let logger = test_utils::TestLogger::new();
3732 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3734 // Now try to send a second payment which will fail to send
3735 let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
3736 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3737 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();
3738 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3739 check_added_monitors!(nodes[0], 1);
3741 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3742 assert_eq!(events_1.len(), 1);
3744 MessageSendEvent::UpdateHTLCs { .. } => {},
3745 _ => panic!("Unexpected event"),
3748 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3749 check_added_monitors!(nodes[1], 1);
3751 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3752 assert_eq!(events_2.len(), 1);
3754 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 } } => {
3755 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3756 assert!(update_add_htlcs.is_empty());
3757 assert_eq!(update_fulfill_htlcs.len(), 1);
3758 assert!(update_fail_htlcs.is_empty());
3759 assert!(update_fail_malformed_htlcs.is_empty());
3760 assert!(update_fee.is_none());
3762 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3763 let events_3 = nodes[0].node.get_and_clear_pending_events();
3764 assert_eq!(events_3.len(), 1);
3766 Event::PaymentSent { ref payment_preimage } => {
3767 assert_eq!(*payment_preimage, payment_preimage_1);
3769 _ => panic!("Unexpected event"),
3772 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3773 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3774 // No commitment_signed so get_event_msg's assert(len == 1) passes
3775 check_added_monitors!(nodes[0], 1);
3777 _ => panic!("Unexpected event"),
3780 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3781 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3783 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3784 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3785 assert_eq!(reestablish_1.len(), 1);
3786 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3787 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3788 assert_eq!(reestablish_2.len(), 1);
3790 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3791 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3792 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3793 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3795 assert!(as_resp.0.is_none());
3796 assert!(bs_resp.0.is_none());
3798 assert!(bs_resp.1.is_none());
3799 assert!(bs_resp.2.is_none());
3801 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3803 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3804 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3805 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3806 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3807 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3808 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3809 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3810 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3811 // No commitment_signed so get_event_msg's assert(len == 1) passes
3812 check_added_monitors!(nodes[1], 1);
3814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3815 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3816 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3817 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3818 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3819 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3820 assert!(bs_second_commitment_signed.update_fee.is_none());
3821 check_added_monitors!(nodes[1], 1);
3823 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3824 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3825 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3826 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3827 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3828 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3829 assert!(as_commitment_signed.update_fee.is_none());
3830 check_added_monitors!(nodes[0], 1);
3832 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3833 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3834 // No commitment_signed so get_event_msg's assert(len == 1) passes
3835 check_added_monitors!(nodes[0], 1);
3837 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3838 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3839 // No commitment_signed so get_event_msg's assert(len == 1) passes
3840 check_added_monitors!(nodes[1], 1);
3842 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3843 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3844 check_added_monitors!(nodes[1], 1);
3846 expect_pending_htlcs_forwardable!(nodes[1]);
3848 let events_5 = nodes[1].node.get_and_clear_pending_events();
3849 assert_eq!(events_5.len(), 1);
3851 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3852 assert_eq!(payment_hash_2, *payment_hash);
3854 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3855 assert!(payment_preimage.is_none());
3856 assert_eq!(payment_secret_2, *payment_secret);
3858 _ => panic!("expected PaymentPurpose::InvoicePayment")
3861 _ => panic!("Unexpected event"),
3864 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3865 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3866 check_added_monitors!(nodes[0], 1);
3868 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3871 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3872 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3873 // to avoid our counterparty failing the channel.
3874 let chanmon_cfgs = create_chanmon_cfgs(2);
3875 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3876 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3877 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3879 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3880 let logger = test_utils::TestLogger::new();
3882 let our_payment_hash = if send_partial_mpp {
3883 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3884 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();
3885 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
3886 // Use the utility function send_payment_along_path to send the payment with MPP data which
3887 // indicates there are more HTLCs coming.
3888 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.
3889 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, &None).unwrap();
3890 check_added_monitors!(nodes[0], 1);
3891 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3892 assert_eq!(events.len(), 1);
3893 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3894 // hop should *not* yet generate any PaymentReceived event(s).
3895 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3898 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3901 let mut block = Block {
3902 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3905 connect_block(&nodes[0], &block);
3906 connect_block(&nodes[1], &block);
3907 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3908 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3909 block.header.prev_blockhash = block.block_hash();
3910 connect_block(&nodes[0], &block);
3911 connect_block(&nodes[1], &block);
3914 expect_pending_htlcs_forwardable!(nodes[1]);
3916 check_added_monitors!(nodes[1], 1);
3917 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3918 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3919 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3920 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3921 assert!(htlc_timeout_updates.update_fee.is_none());
3923 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3924 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3925 // 100_000 msat as u64, followed by the height at which we failed back above
3926 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3927 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3928 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3932 fn test_htlc_timeout() {
3933 do_test_htlc_timeout(true);
3934 do_test_htlc_timeout(false);
3937 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3938 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3939 let chanmon_cfgs = create_chanmon_cfgs(3);
3940 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3941 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3942 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3943 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3944 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3946 // Make sure all nodes are at the same starting height
3947 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3948 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3949 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3951 let logger = test_utils::TestLogger::new();
3953 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3954 let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3956 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3957 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();
3958 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3960 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3961 check_added_monitors!(nodes[1], 1);
3963 // Now attempt to route a second payment, which should be placed in the holding cell
3964 let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3966 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3967 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();
3968 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
3969 check_added_monitors!(nodes[0], 1);
3970 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3971 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3972 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3973 expect_pending_htlcs_forwardable!(nodes[1]);
3974 check_added_monitors!(nodes[1], 0);
3976 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3977 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();
3978 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3979 check_added_monitors!(nodes[1], 0);
3982 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3983 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3984 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3985 connect_blocks(&nodes[1], 1);
3988 expect_pending_htlcs_forwardable!(nodes[1]);
3989 check_added_monitors!(nodes[1], 1);
3990 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3991 assert_eq!(fail_commit.len(), 1);
3992 match fail_commit[0] {
3993 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3994 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3995 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3997 _ => unreachable!(),
3999 expect_payment_failed!(nodes[0], second_payment_hash, false);
4000 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, false);
4002 expect_payment_failed!(nodes[1], second_payment_hash, true);
4007 fn test_holding_cell_htlc_add_timeouts() {
4008 do_test_holding_cell_htlc_add_timeouts(false);
4009 do_test_holding_cell_htlc_add_timeouts(true);
4013 fn test_invalid_channel_announcement() {
4014 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4015 let secp_ctx = Secp256k1::new();
4016 let chanmon_cfgs = create_chanmon_cfgs(2);
4017 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4018 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4019 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4021 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4023 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4024 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4025 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4026 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4028 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 } );
4030 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4031 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4033 let as_network_key = nodes[0].node.get_our_node_id();
4034 let bs_network_key = nodes[1].node.get_our_node_id();
4036 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4038 let mut chan_announcement;
4040 macro_rules! dummy_unsigned_msg {
4042 msgs::UnsignedChannelAnnouncement {
4043 features: ChannelFeatures::known(),
4044 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4045 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4046 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4047 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4048 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4049 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4050 excess_data: Vec::new(),
4055 macro_rules! sign_msg {
4056 ($unsigned_msg: expr) => {
4057 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4058 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4059 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4060 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4061 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4062 chan_announcement = msgs::ChannelAnnouncement {
4063 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4064 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4065 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4066 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4067 contents: $unsigned_msg
4072 let unsigned_msg = dummy_unsigned_msg!();
4073 sign_msg!(unsigned_msg);
4074 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4075 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 } );
4077 // Configured with Network::Testnet
4078 let mut unsigned_msg = dummy_unsigned_msg!();
4079 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4080 sign_msg!(unsigned_msg);
4081 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4083 let mut unsigned_msg = dummy_unsigned_msg!();
4084 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4085 sign_msg!(unsigned_msg);
4086 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4090 fn test_no_txn_manager_serialize_deserialize() {
4091 let chanmon_cfgs = create_chanmon_cfgs(2);
4092 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4093 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4094 let logger: test_utils::TestLogger;
4095 let fee_estimator: test_utils::TestFeeEstimator;
4096 let persister: test_utils::TestPersister;
4097 let new_chain_monitor: test_utils::TestChainMonitor;
4098 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4099 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4101 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4103 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4105 let nodes_0_serialized = nodes[0].node.encode();
4106 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4107 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4109 logger = test_utils::TestLogger::new();
4110 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4111 persister = test_utils::TestPersister::new();
4112 let keys_manager = &chanmon_cfgs[0].keys_manager;
4113 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4114 nodes[0].chain_monitor = &new_chain_monitor;
4115 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4116 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4117 &mut chan_0_monitor_read, keys_manager).unwrap();
4118 assert!(chan_0_monitor_read.is_empty());
4120 let mut nodes_0_read = &nodes_0_serialized[..];
4121 let config = UserConfig::default();
4122 let (_, nodes_0_deserialized_tmp) = {
4123 let mut channel_monitors = HashMap::new();
4124 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4125 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4126 default_config: config,
4128 fee_estimator: &fee_estimator,
4129 chain_monitor: nodes[0].chain_monitor,
4130 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4135 nodes_0_deserialized = nodes_0_deserialized_tmp;
4136 assert!(nodes_0_read.is_empty());
4138 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4139 nodes[0].node = &nodes_0_deserialized;
4140 assert_eq!(nodes[0].node.list_channels().len(), 1);
4141 check_added_monitors!(nodes[0], 1);
4143 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4144 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4145 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4146 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4148 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4149 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4150 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4151 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4153 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4154 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4155 for node in nodes.iter() {
4156 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4157 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4158 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4161 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4165 fn test_dup_htlc_onchain_fails_on_reload() {
4166 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4167 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4168 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4169 // the ChannelMonitor tells it to.
4171 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4172 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4173 // PaymentFailed event appearing). However, because we may not serialize the relevant
4174 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4175 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4176 // and de-duplicates ChannelMonitor events.
4178 // This tests that explicit tracking behavior.
4179 let chanmon_cfgs = create_chanmon_cfgs(2);
4180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4182 let persister: test_utils::TestPersister;
4183 let new_chain_monitor: test_utils::TestChainMonitor;
4184 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4185 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4187 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4189 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4191 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4192 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4193 check_closed_broadcast!(nodes[0], true);
4194 check_added_monitors!(nodes[0], 1);
4196 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4197 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4199 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4200 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4201 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4202 assert_eq!(node_txn.len(), 3);
4203 assert_eq!(node_txn[0], node_txn[1]);
4205 assert!(nodes[1].node.claim_funds(payment_preimage));
4206 check_added_monitors!(nodes[1], 1);
4208 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4209 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4210 check_closed_broadcast!(nodes[1], true);
4211 check_added_monitors!(nodes[1], 1);
4212 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4214 header.prev_blockhash = nodes[0].best_block_hash();
4215 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4217 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4218 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4219 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4220 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4221 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4223 header.prev_blockhash = nodes[0].best_block_hash();
4224 let claim_block = Block { header, txdata: claim_txn};
4225 connect_block(&nodes[0], &claim_block);
4226 expect_payment_sent!(nodes[0], payment_preimage);
4228 // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4229 // connected a highly-relevant block, it likely gets serialized out now.
4230 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4231 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4233 // Now reload nodes[0]...
4234 persister = test_utils::TestPersister::new();
4235 let keys_manager = &chanmon_cfgs[0].keys_manager;
4236 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);
4237 nodes[0].chain_monitor = &new_chain_monitor;
4238 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4239 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4240 &mut chan_0_monitor_read, keys_manager).unwrap();
4241 assert!(chan_0_monitor_read.is_empty());
4243 let (_, nodes_0_deserialized_tmp) = {
4244 let mut channel_monitors = HashMap::new();
4245 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4246 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4247 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4248 default_config: Default::default(),
4250 fee_estimator: node_cfgs[0].fee_estimator,
4251 chain_monitor: nodes[0].chain_monitor,
4252 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4253 logger: nodes[0].logger,
4257 nodes_0_deserialized = nodes_0_deserialized_tmp;
4259 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4260 check_added_monitors!(nodes[0], 1);
4261 nodes[0].node = &nodes_0_deserialized;
4263 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4264 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4265 // payment events should kick in, leaving us with no pending events here.
4266 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4267 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4268 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4272 fn test_manager_serialize_deserialize_events() {
4273 // This test makes sure the events field in ChannelManager survives de/serialization
4274 let chanmon_cfgs = create_chanmon_cfgs(2);
4275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4277 let fee_estimator: test_utils::TestFeeEstimator;
4278 let persister: test_utils::TestPersister;
4279 let logger: test_utils::TestLogger;
4280 let new_chain_monitor: test_utils::TestChainMonitor;
4281 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4282 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4284 // Start creating a channel, but stop right before broadcasting the funding transaction
4285 let channel_value = 100000;
4286 let push_msat = 10001;
4287 let a_flags = InitFeatures::known();
4288 let b_flags = InitFeatures::known();
4289 let node_a = nodes.remove(0);
4290 let node_b = nodes.remove(0);
4291 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4292 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()));
4293 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()));
4295 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4297 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4298 check_added_monitors!(node_a, 0);
4300 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()));
4302 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4303 assert_eq!(added_monitors.len(), 1);
4304 assert_eq!(added_monitors[0].0, funding_output);
4305 added_monitors.clear();
4308 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()));
4310 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4311 assert_eq!(added_monitors.len(), 1);
4312 assert_eq!(added_monitors[0].0, funding_output);
4313 added_monitors.clear();
4315 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4320 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4321 let nodes_0_serialized = nodes[0].node.encode();
4322 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4323 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4325 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4326 logger = test_utils::TestLogger::new();
4327 persister = test_utils::TestPersister::new();
4328 let keys_manager = &chanmon_cfgs[0].keys_manager;
4329 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4330 nodes[0].chain_monitor = &new_chain_monitor;
4331 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4332 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4333 &mut chan_0_monitor_read, keys_manager).unwrap();
4334 assert!(chan_0_monitor_read.is_empty());
4336 let mut nodes_0_read = &nodes_0_serialized[..];
4337 let config = UserConfig::default();
4338 let (_, nodes_0_deserialized_tmp) = {
4339 let mut channel_monitors = HashMap::new();
4340 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4341 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4342 default_config: config,
4344 fee_estimator: &fee_estimator,
4345 chain_monitor: nodes[0].chain_monitor,
4346 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4351 nodes_0_deserialized = nodes_0_deserialized_tmp;
4352 assert!(nodes_0_read.is_empty());
4354 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4356 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4357 nodes[0].node = &nodes_0_deserialized;
4359 // After deserializing, make sure the funding_transaction is still held by the channel manager
4360 let events_4 = nodes[0].node.get_and_clear_pending_events();
4361 assert_eq!(events_4.len(), 0);
4362 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4363 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4365 // Make sure the channel is functioning as though the de/serialization never happened
4366 assert_eq!(nodes[0].node.list_channels().len(), 1);
4367 check_added_monitors!(nodes[0], 1);
4369 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4370 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4371 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4372 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4374 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4375 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4376 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4379 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4380 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4381 for node in nodes.iter() {
4382 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4383 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4384 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4387 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4391 fn test_simple_manager_serialize_deserialize() {
4392 let chanmon_cfgs = create_chanmon_cfgs(2);
4393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4395 let logger: test_utils::TestLogger;
4396 let fee_estimator: test_utils::TestFeeEstimator;
4397 let persister: test_utils::TestPersister;
4398 let new_chain_monitor: test_utils::TestChainMonitor;
4399 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4401 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4403 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4404 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4406 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4408 let nodes_0_serialized = nodes[0].node.encode();
4409 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4410 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4412 logger = test_utils::TestLogger::new();
4413 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4414 persister = test_utils::TestPersister::new();
4415 let keys_manager = &chanmon_cfgs[0].keys_manager;
4416 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4417 nodes[0].chain_monitor = &new_chain_monitor;
4418 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4419 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4420 &mut chan_0_monitor_read, keys_manager).unwrap();
4421 assert!(chan_0_monitor_read.is_empty());
4423 let mut nodes_0_read = &nodes_0_serialized[..];
4424 let (_, nodes_0_deserialized_tmp) = {
4425 let mut channel_monitors = HashMap::new();
4426 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4427 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4428 default_config: UserConfig::default(),
4430 fee_estimator: &fee_estimator,
4431 chain_monitor: nodes[0].chain_monitor,
4432 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4437 nodes_0_deserialized = nodes_0_deserialized_tmp;
4438 assert!(nodes_0_read.is_empty());
4440 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4441 nodes[0].node = &nodes_0_deserialized;
4442 check_added_monitors!(nodes[0], 1);
4444 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4446 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4447 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4451 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4452 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4453 let chanmon_cfgs = create_chanmon_cfgs(4);
4454 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4455 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4456 let logger: test_utils::TestLogger;
4457 let fee_estimator: test_utils::TestFeeEstimator;
4458 let persister: test_utils::TestPersister;
4459 let new_chain_monitor: test_utils::TestChainMonitor;
4460 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4461 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4462 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4463 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4464 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4466 let mut node_0_stale_monitors_serialized = Vec::new();
4467 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4468 let mut writer = test_utils::TestVecWriter(Vec::new());
4469 monitor.1.write(&mut writer).unwrap();
4470 node_0_stale_monitors_serialized.push(writer.0);
4473 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4475 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4476 let nodes_0_serialized = nodes[0].node.encode();
4478 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4479 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4480 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4481 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4483 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4485 let mut node_0_monitors_serialized = Vec::new();
4486 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4487 let mut writer = test_utils::TestVecWriter(Vec::new());
4488 monitor.1.write(&mut writer).unwrap();
4489 node_0_monitors_serialized.push(writer.0);
4492 logger = test_utils::TestLogger::new();
4493 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4494 persister = test_utils::TestPersister::new();
4495 let keys_manager = &chanmon_cfgs[0].keys_manager;
4496 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4497 nodes[0].chain_monitor = &new_chain_monitor;
4500 let mut node_0_stale_monitors = Vec::new();
4501 for serialized in node_0_stale_monitors_serialized.iter() {
4502 let mut read = &serialized[..];
4503 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4504 assert!(read.is_empty());
4505 node_0_stale_monitors.push(monitor);
4508 let mut node_0_monitors = Vec::new();
4509 for serialized in node_0_monitors_serialized.iter() {
4510 let mut read = &serialized[..];
4511 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4512 assert!(read.is_empty());
4513 node_0_monitors.push(monitor);
4516 let mut nodes_0_read = &nodes_0_serialized[..];
4517 if let Err(msgs::DecodeError::InvalidValue) =
4518 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4519 default_config: UserConfig::default(),
4521 fee_estimator: &fee_estimator,
4522 chain_monitor: nodes[0].chain_monitor,
4523 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4525 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4527 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4530 let mut nodes_0_read = &nodes_0_serialized[..];
4531 let (_, nodes_0_deserialized_tmp) =
4532 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4533 default_config: UserConfig::default(),
4535 fee_estimator: &fee_estimator,
4536 chain_monitor: nodes[0].chain_monitor,
4537 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4539 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4541 nodes_0_deserialized = nodes_0_deserialized_tmp;
4542 assert!(nodes_0_read.is_empty());
4544 { // Channel close should result in a commitment tx
4545 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4546 assert_eq!(txn.len(), 1);
4547 check_spends!(txn[0], funding_tx);
4548 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4551 for monitor in node_0_monitors.drain(..) {
4552 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4553 check_added_monitors!(nodes[0], 1);
4555 nodes[0].node = &nodes_0_deserialized;
4557 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4558 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4559 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4560 //... and we can even still claim the payment!
4561 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4563 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4564 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4565 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4566 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4567 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4568 assert_eq!(msg_events.len(), 1);
4569 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4571 &ErrorAction::SendErrorMessage { ref msg } => {
4572 assert_eq!(msg.channel_id, channel_id);
4574 _ => panic!("Unexpected event!"),
4579 macro_rules! check_spendable_outputs {
4580 ($node: expr, $keysinterface: expr) => {
4582 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4583 let mut txn = Vec::new();
4584 let mut all_outputs = Vec::new();
4585 let secp_ctx = Secp256k1::new();
4586 for event in events.drain(..) {
4588 Event::SpendableOutputs { mut outputs } => {
4589 for outp in outputs.drain(..) {
4590 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4591 all_outputs.push(outp);
4594 _ => panic!("Unexpected event"),
4597 if all_outputs.len() > 1 {
4598 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) {
4608 fn test_claim_sizeable_push_msat() {
4609 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4610 let chanmon_cfgs = create_chanmon_cfgs(2);
4611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4613 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4615 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4616 nodes[1].node.force_close_channel(&chan.2).unwrap();
4617 check_closed_broadcast!(nodes[1], true);
4618 check_added_monitors!(nodes[1], 1);
4619 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4620 assert_eq!(node_txn.len(), 1);
4621 check_spends!(node_txn[0], chan.3);
4622 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
4624 mine_transaction(&nodes[1], &node_txn[0]);
4625 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4627 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4628 assert_eq!(spend_txn.len(), 1);
4629 assert_eq!(spend_txn[0].input.len(), 1);
4630 check_spends!(spend_txn[0], node_txn[0]);
4631 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4635 fn test_claim_on_remote_sizeable_push_msat() {
4636 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4637 // to_remote output is encumbered by a P2WPKH
4638 let chanmon_cfgs = create_chanmon_cfgs(2);
4639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4643 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4644 nodes[0].node.force_close_channel(&chan.2).unwrap();
4645 check_closed_broadcast!(nodes[0], true);
4646 check_added_monitors!(nodes[0], 1);
4648 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4649 assert_eq!(node_txn.len(), 1);
4650 check_spends!(node_txn[0], chan.3);
4651 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
4653 mine_transaction(&nodes[1], &node_txn[0]);
4654 check_closed_broadcast!(nodes[1], true);
4655 check_added_monitors!(nodes[1], 1);
4656 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4658 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4659 assert_eq!(spend_txn.len(), 1);
4660 check_spends!(spend_txn[0], node_txn[0]);
4664 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4665 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4666 // to_remote output is encumbered by a P2WPKH
4668 let chanmon_cfgs = create_chanmon_cfgs(2);
4669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4671 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4673 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4674 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4675 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4676 assert_eq!(revoked_local_txn[0].input.len(), 1);
4677 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4679 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4680 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4681 check_closed_broadcast!(nodes[1], true);
4682 check_added_monitors!(nodes[1], 1);
4684 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4685 mine_transaction(&nodes[1], &node_txn[0]);
4686 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4688 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4689 assert_eq!(spend_txn.len(), 3);
4690 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4691 check_spends!(spend_txn[1], node_txn[0]);
4692 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4696 fn test_static_spendable_outputs_preimage_tx() {
4697 let chanmon_cfgs = create_chanmon_cfgs(2);
4698 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4699 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4700 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4702 // Create some initial channels
4703 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4705 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4707 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4708 assert_eq!(commitment_tx[0].input.len(), 1);
4709 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4711 // Settle A's commitment tx on B's chain
4712 assert!(nodes[1].node.claim_funds(payment_preimage));
4713 check_added_monitors!(nodes[1], 1);
4714 mine_transaction(&nodes[1], &commitment_tx[0]);
4715 check_added_monitors!(nodes[1], 1);
4716 let events = nodes[1].node.get_and_clear_pending_msg_events();
4718 MessageSendEvent::UpdateHTLCs { .. } => {},
4719 _ => panic!("Unexpected event"),
4722 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4723 _ => panic!("Unexepected event"),
4726 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4727 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4728 assert_eq!(node_txn.len(), 3);
4729 check_spends!(node_txn[0], commitment_tx[0]);
4730 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4731 check_spends!(node_txn[1], chan_1.3);
4732 check_spends!(node_txn[2], node_txn[1]);
4734 mine_transaction(&nodes[1], &node_txn[0]);
4735 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4737 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4738 assert_eq!(spend_txn.len(), 1);
4739 check_spends!(spend_txn[0], node_txn[0]);
4743 fn test_static_spendable_outputs_timeout_tx() {
4744 let chanmon_cfgs = create_chanmon_cfgs(2);
4745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4749 // Create some initial channels
4750 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4752 // Rebalance the network a bit by relaying one payment through all the channels ...
4753 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4755 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4757 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4758 assert_eq!(commitment_tx[0].input.len(), 1);
4759 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4761 // Settle A's commitment tx on B' chain
4762 mine_transaction(&nodes[1], &commitment_tx[0]);
4763 check_added_monitors!(nodes[1], 1);
4764 let events = nodes[1].node.get_and_clear_pending_msg_events();
4766 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4767 _ => panic!("Unexpected event"),
4769 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4771 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4772 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4773 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4774 check_spends!(node_txn[0], chan_1.3.clone());
4775 check_spends!(node_txn[1], commitment_tx[0].clone());
4776 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4778 mine_transaction(&nodes[1], &node_txn[1]);
4779 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4780 expect_payment_failed!(nodes[1], our_payment_hash, true);
4782 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4783 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4784 check_spends!(spend_txn[0], commitment_tx[0]);
4785 check_spends!(spend_txn[1], node_txn[1]);
4786 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4790 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4791 let chanmon_cfgs = create_chanmon_cfgs(2);
4792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4794 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4796 // Create some initial channels
4797 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4799 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4800 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4801 assert_eq!(revoked_local_txn[0].input.len(), 1);
4802 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4804 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4806 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4807 check_closed_broadcast!(nodes[1], true);
4808 check_added_monitors!(nodes[1], 1);
4810 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4811 assert_eq!(node_txn.len(), 2);
4812 assert_eq!(node_txn[0].input.len(), 2);
4813 check_spends!(node_txn[0], revoked_local_txn[0]);
4815 mine_transaction(&nodes[1], &node_txn[0]);
4816 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4818 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4819 assert_eq!(spend_txn.len(), 1);
4820 check_spends!(spend_txn[0], node_txn[0]);
4824 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4825 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4826 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4829 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4831 // Create some initial channels
4832 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4834 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4835 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4836 assert_eq!(revoked_local_txn[0].input.len(), 1);
4837 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4839 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4841 // A will generate HTLC-Timeout from revoked commitment tx
4842 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4843 check_closed_broadcast!(nodes[0], true);
4844 check_added_monitors!(nodes[0], 1);
4845 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4847 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4848 assert_eq!(revoked_htlc_txn.len(), 2);
4849 check_spends!(revoked_htlc_txn[0], chan_1.3);
4850 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4851 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4852 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4853 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4855 // B will generate justice tx from A's revoked commitment/HTLC tx
4856 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4857 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4858 check_closed_broadcast!(nodes[1], true);
4859 check_added_monitors!(nodes[1], 1);
4861 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4862 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4863 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4864 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4865 // transactions next...
4866 assert_eq!(node_txn[0].input.len(), 3);
4867 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4869 assert_eq!(node_txn[1].input.len(), 2);
4870 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4871 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4872 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4874 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4875 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4878 assert_eq!(node_txn[2].input.len(), 1);
4879 check_spends!(node_txn[2], chan_1.3);
4881 mine_transaction(&nodes[1], &node_txn[1]);
4882 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4884 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4885 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4886 assert_eq!(spend_txn.len(), 1);
4887 assert_eq!(spend_txn[0].input.len(), 1);
4888 check_spends!(spend_txn[0], node_txn[1]);
4892 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4893 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4894 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4899 // Create some initial channels
4900 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4902 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4903 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4904 assert_eq!(revoked_local_txn[0].input.len(), 1);
4905 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4907 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4908 assert_eq!(revoked_local_txn[0].output.len(), 2);
4910 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4912 // B will generate HTLC-Success from revoked commitment tx
4913 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4914 check_closed_broadcast!(nodes[1], true);
4915 check_added_monitors!(nodes[1], 1);
4916 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4918 assert_eq!(revoked_htlc_txn.len(), 2);
4919 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4920 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4921 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4923 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4924 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4925 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4927 // A will generate justice tx from B's revoked commitment/HTLC tx
4928 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4929 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4930 check_closed_broadcast!(nodes[0], true);
4931 check_added_monitors!(nodes[0], 1);
4933 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4934 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4936 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4937 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4938 // transactions next...
4939 assert_eq!(node_txn[0].input.len(), 2);
4940 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4941 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4942 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4944 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4945 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4948 assert_eq!(node_txn[1].input.len(), 1);
4949 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4951 check_spends!(node_txn[2], chan_1.3);
4953 mine_transaction(&nodes[0], &node_txn[1]);
4954 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4956 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4957 // didn't try to generate any new transactions.
4959 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4960 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4961 assert_eq!(spend_txn.len(), 3);
4962 assert_eq!(spend_txn[0].input.len(), 1);
4963 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4964 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4965 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4966 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4970 fn test_onchain_to_onchain_claim() {
4971 // Test that in case of channel closure, we detect the state of output and claim HTLC
4972 // on downstream peer's remote commitment tx.
4973 // First, have C claim an HTLC against its own latest commitment transaction.
4974 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4976 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4979 let chanmon_cfgs = create_chanmon_cfgs(3);
4980 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4981 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4982 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4984 // Create some initial channels
4985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4988 // Ensure all nodes are at the same height
4989 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4990 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4991 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4992 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4994 // Rebalance the network a bit by relaying one payment through all the channels ...
4995 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4996 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4998 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4999 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5000 check_spends!(commitment_tx[0], chan_2.3);
5001 nodes[2].node.claim_funds(payment_preimage);
5002 check_added_monitors!(nodes[2], 1);
5003 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5004 assert!(updates.update_add_htlcs.is_empty());
5005 assert!(updates.update_fail_htlcs.is_empty());
5006 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5007 assert!(updates.update_fail_malformed_htlcs.is_empty());
5009 mine_transaction(&nodes[2], &commitment_tx[0]);
5010 check_closed_broadcast!(nodes[2], true);
5011 check_added_monitors!(nodes[2], 1);
5013 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5014 assert_eq!(c_txn.len(), 3);
5015 assert_eq!(c_txn[0], c_txn[2]);
5016 assert_eq!(commitment_tx[0], c_txn[1]);
5017 check_spends!(c_txn[1], chan_2.3);
5018 check_spends!(c_txn[2], c_txn[1]);
5019 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5020 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5021 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5022 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5024 // 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
5025 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5026 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5027 check_added_monitors!(nodes[1], 1);
5028 expect_payment_forwarded!(nodes[1], Some(1000), true);
5030 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5031 // ChannelMonitor: claim tx
5032 assert_eq!(b_txn.len(), 1);
5033 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5036 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5037 assert_eq!(msg_events.len(), 3);
5038 check_added_monitors!(nodes[1], 1);
5039 match msg_events[0] {
5040 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5041 _ => panic!("Unexpected event"),
5043 match msg_events[1] {
5044 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5045 _ => panic!("Unexpected event"),
5047 match msg_events[2] {
5048 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, .. } } => {
5049 assert!(update_add_htlcs.is_empty());
5050 assert!(update_fail_htlcs.is_empty());
5051 assert_eq!(update_fulfill_htlcs.len(), 1);
5052 assert!(update_fail_malformed_htlcs.is_empty());
5053 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5055 _ => panic!("Unexpected event"),
5057 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5058 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5059 mine_transaction(&nodes[1], &commitment_tx[0]);
5060 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5061 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5062 assert_eq!(b_txn.len(), 3);
5063 check_spends!(b_txn[1], chan_1.3);
5064 check_spends!(b_txn[2], b_txn[1]);
5065 check_spends!(b_txn[0], commitment_tx[0]);
5066 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5067 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5068 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5070 check_closed_broadcast!(nodes[1], true);
5071 check_added_monitors!(nodes[1], 1);
5075 fn test_duplicate_payment_hash_one_failure_one_success() {
5076 // Topology : A --> B --> C --> D
5077 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5078 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5079 // we forward one of the payments onwards to D.
5080 let chanmon_cfgs = create_chanmon_cfgs(4);
5081 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5082 // When this test was written, the default base fee floated based on the HTLC count.
5083 // It is now fixed, so we simply set the fee to the expected value here.
5084 let mut config = test_default_channel_config();
5085 config.channel_options.forwarding_fee_base_msat = 196;
5086 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5087 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5088 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5090 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5091 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5092 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5094 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5095 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5096 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5097 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5098 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5100 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5102 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5103 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5104 // script push size limit so that the below script length checks match
5105 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5106 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
5107 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5108 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5110 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5111 assert_eq!(commitment_txn[0].input.len(), 1);
5112 check_spends!(commitment_txn[0], chan_2.3);
5114 mine_transaction(&nodes[1], &commitment_txn[0]);
5115 check_closed_broadcast!(nodes[1], true);
5116 check_added_monitors!(nodes[1], 1);
5117 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5119 let htlc_timeout_tx;
5120 { // Extract one of the two HTLC-Timeout transaction
5121 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5122 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5123 assert_eq!(node_txn.len(), 4);
5124 check_spends!(node_txn[0], chan_2.3);
5126 check_spends!(node_txn[1], commitment_txn[0]);
5127 assert_eq!(node_txn[1].input.len(), 1);
5128 check_spends!(node_txn[2], commitment_txn[0]);
5129 assert_eq!(node_txn[2].input.len(), 1);
5130 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5131 check_spends!(node_txn[3], commitment_txn[0]);
5132 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5134 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5135 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5136 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5137 htlc_timeout_tx = node_txn[1].clone();
5140 nodes[2].node.claim_funds(our_payment_preimage);
5141 mine_transaction(&nodes[2], &commitment_txn[0]);
5142 check_added_monitors!(nodes[2], 2);
5143 let events = nodes[2].node.get_and_clear_pending_msg_events();
5145 MessageSendEvent::UpdateHTLCs { .. } => {},
5146 _ => panic!("Unexpected event"),
5149 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5150 _ => panic!("Unexepected event"),
5152 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5153 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)
5154 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5155 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5156 assert_eq!(htlc_success_txn[0].input.len(), 1);
5157 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5158 assert_eq!(htlc_success_txn[1].input.len(), 1);
5159 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5160 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5161 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5162 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5163 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5164 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5166 mine_transaction(&nodes[1], &htlc_timeout_tx);
5167 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5168 expect_pending_htlcs_forwardable!(nodes[1]);
5169 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5170 assert!(htlc_updates.update_add_htlcs.is_empty());
5171 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5172 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5173 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5174 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5175 check_added_monitors!(nodes[1], 1);
5177 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5178 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5180 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5181 expect_payment_failure_chan_update!(nodes[0], chan_2.0.contents.short_channel_id, true);
5183 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5185 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5186 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5187 // and nodes[2] fee) is rounded down and then claimed in full.
5188 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5189 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5190 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5191 assert!(updates.update_add_htlcs.is_empty());
5192 assert!(updates.update_fail_htlcs.is_empty());
5193 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5194 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5195 assert!(updates.update_fail_malformed_htlcs.is_empty());
5196 check_added_monitors!(nodes[1], 1);
5198 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5199 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5201 let events = nodes[0].node.get_and_clear_pending_events();
5203 Event::PaymentSent { ref payment_preimage } => {
5204 assert_eq!(*payment_preimage, our_payment_preimage);
5206 _ => panic!("Unexpected event"),
5211 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5212 let chanmon_cfgs = create_chanmon_cfgs(2);
5213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5215 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5217 // Create some initial channels
5218 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5220 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5221 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5222 assert_eq!(local_txn.len(), 1);
5223 assert_eq!(local_txn[0].input.len(), 1);
5224 check_spends!(local_txn[0], chan_1.3);
5226 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5227 nodes[1].node.claim_funds(payment_preimage);
5228 check_added_monitors!(nodes[1], 1);
5229 mine_transaction(&nodes[1], &local_txn[0]);
5230 check_added_monitors!(nodes[1], 1);
5231 let events = nodes[1].node.get_and_clear_pending_msg_events();
5233 MessageSendEvent::UpdateHTLCs { .. } => {},
5234 _ => panic!("Unexpected event"),
5237 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5238 _ => panic!("Unexepected event"),
5241 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5242 assert_eq!(node_txn.len(), 3);
5243 assert_eq!(node_txn[0], node_txn[2]);
5244 assert_eq!(node_txn[1], local_txn[0]);
5245 assert_eq!(node_txn[0].input.len(), 1);
5246 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5247 check_spends!(node_txn[0], local_txn[0]);
5251 mine_transaction(&nodes[1], &node_tx);
5252 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5254 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5255 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5256 assert_eq!(spend_txn.len(), 1);
5257 assert_eq!(spend_txn[0].input.len(), 1);
5258 check_spends!(spend_txn[0], node_tx);
5259 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5262 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5263 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5264 // unrevoked commitment transaction.
5265 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5266 // a remote RAA before they could be failed backwards (and combinations thereof).
5267 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5268 // use the same payment hashes.
5269 // Thus, we use a six-node network:
5274 // And test where C fails back to A/B when D announces its latest commitment transaction
5275 let chanmon_cfgs = create_chanmon_cfgs(6);
5276 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5277 // When this test was written, the default base fee floated based on the HTLC count.
5278 // It is now fixed, so we simply set the fee to the expected value here.
5279 let mut config = test_default_channel_config();
5280 config.channel_options.forwarding_fee_base_msat = 196;
5281 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5282 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5283 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5284 let logger = test_utils::TestLogger::new();
5286 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5287 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5288 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5289 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5290 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5292 // Rebalance and check output sanity...
5293 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5294 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5295 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5297 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5299 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
5301 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
5302 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5303 let our_node_id = &nodes[1].node.get_our_node_id();
5304 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();
5306 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
5308 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
5310 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5312 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5313 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();
5315 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());
5317 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());
5320 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5322 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();
5323 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
5326 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
5328 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();
5329 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());
5331 // Double-check that six of the new HTLC were added
5332 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5333 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5334 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5335 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5337 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5338 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5339 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5340 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5341 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5342 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5343 check_added_monitors!(nodes[4], 0);
5344 expect_pending_htlcs_forwardable!(nodes[4]);
5345 check_added_monitors!(nodes[4], 1);
5347 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5348 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5349 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5350 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5351 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5352 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5354 // Fail 3rd below-dust and 7th above-dust HTLCs
5355 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5356 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5357 check_added_monitors!(nodes[5], 0);
5358 expect_pending_htlcs_forwardable!(nodes[5]);
5359 check_added_monitors!(nodes[5], 1);
5361 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5362 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5363 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5364 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5366 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5368 expect_pending_htlcs_forwardable!(nodes[3]);
5369 check_added_monitors!(nodes[3], 1);
5370 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5371 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5372 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5373 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5374 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5375 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5376 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5377 if deliver_last_raa {
5378 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5380 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5383 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5384 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5385 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5386 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5388 // We now broadcast the latest commitment transaction, which *should* result in failures for
5389 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5390 // the non-broadcast above-dust HTLCs.
5392 // Alternatively, we may broadcast the previous commitment transaction, which should only
5393 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5394 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5396 if announce_latest {
5397 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5399 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5401 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5402 check_closed_broadcast!(nodes[2], true);
5403 expect_pending_htlcs_forwardable!(nodes[2]);
5404 check_added_monitors!(nodes[2], 3);
5406 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5407 assert_eq!(cs_msgs.len(), 2);
5408 let mut a_done = false;
5409 for msg in cs_msgs {
5411 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5412 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5413 // should be failed-backwards here.
5414 let target = if *node_id == nodes[0].node.get_our_node_id() {
5415 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5416 for htlc in &updates.update_fail_htlcs {
5417 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 });
5419 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5424 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5425 for htlc in &updates.update_fail_htlcs {
5426 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5428 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5429 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5432 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5433 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5434 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5435 if announce_latest {
5436 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5437 if *node_id == nodes[0].node.get_our_node_id() {
5438 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5441 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5443 _ => panic!("Unexpected event"),
5447 let as_events = nodes[0].node.get_and_clear_pending_events();
5448 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5449 let mut as_failds = HashSet::new();
5450 for event in as_events.iter() {
5451 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5452 assert!(as_failds.insert(*payment_hash));
5453 if *payment_hash != payment_hash_2 {
5454 assert_eq!(*rejected_by_dest, deliver_last_raa);
5456 assert!(!rejected_by_dest);
5458 } else { panic!("Unexpected event"); }
5460 assert!(as_failds.contains(&payment_hash_1));
5461 assert!(as_failds.contains(&payment_hash_2));
5462 if announce_latest {
5463 assert!(as_failds.contains(&payment_hash_3));
5464 assert!(as_failds.contains(&payment_hash_5));
5466 assert!(as_failds.contains(&payment_hash_6));
5468 let bs_events = nodes[1].node.get_and_clear_pending_events();
5469 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5470 let mut bs_failds = HashSet::new();
5471 for event in bs_events.iter() {
5472 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5473 assert!(bs_failds.insert(*payment_hash));
5474 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5475 assert_eq!(*rejected_by_dest, deliver_last_raa);
5477 assert!(!rejected_by_dest);
5479 } else { panic!("Unexpected event"); }
5481 assert!(bs_failds.contains(&payment_hash_1));
5482 assert!(bs_failds.contains(&payment_hash_2));
5483 if announce_latest {
5484 assert!(bs_failds.contains(&payment_hash_4));
5486 assert!(bs_failds.contains(&payment_hash_5));
5488 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5489 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5490 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5491 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5492 // PaymentFailureNetworkUpdates.
5493 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5494 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5495 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5496 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5497 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5499 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5500 _ => panic!("Unexpected event"),
5506 fn test_fail_backwards_latest_remote_announce_a() {
5507 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5511 fn test_fail_backwards_latest_remote_announce_b() {
5512 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5516 fn test_fail_backwards_previous_remote_announce() {
5517 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5518 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5519 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5523 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5524 let chanmon_cfgs = create_chanmon_cfgs(2);
5525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5529 // Create some initial channels
5530 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5532 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5533 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5534 assert_eq!(local_txn[0].input.len(), 1);
5535 check_spends!(local_txn[0], chan_1.3);
5537 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5538 mine_transaction(&nodes[0], &local_txn[0]);
5539 check_closed_broadcast!(nodes[0], true);
5540 check_added_monitors!(nodes[0], 1);
5541 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5543 let htlc_timeout = {
5544 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5545 assert_eq!(node_txn.len(), 2);
5546 check_spends!(node_txn[0], chan_1.3);
5547 assert_eq!(node_txn[1].input.len(), 1);
5548 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5549 check_spends!(node_txn[1], local_txn[0]);
5553 mine_transaction(&nodes[0], &htlc_timeout);
5554 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5555 expect_payment_failed!(nodes[0], our_payment_hash, true);
5557 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5558 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5559 assert_eq!(spend_txn.len(), 3);
5560 check_spends!(spend_txn[0], local_txn[0]);
5561 assert_eq!(spend_txn[1].input.len(), 1);
5562 check_spends!(spend_txn[1], htlc_timeout);
5563 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5564 assert_eq!(spend_txn[2].input.len(), 2);
5565 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5566 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5567 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5571 fn test_key_derivation_params() {
5572 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5573 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5574 // let us re-derive the channel key set to then derive a delayed_payment_key.
5576 let chanmon_cfgs = create_chanmon_cfgs(3);
5578 // We manually create the node configuration to backup the seed.
5579 let seed = [42; 32];
5580 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5581 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);
5582 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() };
5583 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5584 node_cfgs.remove(0);
5585 node_cfgs.insert(0, node);
5587 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5588 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5590 // Create some initial channels
5591 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5593 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5594 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5595 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5597 // Ensure all nodes are at the same height
5598 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5599 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5600 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5601 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5603 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5604 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5605 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5606 assert_eq!(local_txn_1[0].input.len(), 1);
5607 check_spends!(local_txn_1[0], chan_1.3);
5609 // We check funding pubkey are unique
5610 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]));
5611 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]));
5612 if from_0_funding_key_0 == from_1_funding_key_0
5613 || from_0_funding_key_0 == from_1_funding_key_1
5614 || from_0_funding_key_1 == from_1_funding_key_0
5615 || from_0_funding_key_1 == from_1_funding_key_1 {
5616 panic!("Funding pubkeys aren't unique");
5619 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5620 mine_transaction(&nodes[0], &local_txn_1[0]);
5621 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5622 check_closed_broadcast!(nodes[0], true);
5623 check_added_monitors!(nodes[0], 1);
5625 let htlc_timeout = {
5626 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5627 assert_eq!(node_txn[1].input.len(), 1);
5628 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5629 check_spends!(node_txn[1], local_txn_1[0]);
5633 mine_transaction(&nodes[0], &htlc_timeout);
5634 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5635 expect_payment_failed!(nodes[0], our_payment_hash, true);
5637 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5638 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5639 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5640 assert_eq!(spend_txn.len(), 3);
5641 check_spends!(spend_txn[0], local_txn_1[0]);
5642 assert_eq!(spend_txn[1].input.len(), 1);
5643 check_spends!(spend_txn[1], htlc_timeout);
5644 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5645 assert_eq!(spend_txn[2].input.len(), 2);
5646 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5647 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5648 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5652 fn test_static_output_closing_tx() {
5653 let chanmon_cfgs = create_chanmon_cfgs(2);
5654 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5655 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5656 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5658 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5660 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5661 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5663 mine_transaction(&nodes[0], &closing_tx);
5664 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5666 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5667 assert_eq!(spend_txn.len(), 1);
5668 check_spends!(spend_txn[0], closing_tx);
5670 mine_transaction(&nodes[1], &closing_tx);
5671 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5673 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5674 assert_eq!(spend_txn.len(), 1);
5675 check_spends!(spend_txn[0], closing_tx);
5678 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5679 let chanmon_cfgs = create_chanmon_cfgs(2);
5680 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5681 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5682 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5683 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5685 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5687 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5688 // present in B's local commitment transaction, but none of A's commitment transactions.
5689 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5690 check_added_monitors!(nodes[1], 1);
5692 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5693 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5694 let events = nodes[0].node.get_and_clear_pending_events();
5695 assert_eq!(events.len(), 1);
5697 Event::PaymentSent { payment_preimage } => {
5698 assert_eq!(payment_preimage, our_payment_preimage);
5700 _ => panic!("Unexpected event"),
5703 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5704 check_added_monitors!(nodes[0], 1);
5705 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5706 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5707 check_added_monitors!(nodes[1], 1);
5709 let starting_block = nodes[1].best_block_info();
5710 let mut block = Block {
5711 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5714 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5715 connect_block(&nodes[1], &block);
5716 block.header.prev_blockhash = block.block_hash();
5718 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5719 check_closed_broadcast!(nodes[1], true);
5720 check_added_monitors!(nodes[1], 1);
5723 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5724 let chanmon_cfgs = create_chanmon_cfgs(2);
5725 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5726 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5727 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5728 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5729 let logger = test_utils::TestLogger::new();
5731 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
5732 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5733 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();
5734 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5735 check_added_monitors!(nodes[0], 1);
5737 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5739 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5740 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5741 // to "time out" the HTLC.
5743 let starting_block = nodes[1].best_block_info();
5744 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5746 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5747 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5748 header.prev_blockhash = header.block_hash();
5750 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5751 check_closed_broadcast!(nodes[0], true);
5752 check_added_monitors!(nodes[0], 1);
5755 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5756 let chanmon_cfgs = create_chanmon_cfgs(3);
5757 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5758 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5759 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5760 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5762 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5763 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5764 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5765 // actually revoked.
5766 let htlc_value = if use_dust { 50000 } else { 3000000 };
5767 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5768 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5769 expect_pending_htlcs_forwardable!(nodes[1]);
5770 check_added_monitors!(nodes[1], 1);
5772 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5773 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5774 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5775 check_added_monitors!(nodes[0], 1);
5776 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5777 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5778 check_added_monitors!(nodes[1], 1);
5779 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5780 check_added_monitors!(nodes[1], 1);
5781 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5783 if check_revoke_no_close {
5784 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5785 check_added_monitors!(nodes[0], 1);
5788 let starting_block = nodes[1].best_block_info();
5789 let mut block = Block {
5790 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5793 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5794 connect_block(&nodes[0], &block);
5795 block.header.prev_blockhash = block.block_hash();
5797 if !check_revoke_no_close {
5798 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5799 check_closed_broadcast!(nodes[0], true);
5800 check_added_monitors!(nodes[0], 1);
5802 expect_payment_failed!(nodes[0], our_payment_hash, true);
5806 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5807 // There are only a few cases to test here:
5808 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5809 // broadcastable commitment transactions result in channel closure,
5810 // * its included in an unrevoked-but-previous remote commitment transaction,
5811 // * its included in the latest remote or local commitment transactions.
5812 // We test each of the three possible commitment transactions individually and use both dust and
5814 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5815 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5816 // tested for at least one of the cases in other tests.
5818 fn htlc_claim_single_commitment_only_a() {
5819 do_htlc_claim_local_commitment_only(true);
5820 do_htlc_claim_local_commitment_only(false);
5822 do_htlc_claim_current_remote_commitment_only(true);
5823 do_htlc_claim_current_remote_commitment_only(false);
5827 fn htlc_claim_single_commitment_only_b() {
5828 do_htlc_claim_previous_remote_commitment_only(true, false);
5829 do_htlc_claim_previous_remote_commitment_only(false, false);
5830 do_htlc_claim_previous_remote_commitment_only(true, true);
5831 do_htlc_claim_previous_remote_commitment_only(false, true);
5836 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5837 let chanmon_cfgs = create_chanmon_cfgs(2);
5838 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5839 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5840 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5841 //Force duplicate channel ids
5842 for node in nodes.iter() {
5843 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5846 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5847 let channel_value_satoshis=10000;
5848 let push_msat=10001;
5849 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5850 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5851 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5853 //Create a second channel with a channel_id collision
5854 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5858 fn bolt2_open_channel_sending_node_checks_part2() {
5859 let chanmon_cfgs = create_chanmon_cfgs(2);
5860 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5861 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5862 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5864 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5865 let channel_value_satoshis=2^24;
5866 let push_msat=10001;
5867 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5869 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5870 let channel_value_satoshis=10000;
5871 // Test when push_msat is equal to 1000 * funding_satoshis.
5872 let push_msat=1000*channel_value_satoshis+1;
5873 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5875 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5876 let channel_value_satoshis=10000;
5877 let push_msat=10001;
5878 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
5879 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5880 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5882 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5883 // 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
5884 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5886 // 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.
5887 assert!(BREAKDOWN_TIMEOUT>0);
5888 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5890 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5891 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5892 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5894 // 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.
5895 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5896 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5897 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5898 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5899 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5903 fn bolt2_open_channel_sane_dust_limit() {
5904 let chanmon_cfgs = create_chanmon_cfgs(2);
5905 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5906 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5907 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5909 let channel_value_satoshis=1000000;
5910 let push_msat=10001;
5911 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5912 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5913 node0_to_1_send_open_channel.dust_limit_satoshis = 661;
5914 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5916 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5917 let events = nodes[1].node.get_and_clear_pending_msg_events();
5918 let err_msg = match events[0] {
5919 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5922 _ => panic!("Unexpected event"),
5924 assert_eq!(err_msg.data, "dust_limit_satoshis (661) is greater than the implementation limit (660)");
5927 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5928 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5929 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5930 // is no longer affordable once it's freed.
5932 fn test_fail_holding_cell_htlc_upon_free() {
5933 let chanmon_cfgs = create_chanmon_cfgs(2);
5934 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5935 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5936 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5937 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5938 let logger = test_utils::TestLogger::new();
5940 // First nodes[0] generates an update_fee, setting the channel's
5941 // pending_update_fee.
5943 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5944 *feerate_lock += 20;
5946 nodes[0].node.timer_tick_occurred();
5947 check_added_monitors!(nodes[0], 1);
5949 let events = nodes[0].node.get_and_clear_pending_msg_events();
5950 assert_eq!(events.len(), 1);
5951 let (update_msg, commitment_signed) = match events[0] {
5952 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5953 (update_fee.as_ref(), commitment_signed)
5955 _ => panic!("Unexpected event"),
5958 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5960 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5961 let channel_reserve = chan_stat.channel_reserve_msat;
5962 let feerate = get_feerate!(nodes[0], chan.2);
5964 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5965 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
5966 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5967 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5968 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();
5970 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5971 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5972 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5973 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5975 // Flush the pending fee update.
5976 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5977 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5978 check_added_monitors!(nodes[1], 1);
5979 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5980 check_added_monitors!(nodes[0], 1);
5982 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5983 // HTLC, but now that the fee has been raised the payment will now fail, causing
5984 // us to surface its failure to the user.
5985 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5986 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5987 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);
5988 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 {}",
5989 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5990 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5992 // Check that the payment failed to be sent out.
5993 let events = nodes[0].node.get_and_clear_pending_events();
5994 assert_eq!(events.len(), 1);
5996 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5997 assert_eq!(our_payment_hash.clone(), *payment_hash);
5998 assert_eq!(*rejected_by_dest, false);
5999 assert_eq!(*error_code, None);
6000 assert_eq!(*error_data, None);
6002 _ => panic!("Unexpected event"),
6006 // Test that if multiple HTLCs are released from the holding cell and one is
6007 // valid but the other is no longer valid upon release, the valid HTLC can be
6008 // successfully completed while the other one fails as expected.
6010 fn test_free_and_fail_holding_cell_htlcs() {
6011 let chanmon_cfgs = create_chanmon_cfgs(2);
6012 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6013 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6014 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6015 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6016 let logger = test_utils::TestLogger::new();
6018 // First nodes[0] generates an update_fee, setting the channel's
6019 // pending_update_fee.
6021 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6022 *feerate_lock += 200;
6024 nodes[0].node.timer_tick_occurred();
6025 check_added_monitors!(nodes[0], 1);
6027 let events = nodes[0].node.get_and_clear_pending_msg_events();
6028 assert_eq!(events.len(), 1);
6029 let (update_msg, commitment_signed) = match events[0] {
6030 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6031 (update_fee.as_ref(), commitment_signed)
6033 _ => panic!("Unexpected event"),
6036 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6038 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6039 let channel_reserve = chan_stat.channel_reserve_msat;
6040 let feerate = get_feerate!(nodes[0], chan.2);
6042 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6043 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6045 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6046 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6047 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6048 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();
6049 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();
6051 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6052 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6053 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6054 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6055 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6056 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6057 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6059 // Flush the pending fee update.
6060 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6061 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6062 check_added_monitors!(nodes[1], 1);
6063 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6064 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6065 check_added_monitors!(nodes[0], 2);
6067 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6068 // but now that the fee has been raised the second payment will now fail, causing us
6069 // to surface its failure to the user. The first payment should succeed.
6070 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6071 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6072 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);
6073 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 {}",
6074 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6075 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6077 // Check that the second payment failed to be sent out.
6078 let events = nodes[0].node.get_and_clear_pending_events();
6079 assert_eq!(events.len(), 1);
6081 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6082 assert_eq!(payment_hash_2.clone(), *payment_hash);
6083 assert_eq!(*rejected_by_dest, false);
6084 assert_eq!(*error_code, None);
6085 assert_eq!(*error_data, None);
6087 _ => panic!("Unexpected event"),
6090 // Complete the first payment and the RAA from the fee update.
6091 let (payment_event, send_raa_event) = {
6092 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6093 assert_eq!(msgs.len(), 2);
6094 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6096 let raa = match send_raa_event {
6097 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6098 _ => panic!("Unexpected event"),
6100 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6101 check_added_monitors!(nodes[1], 1);
6102 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6103 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6104 let events = nodes[1].node.get_and_clear_pending_events();
6105 assert_eq!(events.len(), 1);
6107 Event::PendingHTLCsForwardable { .. } => {},
6108 _ => panic!("Unexpected event"),
6110 nodes[1].node.process_pending_htlc_forwards();
6111 let events = nodes[1].node.get_and_clear_pending_events();
6112 assert_eq!(events.len(), 1);
6114 Event::PaymentReceived { .. } => {},
6115 _ => panic!("Unexpected event"),
6117 nodes[1].node.claim_funds(payment_preimage_1);
6118 check_added_monitors!(nodes[1], 1);
6119 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6120 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6121 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6122 let events = nodes[0].node.get_and_clear_pending_events();
6123 assert_eq!(events.len(), 1);
6125 Event::PaymentSent { ref payment_preimage } => {
6126 assert_eq!(*payment_preimage, payment_preimage_1);
6128 _ => panic!("Unexpected event"),
6132 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6133 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6134 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6137 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6138 let chanmon_cfgs = create_chanmon_cfgs(3);
6139 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6140 // When this test was written, the default base fee floated based on the HTLC count.
6141 // It is now fixed, so we simply set the fee to the expected value here.
6142 let mut config = test_default_channel_config();
6143 config.channel_options.forwarding_fee_base_msat = 196;
6144 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6145 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6146 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6147 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6148 let logger = test_utils::TestLogger::new();
6150 // First nodes[1] generates an update_fee, setting the channel's
6151 // pending_update_fee.
6153 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6154 *feerate_lock += 20;
6156 nodes[1].node.timer_tick_occurred();
6157 check_added_monitors!(nodes[1], 1);
6159 let events = nodes[1].node.get_and_clear_pending_msg_events();
6160 assert_eq!(events.len(), 1);
6161 let (update_msg, commitment_signed) = match events[0] {
6162 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6163 (update_fee.as_ref(), commitment_signed)
6165 _ => panic!("Unexpected event"),
6168 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6170 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6171 let channel_reserve = chan_stat.channel_reserve_msat;
6172 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6174 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6176 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6177 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6178 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6179 let payment_event = {
6180 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6181 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();
6182 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6183 check_added_monitors!(nodes[0], 1);
6185 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6186 assert_eq!(events.len(), 1);
6188 SendEvent::from_event(events.remove(0))
6190 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6191 check_added_monitors!(nodes[1], 0);
6192 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6193 expect_pending_htlcs_forwardable!(nodes[1]);
6195 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6196 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6198 // Flush the pending fee update.
6199 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6200 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6201 check_added_monitors!(nodes[2], 1);
6202 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6203 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6204 check_added_monitors!(nodes[1], 2);
6206 // A final RAA message is generated to finalize the fee update.
6207 let events = nodes[1].node.get_and_clear_pending_msg_events();
6208 assert_eq!(events.len(), 1);
6210 let raa_msg = match &events[0] {
6211 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6214 _ => panic!("Unexpected event"),
6217 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6218 check_added_monitors!(nodes[2], 1);
6219 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6221 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6222 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6223 assert_eq!(process_htlc_forwards_event.len(), 1);
6224 match &process_htlc_forwards_event[0] {
6225 &Event::PendingHTLCsForwardable { .. } => {},
6226 _ => panic!("Unexpected event"),
6229 // In response, we call ChannelManager's process_pending_htlc_forwards
6230 nodes[1].node.process_pending_htlc_forwards();
6231 check_added_monitors!(nodes[1], 1);
6233 // This causes the HTLC to be failed backwards.
6234 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6235 assert_eq!(fail_event.len(), 1);
6236 let (fail_msg, commitment_signed) = match &fail_event[0] {
6237 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6238 assert_eq!(updates.update_add_htlcs.len(), 0);
6239 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6240 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6241 assert_eq!(updates.update_fail_htlcs.len(), 1);
6242 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6244 _ => panic!("Unexpected event"),
6247 // Pass the failure messages back to nodes[0].
6248 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6249 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6251 // Complete the HTLC failure+removal process.
6252 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6253 check_added_monitors!(nodes[0], 1);
6254 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6255 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6256 check_added_monitors!(nodes[1], 2);
6257 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6258 assert_eq!(final_raa_event.len(), 1);
6259 let raa = match &final_raa_event[0] {
6260 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6261 _ => panic!("Unexpected event"),
6263 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6264 expect_payment_failure_chan_update!(nodes[0], chan_1_2.0.contents.short_channel_id, false);
6265 expect_payment_failed!(nodes[0], our_payment_hash, false);
6266 check_added_monitors!(nodes[0], 1);
6269 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6270 // 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.
6271 //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.
6274 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6275 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6276 let chanmon_cfgs = create_chanmon_cfgs(2);
6277 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6282 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6283 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6284 let logger = test_utils::TestLogger::new();
6285 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();
6286 route.paths[0][0].fee_msat = 100;
6288 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6289 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6290 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6291 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6295 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6296 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6297 let chanmon_cfgs = create_chanmon_cfgs(2);
6298 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6299 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6300 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6301 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6302 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6304 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6305 let logger = test_utils::TestLogger::new();
6306 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();
6307 route.paths[0][0].fee_msat = 0;
6308 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6309 assert_eq!(err, "Cannot send 0-msat HTLC"));
6311 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6312 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6316 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6317 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6318 let chanmon_cfgs = create_chanmon_cfgs(2);
6319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6322 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6324 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6325 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6326 let logger = test_utils::TestLogger::new();
6327 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();
6328 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6329 check_added_monitors!(nodes[0], 1);
6330 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6331 updates.update_add_htlcs[0].amount_msat = 0;
6333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6334 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6335 check_closed_broadcast!(nodes[1], true).unwrap();
6336 check_added_monitors!(nodes[1], 1);
6340 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6341 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6342 //It is enforced when constructing a route.
6343 let chanmon_cfgs = create_chanmon_cfgs(2);
6344 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6345 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6346 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6347 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6348 let logger = test_utils::TestLogger::new();
6350 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6352 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6353 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();
6354 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6355 assert_eq!(err, &"Channel CLTV overflowed?"));
6359 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6360 //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.
6361 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6362 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6363 let chanmon_cfgs = create_chanmon_cfgs(2);
6364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6368 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6370 let logger = test_utils::TestLogger::new();
6371 for i in 0..max_accepted_htlcs {
6372 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6373 let payment_event = {
6374 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6375 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();
6376 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6377 check_added_monitors!(nodes[0], 1);
6379 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6380 assert_eq!(events.len(), 1);
6381 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6382 assert_eq!(htlcs[0].htlc_id, i);
6386 SendEvent::from_event(events.remove(0))
6388 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6389 check_added_monitors!(nodes[1], 0);
6390 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6392 expect_pending_htlcs_forwardable!(nodes[1]);
6393 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6395 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6396 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6397 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();
6398 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6399 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6401 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6402 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6406 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6407 //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.
6408 let chanmon_cfgs = create_chanmon_cfgs(2);
6409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6411 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6412 let channel_value = 100000;
6413 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6414 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6416 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6418 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6419 // Manually create a route over our max in flight (which our router normally automatically
6421 let route = Route { paths: vec![vec![RouteHop {
6422 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6423 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6424 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6426 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6427 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)));
6429 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6430 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);
6432 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6435 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6437 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6438 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6439 let chanmon_cfgs = create_chanmon_cfgs(2);
6440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6442 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6443 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6444 let htlc_minimum_msat: u64;
6446 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6447 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6448 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6451 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6452 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6453 let logger = test_utils::TestLogger::new();
6454 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();
6455 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6456 check_added_monitors!(nodes[0], 1);
6457 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6458 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6459 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6460 assert!(nodes[1].node.list_channels().is_empty());
6461 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6462 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()));
6463 check_added_monitors!(nodes[1], 1);
6467 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6468 //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
6469 let chanmon_cfgs = create_chanmon_cfgs(2);
6470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6473 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6474 let logger = test_utils::TestLogger::new();
6476 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6477 let channel_reserve = chan_stat.channel_reserve_msat;
6478 let feerate = get_feerate!(nodes[0], chan.2);
6479 // The 2* and +1 are for the fee spike reserve.
6480 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6482 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6483 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6484 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6485 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();
6486 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6487 check_added_monitors!(nodes[0], 1);
6488 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6490 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6491 // at this time channel-initiatee receivers are not required to enforce that senders
6492 // respect the fee_spike_reserve.
6493 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6494 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6496 assert!(nodes[1].node.list_channels().is_empty());
6497 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6498 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6499 check_added_monitors!(nodes[1], 1);
6503 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6504 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6505 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6506 let chanmon_cfgs = create_chanmon_cfgs(2);
6507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6509 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6510 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6511 let logger = test_utils::TestLogger::new();
6513 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6514 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6516 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6517 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();
6519 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6520 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6521 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6522 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6524 let mut msg = msgs::UpdateAddHTLC {
6528 payment_hash: our_payment_hash,
6529 cltv_expiry: htlc_cltv,
6530 onion_routing_packet: onion_packet.clone(),
6533 for i in 0..super::channel::OUR_MAX_HTLCS {
6534 msg.htlc_id = i as u64;
6535 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6537 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6538 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6540 assert!(nodes[1].node.list_channels().is_empty());
6541 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6542 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6543 check_added_monitors!(nodes[1], 1);
6547 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6548 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6549 let chanmon_cfgs = create_chanmon_cfgs(2);
6550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6552 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6554 let logger = test_utils::TestLogger::new();
6556 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6557 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6558 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();
6559 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6560 check_added_monitors!(nodes[0], 1);
6561 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6563 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6565 assert!(nodes[1].node.list_channels().is_empty());
6566 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6567 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6568 check_added_monitors!(nodes[1], 1);
6572 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6573 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6574 let chanmon_cfgs = create_chanmon_cfgs(2);
6575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6577 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6578 let logger = test_utils::TestLogger::new();
6580 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6581 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6582 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6583 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();
6584 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6585 check_added_monitors!(nodes[0], 1);
6586 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6587 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6588 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6590 assert!(nodes[1].node.list_channels().is_empty());
6591 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6592 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6593 check_added_monitors!(nodes[1], 1);
6597 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6598 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6599 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6600 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6601 let chanmon_cfgs = create_chanmon_cfgs(2);
6602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6604 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6605 let logger = test_utils::TestLogger::new();
6607 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6608 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6609 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6610 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();
6611 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6612 check_added_monitors!(nodes[0], 1);
6613 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6614 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6616 //Disconnect and Reconnect
6617 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6618 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6619 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6620 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6621 assert_eq!(reestablish_1.len(), 1);
6622 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6623 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6624 assert_eq!(reestablish_2.len(), 1);
6625 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6626 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6627 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6628 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6632 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6633 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6634 check_added_monitors!(nodes[1], 1);
6635 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6639 assert!(nodes[1].node.list_channels().is_empty());
6640 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6641 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6642 check_added_monitors!(nodes[1], 1);
6646 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6647 //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.
6649 let chanmon_cfgs = create_chanmon_cfgs(2);
6650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6652 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6653 let logger = test_utils::TestLogger::new();
6654 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6655 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6656 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6657 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();
6658 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6660 check_added_monitors!(nodes[0], 1);
6661 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6662 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6664 let update_msg = msgs::UpdateFulfillHTLC{
6667 payment_preimage: our_payment_preimage,
6670 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6672 assert!(nodes[0].node.list_channels().is_empty());
6673 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6674 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()));
6675 check_added_monitors!(nodes[0], 1);
6679 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6680 //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.
6682 let chanmon_cfgs = create_chanmon_cfgs(2);
6683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6685 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6686 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6687 let logger = test_utils::TestLogger::new();
6689 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6690 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6691 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();
6692 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6693 check_added_monitors!(nodes[0], 1);
6694 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6695 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6697 let update_msg = msgs::UpdateFailHTLC{
6700 reason: msgs::OnionErrorPacket { data: Vec::new()},
6703 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6705 assert!(nodes[0].node.list_channels().is_empty());
6706 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6707 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()));
6708 check_added_monitors!(nodes[0], 1);
6712 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6713 //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.
6715 let chanmon_cfgs = create_chanmon_cfgs(2);
6716 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6717 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6718 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6719 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6720 let logger = test_utils::TestLogger::new();
6722 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6723 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6724 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();
6725 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6726 check_added_monitors!(nodes[0], 1);
6727 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6728 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6729 let update_msg = msgs::UpdateFailMalformedHTLC{
6732 sha256_of_onion: [1; 32],
6733 failure_code: 0x8000,
6736 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6738 assert!(nodes[0].node.list_channels().is_empty());
6739 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6740 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()));
6741 check_added_monitors!(nodes[0], 1);
6745 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6746 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6748 let chanmon_cfgs = create_chanmon_cfgs(2);
6749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6751 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6752 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6754 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6756 nodes[1].node.claim_funds(our_payment_preimage);
6757 check_added_monitors!(nodes[1], 1);
6759 let events = nodes[1].node.get_and_clear_pending_msg_events();
6760 assert_eq!(events.len(), 1);
6761 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6763 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, .. } } => {
6764 assert!(update_add_htlcs.is_empty());
6765 assert_eq!(update_fulfill_htlcs.len(), 1);
6766 assert!(update_fail_htlcs.is_empty());
6767 assert!(update_fail_malformed_htlcs.is_empty());
6768 assert!(update_fee.is_none());
6769 update_fulfill_htlcs[0].clone()
6771 _ => panic!("Unexpected event"),
6775 update_fulfill_msg.htlc_id = 1;
6777 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6779 assert!(nodes[0].node.list_channels().is_empty());
6780 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6781 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6782 check_added_monitors!(nodes[0], 1);
6786 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6787 //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.
6789 let chanmon_cfgs = create_chanmon_cfgs(2);
6790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6792 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6793 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6795 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6797 nodes[1].node.claim_funds(our_payment_preimage);
6798 check_added_monitors!(nodes[1], 1);
6800 let events = nodes[1].node.get_and_clear_pending_msg_events();
6801 assert_eq!(events.len(), 1);
6802 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6804 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, .. } } => {
6805 assert!(update_add_htlcs.is_empty());
6806 assert_eq!(update_fulfill_htlcs.len(), 1);
6807 assert!(update_fail_htlcs.is_empty());
6808 assert!(update_fail_malformed_htlcs.is_empty());
6809 assert!(update_fee.is_none());
6810 update_fulfill_htlcs[0].clone()
6812 _ => panic!("Unexpected event"),
6816 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6818 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6820 assert!(nodes[0].node.list_channels().is_empty());
6821 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6822 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6823 check_added_monitors!(nodes[0], 1);
6827 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6828 //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.
6830 let chanmon_cfgs = create_chanmon_cfgs(2);
6831 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6833 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6834 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6835 let logger = test_utils::TestLogger::new();
6837 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6838 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6839 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();
6840 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6841 check_added_monitors!(nodes[0], 1);
6843 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6844 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6846 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6847 check_added_monitors!(nodes[1], 0);
6848 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6850 let events = nodes[1].node.get_and_clear_pending_msg_events();
6852 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6854 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, .. } } => {
6855 assert!(update_add_htlcs.is_empty());
6856 assert!(update_fulfill_htlcs.is_empty());
6857 assert!(update_fail_htlcs.is_empty());
6858 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6859 assert!(update_fee.is_none());
6860 update_fail_malformed_htlcs[0].clone()
6862 _ => panic!("Unexpected event"),
6865 update_msg.failure_code &= !0x8000;
6866 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6868 assert!(nodes[0].node.list_channels().is_empty());
6869 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6870 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6871 check_added_monitors!(nodes[0], 1);
6875 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6876 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6877 // * 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.
6879 let chanmon_cfgs = create_chanmon_cfgs(3);
6880 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6881 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6882 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6883 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6884 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6885 let logger = test_utils::TestLogger::new();
6887 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6890 let mut payment_event = {
6891 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6892 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();
6893 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6894 check_added_monitors!(nodes[0], 1);
6895 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6896 assert_eq!(events.len(), 1);
6897 SendEvent::from_event(events.remove(0))
6899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6900 check_added_monitors!(nodes[1], 0);
6901 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6902 expect_pending_htlcs_forwardable!(nodes[1]);
6903 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6904 assert_eq!(events_2.len(), 1);
6905 check_added_monitors!(nodes[1], 1);
6906 payment_event = SendEvent::from_event(events_2.remove(0));
6907 assert_eq!(payment_event.msgs.len(), 1);
6910 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6911 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6912 check_added_monitors!(nodes[2], 0);
6913 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6915 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6916 assert_eq!(events_3.len(), 1);
6917 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6919 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 } } => {
6920 assert!(update_add_htlcs.is_empty());
6921 assert!(update_fulfill_htlcs.is_empty());
6922 assert!(update_fail_htlcs.is_empty());
6923 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6924 assert!(update_fee.is_none());
6925 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6927 _ => panic!("Unexpected event"),
6931 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6933 check_added_monitors!(nodes[1], 0);
6934 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6935 expect_pending_htlcs_forwardable!(nodes[1]);
6936 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6937 assert_eq!(events_4.len(), 1);
6939 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6941 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, .. } } => {
6942 assert!(update_add_htlcs.is_empty());
6943 assert!(update_fulfill_htlcs.is_empty());
6944 assert_eq!(update_fail_htlcs.len(), 1);
6945 assert!(update_fail_malformed_htlcs.is_empty());
6946 assert!(update_fee.is_none());
6948 _ => panic!("Unexpected event"),
6951 check_added_monitors!(nodes[1], 1);
6954 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6955 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6956 // 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
6957 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6959 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6960 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6961 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6962 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6963 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6964 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6966 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6968 // We route 2 dust-HTLCs between A and B
6969 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6970 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6971 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6973 // Cache one local commitment tx as previous
6974 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6976 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6977 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6978 check_added_monitors!(nodes[1], 0);
6979 expect_pending_htlcs_forwardable!(nodes[1]);
6980 check_added_monitors!(nodes[1], 1);
6982 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6983 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6984 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6985 check_added_monitors!(nodes[0], 1);
6987 // Cache one local commitment tx as lastest
6988 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6990 let events = nodes[0].node.get_and_clear_pending_msg_events();
6992 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6993 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6995 _ => panic!("Unexpected event"),
6998 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6999 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7001 _ => panic!("Unexpected event"),
7004 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7005 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7006 if announce_latest {
7007 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7009 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7012 check_closed_broadcast!(nodes[0], true);
7013 check_added_monitors!(nodes[0], 1);
7015 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7016 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7017 let events = nodes[0].node.get_and_clear_pending_events();
7018 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7019 assert_eq!(events.len(), 2);
7020 let mut first_failed = false;
7021 for event in events {
7023 Event::PaymentFailed { payment_hash, .. } => {
7024 if payment_hash == payment_hash_1 {
7025 assert!(!first_failed);
7026 first_failed = true;
7028 assert_eq!(payment_hash, payment_hash_2);
7031 _ => panic!("Unexpected event"),
7037 fn test_failure_delay_dust_htlc_local_commitment() {
7038 do_test_failure_delay_dust_htlc_local_commitment(true);
7039 do_test_failure_delay_dust_htlc_local_commitment(false);
7042 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7043 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7044 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7045 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7046 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7047 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7048 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7050 let chanmon_cfgs = create_chanmon_cfgs(3);
7051 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7052 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7053 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7054 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7056 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7058 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7059 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7061 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7062 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7064 // We revoked bs_commitment_tx
7066 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7067 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7070 let mut timeout_tx = Vec::new();
7072 // We fail dust-HTLC 1 by broadcast of local commitment tx
7073 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7074 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7075 expect_payment_failed!(nodes[0], dust_hash, true);
7077 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7078 check_closed_broadcast!(nodes[0], true);
7079 check_added_monitors!(nodes[0], 1);
7080 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7081 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7082 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7083 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7084 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7085 mine_transaction(&nodes[0], &timeout_tx[0]);
7086 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7087 expect_payment_failed!(nodes[0], non_dust_hash, true);
7089 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7090 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7091 check_closed_broadcast!(nodes[0], true);
7092 check_added_monitors!(nodes[0], 1);
7093 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7094 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7095 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7097 expect_payment_failed!(nodes[0], dust_hash, true);
7098 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7099 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7100 mine_transaction(&nodes[0], &timeout_tx[0]);
7101 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7102 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7103 expect_payment_failed!(nodes[0], non_dust_hash, true);
7105 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7107 let events = nodes[0].node.get_and_clear_pending_events();
7108 assert_eq!(events.len(), 2);
7111 Event::PaymentFailed { payment_hash, .. } => {
7112 if payment_hash == dust_hash { first = true; }
7113 else { first = false; }
7115 _ => panic!("Unexpected event"),
7118 Event::PaymentFailed { payment_hash, .. } => {
7119 if first { assert_eq!(payment_hash, non_dust_hash); }
7120 else { assert_eq!(payment_hash, dust_hash); }
7122 _ => panic!("Unexpected event"),
7129 fn test_sweep_outbound_htlc_failure_update() {
7130 do_test_sweep_outbound_htlc_failure_update(false, true);
7131 do_test_sweep_outbound_htlc_failure_update(false, false);
7132 do_test_sweep_outbound_htlc_failure_update(true, false);
7136 fn test_user_configurable_csv_delay() {
7137 // We test our channel constructors yield errors when we pass them absurd csv delay
7139 let mut low_our_to_self_config = UserConfig::default();
7140 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7141 let mut high_their_to_self_config = UserConfig::default();
7142 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7143 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7144 let chanmon_cfgs = create_chanmon_cfgs(2);
7145 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7146 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7147 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7149 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7150 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) {
7152 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())); },
7153 _ => panic!("Unexpected event"),
7155 } else { assert!(false) }
7157 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7158 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7159 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7160 open_channel.to_self_delay = 200;
7161 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) {
7163 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())); },
7164 _ => panic!("Unexpected event"),
7166 } else { assert!(false); }
7168 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7169 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7170 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()));
7171 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7172 accept_channel.to_self_delay = 200;
7173 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7174 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7176 &ErrorAction::SendErrorMessage { ref msg } => {
7177 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()));
7179 _ => { assert!(false); }
7181 } else { assert!(false); }
7183 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7184 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7185 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7186 open_channel.to_self_delay = 200;
7187 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) {
7189 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())); },
7190 _ => panic!("Unexpected event"),
7192 } else { assert!(false); }
7196 fn test_data_loss_protect() {
7197 // We want to be sure that :
7198 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7199 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7200 // * we close channel in case of detecting other being fallen behind
7201 // * we are able to claim our own outputs thanks to to_remote being static
7202 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7208 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7209 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7210 // during signing due to revoked tx
7211 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7212 let keys_manager = &chanmon_cfgs[0].keys_manager;
7215 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7216 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7217 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7219 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7221 // Cache node A state before any channel update
7222 let previous_node_state = nodes[0].node.encode();
7223 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7224 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7226 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7227 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7229 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7230 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7232 // Restore node A from previous state
7233 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7234 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7235 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7236 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7237 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7238 persister = test_utils::TestPersister::new();
7239 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7241 let mut channel_monitors = HashMap::new();
7242 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7243 <(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 {
7244 keys_manager: keys_manager,
7245 fee_estimator: &fee_estimator,
7246 chain_monitor: &monitor,
7248 tx_broadcaster: &tx_broadcaster,
7249 default_config: UserConfig::default(),
7253 nodes[0].node = &node_state_0;
7254 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7255 nodes[0].chain_monitor = &monitor;
7256 nodes[0].chain_source = &chain_source;
7258 check_added_monitors!(nodes[0], 1);
7260 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7261 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7263 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7265 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7266 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7267 check_added_monitors!(nodes[0], 1);
7270 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7271 assert_eq!(node_txn.len(), 0);
7274 let mut reestablish_1 = Vec::with_capacity(1);
7275 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7276 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7277 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7278 reestablish_1.push(msg.clone());
7279 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7280 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7282 &ErrorAction::SendErrorMessage { ref msg } => {
7283 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");
7285 _ => panic!("Unexpected event!"),
7288 panic!("Unexpected event")
7292 // Check we close channel detecting A is fallen-behind
7293 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7294 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7295 check_added_monitors!(nodes[1], 1);
7298 // Check A is able to claim to_remote output
7299 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7300 assert_eq!(node_txn.len(), 1);
7301 check_spends!(node_txn[0], chan.3);
7302 assert_eq!(node_txn[0].output.len(), 2);
7303 mine_transaction(&nodes[0], &node_txn[0]);
7304 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7305 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7306 assert_eq!(spend_txn.len(), 1);
7307 check_spends!(spend_txn[0], node_txn[0]);
7311 fn test_check_htlc_underpaying() {
7312 // Send payment through A -> B but A is maliciously
7313 // sending a probe payment (i.e less than expected value0
7314 // to B, B should refuse payment.
7316 let chanmon_cfgs = create_chanmon_cfgs(2);
7317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7319 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7321 // Create some initial channels
7322 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7324 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();
7325 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7326 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7327 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7328 check_added_monitors!(nodes[0], 1);
7330 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7331 assert_eq!(events.len(), 1);
7332 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7334 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7336 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7337 // and then will wait a second random delay before failing the HTLC back:
7338 expect_pending_htlcs_forwardable!(nodes[1]);
7339 expect_pending_htlcs_forwardable!(nodes[1]);
7341 // Node 3 is expecting payment of 100_000 but received 10_000,
7342 // it should fail htlc like we didn't know the preimage.
7343 nodes[1].node.process_pending_htlc_forwards();
7345 let events = nodes[1].node.get_and_clear_pending_msg_events();
7346 assert_eq!(events.len(), 1);
7347 let (update_fail_htlc, commitment_signed) = match events[0] {
7348 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 } } => {
7349 assert!(update_add_htlcs.is_empty());
7350 assert!(update_fulfill_htlcs.is_empty());
7351 assert_eq!(update_fail_htlcs.len(), 1);
7352 assert!(update_fail_malformed_htlcs.is_empty());
7353 assert!(update_fee.is_none());
7354 (update_fail_htlcs[0].clone(), commitment_signed)
7356 _ => panic!("Unexpected event"),
7358 check_added_monitors!(nodes[1], 1);
7360 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7361 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7363 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7364 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7365 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7366 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7370 fn test_announce_disable_channels() {
7371 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7372 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7374 let chanmon_cfgs = create_chanmon_cfgs(2);
7375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7379 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7380 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7381 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7384 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7385 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7387 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7388 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7389 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7390 assert_eq!(msg_events.len(), 3);
7391 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7392 for e in msg_events {
7394 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7395 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7396 // Check that each channel gets updated exactly once
7397 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7398 panic!("Generated ChannelUpdate for wrong chan!");
7401 _ => panic!("Unexpected event"),
7405 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7406 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7407 assert_eq!(reestablish_1.len(), 3);
7408 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7409 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7410 assert_eq!(reestablish_2.len(), 3);
7412 // Reestablish chan_1
7413 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7414 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7415 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7416 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7417 // Reestablish chan_2
7418 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7419 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7420 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7421 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7422 // Reestablish chan_3
7423 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7424 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7425 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7426 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7428 nodes[0].node.timer_tick_occurred();
7429 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7430 nodes[0].node.timer_tick_occurred();
7431 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7432 assert_eq!(msg_events.len(), 3);
7433 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7434 for e in msg_events {
7436 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7437 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7438 // Check that each channel gets updated exactly once
7439 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7440 panic!("Generated ChannelUpdate for wrong chan!");
7443 _ => panic!("Unexpected event"),
7449 fn test_priv_forwarding_rejection() {
7450 // If we have a private channel with outbound liquidity, and
7451 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7452 // to forward through that channel.
7453 let chanmon_cfgs = create_chanmon_cfgs(3);
7454 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7455 let mut no_announce_cfg = test_default_channel_config();
7456 no_announce_cfg.channel_options.announced_channel = false;
7457 no_announce_cfg.accept_forwards_to_priv_channels = false;
7458 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7459 let persister: test_utils::TestPersister;
7460 let new_chain_monitor: test_utils::TestChainMonitor;
7461 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7462 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7464 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7466 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7467 // not send for private channels.
7468 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7469 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7470 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7471 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7472 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7474 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7475 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7476 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()));
7477 check_added_monitors!(nodes[2], 1);
7479 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()));
7480 check_added_monitors!(nodes[1], 1);
7482 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7483 confirm_transaction_at(&nodes[1], &tx, conf_height);
7484 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7485 confirm_transaction_at(&nodes[2], &tx, conf_height);
7486 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7487 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7488 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()));
7489 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7490 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7491 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7493 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7494 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7495 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7497 // We should always be able to forward through nodes[1] as long as its out through a public
7499 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7501 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7502 // to nodes[2], which should be rejected:
7503 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7504 let route = get_route(&nodes[0].node.get_our_node_id(),
7505 &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
7506 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
7507 &[&RouteHint(vec![RouteHintHop {
7508 src_node_id: nodes[1].node.get_our_node_id(),
7509 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7510 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7511 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7512 htlc_minimum_msat: None,
7513 htlc_maximum_msat: None,
7514 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7516 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7517 check_added_monitors!(nodes[0], 1);
7518 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7519 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7520 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7522 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7523 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7524 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7525 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7526 assert!(htlc_fail_updates.update_fee.is_none());
7528 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7529 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7530 expect_payment_failed!(nodes[0], our_payment_hash, false);
7531 expect_payment_failure_chan_update!(nodes[0], nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7533 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7534 // to true. Sadly there is currently no way to change it at runtime.
7536 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7537 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7539 let nodes_1_serialized = nodes[1].node.encode();
7540 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7541 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7543 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7544 let mut mon_iter = mons.iter();
7545 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7546 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7549 persister = test_utils::TestPersister::new();
7550 let keys_manager = &chanmon_cfgs[1].keys_manager;
7551 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);
7552 nodes[1].chain_monitor = &new_chain_monitor;
7554 let mut monitor_a_read = &monitor_a_serialized.0[..];
7555 let mut monitor_b_read = &monitor_b_serialized.0[..];
7556 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7557 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7558 assert!(monitor_a_read.is_empty());
7559 assert!(monitor_b_read.is_empty());
7561 no_announce_cfg.accept_forwards_to_priv_channels = true;
7563 let mut nodes_1_read = &nodes_1_serialized[..];
7564 let (_, nodes_1_deserialized_tmp) = {
7565 let mut channel_monitors = HashMap::new();
7566 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7567 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7568 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7569 default_config: no_announce_cfg,
7571 fee_estimator: node_cfgs[1].fee_estimator,
7572 chain_monitor: nodes[1].chain_monitor,
7573 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7574 logger: nodes[1].logger,
7578 assert!(nodes_1_read.is_empty());
7579 nodes_1_deserialized = nodes_1_deserialized_tmp;
7581 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7582 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7583 check_added_monitors!(nodes[1], 2);
7584 nodes[1].node = &nodes_1_deserialized;
7586 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7587 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7588 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7589 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7590 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7591 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7592 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7593 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7595 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7596 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7597 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7598 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7599 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7600 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7601 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7602 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7604 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7605 check_added_monitors!(nodes[0], 1);
7606 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7607 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7611 fn test_bump_penalty_txn_on_revoked_commitment() {
7612 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7613 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7615 let chanmon_cfgs = create_chanmon_cfgs(2);
7616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7618 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7620 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7621 let logger = test_utils::TestLogger::new();
7623 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7624 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7625 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();
7626 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7628 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7629 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7630 assert_eq!(revoked_txn[0].output.len(), 4);
7631 assert_eq!(revoked_txn[0].input.len(), 1);
7632 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7633 let revoked_txid = revoked_txn[0].txid();
7635 let mut penalty_sum = 0;
7636 for outp in revoked_txn[0].output.iter() {
7637 if outp.script_pubkey.is_v0_p2wsh() {
7638 penalty_sum += outp.value;
7642 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7643 let header_114 = connect_blocks(&nodes[1], 14);
7645 // Actually revoke tx by claiming a HTLC
7646 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7647 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7648 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7649 check_added_monitors!(nodes[1], 1);
7651 // One or more justice tx should have been broadcast, check it
7655 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7656 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7657 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7658 assert_eq!(node_txn[0].output.len(), 1);
7659 check_spends!(node_txn[0], revoked_txn[0]);
7660 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7661 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7662 penalty_1 = node_txn[0].txid();
7666 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7667 connect_blocks(&nodes[1], 15);
7668 let mut penalty_2 = penalty_1;
7669 let mut feerate_2 = 0;
7671 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7672 assert_eq!(node_txn.len(), 1);
7673 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7674 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7675 assert_eq!(node_txn[0].output.len(), 1);
7676 check_spends!(node_txn[0], revoked_txn[0]);
7677 penalty_2 = node_txn[0].txid();
7678 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7679 assert_ne!(penalty_2, penalty_1);
7680 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7681 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7682 // Verify 25% bump heuristic
7683 assert!(feerate_2 * 100 >= feerate_1 * 125);
7687 assert_ne!(feerate_2, 0);
7689 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7690 connect_blocks(&nodes[1], 1);
7692 let mut feerate_3 = 0;
7694 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7695 assert_eq!(node_txn.len(), 1);
7696 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7697 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7698 assert_eq!(node_txn[0].output.len(), 1);
7699 check_spends!(node_txn[0], revoked_txn[0]);
7700 penalty_3 = node_txn[0].txid();
7701 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7702 assert_ne!(penalty_3, penalty_2);
7703 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7704 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7705 // Verify 25% bump heuristic
7706 assert!(feerate_3 * 100 >= feerate_2 * 125);
7710 assert_ne!(feerate_3, 0);
7712 nodes[1].node.get_and_clear_pending_events();
7713 nodes[1].node.get_and_clear_pending_msg_events();
7717 fn test_bump_penalty_txn_on_revoked_htlcs() {
7718 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7719 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7721 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7722 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7727 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7728 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7729 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
7730 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7731 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7732 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph.read().unwrap(),
7733 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7734 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7736 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7737 assert_eq!(revoked_local_txn[0].input.len(), 1);
7738 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7740 // Revoke local commitment tx
7741 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7743 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7744 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7745 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7746 check_closed_broadcast!(nodes[1], true);
7747 check_added_monitors!(nodes[1], 1);
7748 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7750 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7751 assert_eq!(revoked_htlc_txn.len(), 3);
7752 check_spends!(revoked_htlc_txn[1], chan.3);
7754 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7755 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7756 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7758 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7759 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7760 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7761 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7763 // Broadcast set of revoked txn on A
7764 let hash_128 = connect_blocks(&nodes[0], 40);
7765 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7766 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7767 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7768 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7769 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7774 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7775 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7776 // Verify claim tx are spending revoked HTLC txn
7778 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7779 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7780 // which are included in the same block (they are broadcasted because we scan the
7781 // transactions linearly and generate claims as we go, they likely should be removed in the
7783 assert_eq!(node_txn[0].input.len(), 1);
7784 check_spends!(node_txn[0], revoked_local_txn[0]);
7785 assert_eq!(node_txn[1].input.len(), 1);
7786 check_spends!(node_txn[1], revoked_local_txn[0]);
7787 assert_eq!(node_txn[2].input.len(), 1);
7788 check_spends!(node_txn[2], revoked_local_txn[0]);
7790 // Each of the three justice transactions claim a separate (single) output of the three
7791 // available, which we check here:
7792 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7793 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7794 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7796 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7797 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7799 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7800 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7801 // a remote commitment tx has already been confirmed).
7802 check_spends!(node_txn[3], chan.3);
7804 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7805 // output, checked above).
7806 assert_eq!(node_txn[4].input.len(), 2);
7807 assert_eq!(node_txn[4].output.len(), 1);
7808 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7810 first = node_txn[4].txid();
7811 // Store both feerates for later comparison
7812 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7813 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7814 penalty_txn = vec![node_txn[2].clone()];
7818 // Connect one more block to see if bumped penalty are issued for HTLC txn
7819 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7820 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7821 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7822 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7824 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7825 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7827 check_spends!(node_txn[0], revoked_local_txn[0]);
7828 check_spends!(node_txn[1], revoked_local_txn[0]);
7829 // Note that these are both bogus - they spend outputs already claimed in block 129:
7830 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7831 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7833 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7834 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7840 // Few more blocks to confirm penalty txn
7841 connect_blocks(&nodes[0], 4);
7842 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7843 let header_144 = connect_blocks(&nodes[0], 9);
7845 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7846 assert_eq!(node_txn.len(), 1);
7848 assert_eq!(node_txn[0].input.len(), 2);
7849 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7850 // Verify bumped tx is different and 25% bump heuristic
7851 assert_ne!(first, node_txn[0].txid());
7852 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7853 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7854 assert!(feerate_2 * 100 > feerate_1 * 125);
7855 let txn = vec![node_txn[0].clone()];
7859 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7860 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7861 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7862 connect_blocks(&nodes[0], 20);
7864 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7865 // We verify than no new transaction has been broadcast because previously
7866 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7867 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7868 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7869 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7870 // up bumped justice generation.
7871 assert_eq!(node_txn.len(), 0);
7874 check_closed_broadcast!(nodes[0], true);
7875 check_added_monitors!(nodes[0], 1);
7879 fn test_bump_penalty_txn_on_remote_commitment() {
7880 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7881 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7884 // Provide preimage for one
7885 // Check aggregation
7887 let chanmon_cfgs = create_chanmon_cfgs(2);
7888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7890 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7892 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7893 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7894 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7896 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7897 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7898 assert_eq!(remote_txn[0].output.len(), 4);
7899 assert_eq!(remote_txn[0].input.len(), 1);
7900 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7902 // Claim a HTLC without revocation (provide B monitor with preimage)
7903 nodes[1].node.claim_funds(payment_preimage);
7904 mine_transaction(&nodes[1], &remote_txn[0]);
7905 check_added_monitors!(nodes[1], 2);
7906 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7908 // One or more claim tx should have been broadcast, check it
7912 let feerate_timeout;
7913 let feerate_preimage;
7915 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7916 // 9 transactions including:
7917 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7918 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7919 // 2 * HTLC-Success (one RBF bump we'll check later)
7921 assert_eq!(node_txn.len(), 8);
7922 assert_eq!(node_txn[0].input.len(), 1);
7923 assert_eq!(node_txn[6].input.len(), 1);
7924 check_spends!(node_txn[0], remote_txn[0]);
7925 check_spends!(node_txn[6], remote_txn[0]);
7926 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7927 preimage_bump = node_txn[3].clone();
7929 check_spends!(node_txn[1], chan.3);
7930 check_spends!(node_txn[2], node_txn[1]);
7931 assert_eq!(node_txn[1], node_txn[4]);
7932 assert_eq!(node_txn[2], node_txn[5]);
7934 timeout = node_txn[6].txid();
7935 let index = node_txn[6].input[0].previous_output.vout;
7936 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7937 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7939 preimage = node_txn[0].txid();
7940 let index = node_txn[0].input[0].previous_output.vout;
7941 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7942 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7946 assert_ne!(feerate_timeout, 0);
7947 assert_ne!(feerate_preimage, 0);
7949 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7950 connect_blocks(&nodes[1], 15);
7952 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7953 assert_eq!(node_txn.len(), 1);
7954 assert_eq!(node_txn[0].input.len(), 1);
7955 assert_eq!(preimage_bump.input.len(), 1);
7956 check_spends!(node_txn[0], remote_txn[0]);
7957 check_spends!(preimage_bump, remote_txn[0]);
7959 let index = preimage_bump.input[0].previous_output.vout;
7960 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7961 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7962 assert!(new_feerate * 100 > feerate_timeout * 125);
7963 assert_ne!(timeout, preimage_bump.txid());
7965 let index = node_txn[0].input[0].previous_output.vout;
7966 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7967 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7968 assert!(new_feerate * 100 > feerate_preimage * 125);
7969 assert_ne!(preimage, node_txn[0].txid());
7974 nodes[1].node.get_and_clear_pending_events();
7975 nodes[1].node.get_and_clear_pending_msg_events();
7979 fn test_counterparty_raa_skip_no_crash() {
7980 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7981 // commitment transaction, we would have happily carried on and provided them the next
7982 // commitment transaction based on one RAA forward. This would probably eventually have led to
7983 // channel closure, but it would not have resulted in funds loss. Still, our
7984 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
7985 // check simply that the channel is closed in response to such an RAA, but don't check whether
7986 // we decide to punish our counterparty for revoking their funds (as we don't currently
7988 let chanmon_cfgs = create_chanmon_cfgs(2);
7989 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7990 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7991 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7992 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7994 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7995 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7996 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7997 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7998 // Must revoke without gaps
7999 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8000 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8001 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8003 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8004 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8005 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8006 check_added_monitors!(nodes[1], 1);
8010 fn test_bump_txn_sanitize_tracking_maps() {
8011 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8012 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8014 let chanmon_cfgs = create_chanmon_cfgs(2);
8015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8017 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8019 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8020 // Lock HTLC in both directions
8021 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8022 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8024 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8025 assert_eq!(revoked_local_txn[0].input.len(), 1);
8026 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8028 // Revoke local commitment tx
8029 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8031 // Broadcast set of revoked txn on A
8032 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8033 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8034 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8036 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8037 check_closed_broadcast!(nodes[0], true);
8038 check_added_monitors!(nodes[0], 1);
8040 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8041 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8042 check_spends!(node_txn[0], revoked_local_txn[0]);
8043 check_spends!(node_txn[1], revoked_local_txn[0]);
8044 check_spends!(node_txn[2], revoked_local_txn[0]);
8045 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8049 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8050 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8051 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8053 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8054 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8055 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8056 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8062 fn test_override_channel_config() {
8063 let chanmon_cfgs = create_chanmon_cfgs(2);
8064 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8065 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8066 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8068 // Node0 initiates a channel to node1 using the override config.
8069 let mut override_config = UserConfig::default();
8070 override_config.own_channel_config.our_to_self_delay = 200;
8072 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8074 // Assert the channel created by node0 is using the override config.
8075 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8076 assert_eq!(res.channel_flags, 0);
8077 assert_eq!(res.to_self_delay, 200);
8081 fn test_override_0msat_htlc_minimum() {
8082 let mut zero_config = UserConfig::default();
8083 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8084 let chanmon_cfgs = create_chanmon_cfgs(2);
8085 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8086 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8087 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8089 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8090 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8091 assert_eq!(res.htlc_minimum_msat, 1);
8093 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8094 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8095 assert_eq!(res.htlc_minimum_msat, 1);
8099 fn test_simple_mpp() {
8100 // Simple test of sending a multi-path payment.
8101 let chanmon_cfgs = create_chanmon_cfgs(4);
8102 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8103 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8104 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8106 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8107 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8108 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8109 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8110 let logger = test_utils::TestLogger::new();
8112 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8113 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8114 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();
8115 let path = route.paths[0].clone();
8116 route.paths.push(path);
8117 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8118 route.paths[0][0].short_channel_id = chan_1_id;
8119 route.paths[0][1].short_channel_id = chan_3_id;
8120 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8121 route.paths[1][0].short_channel_id = chan_2_id;
8122 route.paths[1][1].short_channel_id = chan_4_id;
8123 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8124 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8128 fn test_preimage_storage() {
8129 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8130 let chanmon_cfgs = create_chanmon_cfgs(2);
8131 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8132 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8133 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8135 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8138 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8140 let logger = test_utils::TestLogger::new();
8141 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8142 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();
8143 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8144 check_added_monitors!(nodes[0], 1);
8145 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8146 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8148 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8150 // Note that after leaving the above scope we have no knowledge of any arguments or return
8151 // values from previous calls.
8152 expect_pending_htlcs_forwardable!(nodes[1]);
8153 let events = nodes[1].node.get_and_clear_pending_events();
8154 assert_eq!(events.len(), 1);
8156 Event::PaymentReceived { ref purpose, .. } => {
8158 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8159 assert_eq!(*user_payment_id, 42);
8160 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8162 _ => panic!("expected PaymentPurpose::InvoicePayment")
8165 _ => panic!("Unexpected event"),
8170 fn test_secret_timeout() {
8171 // Simple test of payment secret storage time outs
8172 let chanmon_cfgs = create_chanmon_cfgs(2);
8173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8177 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8179 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8181 // We should fail to register the same payment hash twice, at least until we've connected a
8182 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8183 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8184 assert_eq!(err, "Duplicate payment hash");
8185 } else { panic!(); }
8187 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8189 header: BlockHeader {
8191 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8192 merkle_root: Default::default(),
8193 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8197 connect_block(&nodes[1], &block);
8198 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8199 assert_eq!(err, "Duplicate payment hash");
8200 } else { panic!(); }
8202 // If we then connect the second block, we should be able to register the same payment hash
8203 // again with a different user_payment_id (this time getting a new payment secret).
8204 block.header.prev_blockhash = block.header.block_hash();
8205 block.header.time += 1;
8206 connect_block(&nodes[1], &block);
8207 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8208 assert_ne!(payment_secret_1, our_payment_secret);
8211 let logger = test_utils::TestLogger::new();
8212 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8213 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();
8214 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8215 check_added_monitors!(nodes[0], 1);
8216 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8217 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8218 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8219 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8221 // Note that after leaving the above scope we have no knowledge of any arguments or return
8222 // values from previous calls.
8223 expect_pending_htlcs_forwardable!(nodes[1]);
8224 let events = nodes[1].node.get_and_clear_pending_events();
8225 assert_eq!(events.len(), 1);
8227 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8228 assert!(payment_preimage.is_none());
8229 assert_eq!(user_payment_id, 42);
8230 assert_eq!(payment_secret, our_payment_secret);
8231 // We don't actually have the payment preimage with which to claim this payment!
8233 _ => panic!("Unexpected event"),
8238 fn test_bad_secret_hash() {
8239 // Simple test of unregistered payment hash/invalid payment secret handling
8240 let chanmon_cfgs = create_chanmon_cfgs(2);
8241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8243 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8245 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8247 let random_payment_hash = PaymentHash([42; 32]);
8248 let random_payment_secret = PaymentSecret([43; 32]);
8249 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8251 let logger = test_utils::TestLogger::new();
8252 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8253 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();
8255 // All the below cases should end up being handled exactly identically, so we macro the
8256 // resulting events.
8257 macro_rules! handle_unknown_invalid_payment_data {
8259 check_added_monitors!(nodes[0], 1);
8260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8261 let payment_event = SendEvent::from_event(events.pop().unwrap());
8262 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8263 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8265 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8266 // again to process the pending backwards-failure of the HTLC
8267 expect_pending_htlcs_forwardable!(nodes[1]);
8268 expect_pending_htlcs_forwardable!(nodes[1]);
8269 check_added_monitors!(nodes[1], 1);
8271 // We should fail the payment back
8272 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8273 match events.pop().unwrap() {
8274 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8275 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8276 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8278 _ => panic!("Unexpected event"),
8283 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8284 // Error data is the HTLC value (100,000) and current block height
8285 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8287 // Send a payment with the right payment hash but the wrong payment secret
8288 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8289 handle_unknown_invalid_payment_data!();
8290 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8292 // Send a payment with a random payment hash, but the right payment secret
8293 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8294 handle_unknown_invalid_payment_data!();
8295 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8297 // Send a payment with a random payment hash and random payment secret
8298 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8299 handle_unknown_invalid_payment_data!();
8300 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8304 fn test_update_err_monitor_lockdown() {
8305 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8306 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8307 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8309 // This scenario may happen in a watchtower setup, where watchtower process a block height
8310 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8311 // commitment at same time.
8313 let chanmon_cfgs = create_chanmon_cfgs(2);
8314 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8315 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8316 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8318 // Create some initial channel
8319 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8320 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8322 // Rebalance the network to generate htlc in the two directions
8323 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8325 // Route a HTLC from node 0 to node 1 (but don't settle)
8326 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8328 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8329 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8330 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8331 let persister = test_utils::TestPersister::new();
8333 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8334 let monitor = monitors.get(&outpoint).unwrap();
8335 let mut w = test_utils::TestVecWriter(Vec::new());
8336 monitor.write(&mut w).unwrap();
8337 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8338 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8339 assert!(new_monitor == *monitor);
8340 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);
8341 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8344 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8345 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8346 // transaction lock time requirements here.
8347 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8348 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8350 // Try to update ChannelMonitor
8351 assert!(nodes[1].node.claim_funds(preimage));
8352 check_added_monitors!(nodes[1], 1);
8353 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8354 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8355 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8356 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8357 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8358 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8359 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8360 } else { assert!(false); }
8361 } else { assert!(false); };
8362 // Our local monitor is in-sync and hasn't processed yet timeout
8363 check_added_monitors!(nodes[0], 1);
8364 let events = nodes[0].node.get_and_clear_pending_events();
8365 assert_eq!(events.len(), 1);
8369 fn test_concurrent_monitor_claim() {
8370 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8371 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8372 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8373 // state N+1 confirms. Alice claims output from state N+1.
8375 let chanmon_cfgs = create_chanmon_cfgs(2);
8376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8378 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8380 // Create some initial channel
8381 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8382 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8384 // Rebalance the network to generate htlc in the two directions
8385 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8387 // Route a HTLC from node 0 to node 1 (but don't settle)
8388 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8390 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8391 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8392 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8393 let persister = test_utils::TestPersister::new();
8394 let watchtower_alice = {
8395 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8396 let monitor = monitors.get(&outpoint).unwrap();
8397 let mut w = test_utils::TestVecWriter(Vec::new());
8398 monitor.write(&mut w).unwrap();
8399 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8400 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8401 assert!(new_monitor == *monitor);
8402 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);
8403 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8406 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8407 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8408 // transaction lock time requirements here.
8409 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8410 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8412 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8414 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8415 assert_eq!(txn.len(), 2);
8419 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8420 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8421 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8422 let persister = test_utils::TestPersister::new();
8423 let watchtower_bob = {
8424 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8425 let monitor = monitors.get(&outpoint).unwrap();
8426 let mut w = test_utils::TestVecWriter(Vec::new());
8427 monitor.write(&mut w).unwrap();
8428 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8429 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8430 assert!(new_monitor == *monitor);
8431 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);
8432 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8435 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8436 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8438 // Route another payment to generate another update with still previous HTLC pending
8439 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8441 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8442 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();
8443 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8445 check_added_monitors!(nodes[1], 1);
8447 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8448 assert_eq!(updates.update_add_htlcs.len(), 1);
8449 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8450 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8451 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8452 // Watchtower Alice should already have seen the block and reject the update
8453 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8454 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8455 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8456 } else { assert!(false); }
8457 } else { assert!(false); };
8458 // Our local monitor is in-sync and hasn't processed yet timeout
8459 check_added_monitors!(nodes[0], 1);
8461 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8462 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8463 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8465 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8468 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8469 assert_eq!(txn.len(), 2);
8470 bob_state_y = txn[0].clone();
8474 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8475 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8476 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);
8478 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8479 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8480 // the onchain detection of the HTLC output
8481 assert_eq!(htlc_txn.len(), 2);
8482 check_spends!(htlc_txn[0], bob_state_y);
8483 check_spends!(htlc_txn[1], bob_state_y);
8488 fn test_pre_lockin_no_chan_closed_update() {
8489 // Test that if a peer closes a channel in response to a funding_created message we don't
8490 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8493 // Doing so would imply a channel monitor update before the initial channel monitor
8494 // registration, violating our API guarantees.
8496 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8497 // then opening a second channel with the same funding output as the first (which is not
8498 // rejected because the first channel does not exist in the ChannelManager) and closing it
8499 // before receiving funding_signed.
8500 let chanmon_cfgs = create_chanmon_cfgs(2);
8501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8503 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8505 // Create an initial channel
8506 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8507 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8508 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8509 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8510 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8512 // Move the first channel through the funding flow...
8513 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8515 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8516 check_added_monitors!(nodes[0], 0);
8518 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8519 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8520 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8521 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8525 fn test_htlc_no_detection() {
8526 // This test is a mutation to underscore the detection logic bug we had
8527 // before #653. HTLC value routed is above the remaining balance, thus
8528 // inverting HTLC and `to_remote` output. HTLC will come second and
8529 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8530 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8531 // outputs order detection for correct spending children filtring.
8533 let chanmon_cfgs = create_chanmon_cfgs(2);
8534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8536 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8538 // Create some initial channels
8539 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8541 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8542 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8543 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8544 assert_eq!(local_txn[0].input.len(), 1);
8545 assert_eq!(local_txn[0].output.len(), 3);
8546 check_spends!(local_txn[0], chan_1.3);
8548 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8549 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8550 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8551 // We deliberately connect the local tx twice as this should provoke a failure calling
8552 // this test before #653 fix.
8553 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);
8554 check_closed_broadcast!(nodes[0], true);
8555 check_added_monitors!(nodes[0], 1);
8556 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8558 let htlc_timeout = {
8559 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8560 assert_eq!(node_txn[1].input.len(), 1);
8561 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8562 check_spends!(node_txn[1], local_txn[0]);
8566 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8567 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8568 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8569 expect_payment_failed!(nodes[0], our_payment_hash, true);
8572 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8573 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8574 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8575 // Carol, Alice would be the upstream node, and Carol the downstream.)
8577 // Steps of the test:
8578 // 1) Alice sends a HTLC to Carol through Bob.
8579 // 2) Carol doesn't settle the HTLC.
8580 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8581 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8582 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8583 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8584 // 5) Carol release the preimage to Bob off-chain.
8585 // 6) Bob claims the offered output on the broadcasted commitment.
8586 let chanmon_cfgs = create_chanmon_cfgs(3);
8587 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8589 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8591 // Create some initial channels
8592 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8593 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8595 // Steps (1) and (2):
8596 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8597 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8599 // Check that Alice's commitment transaction now contains an output for this HTLC.
8600 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8601 check_spends!(alice_txn[0], chan_ab.3);
8602 assert_eq!(alice_txn[0].output.len(), 2);
8603 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8604 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8605 assert_eq!(alice_txn.len(), 2);
8607 // Steps (3) and (4):
8608 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8609 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8610 let mut force_closing_node = 0; // Alice force-closes
8611 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8612 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8613 check_closed_broadcast!(nodes[force_closing_node], true);
8614 check_added_monitors!(nodes[force_closing_node], 1);
8615 if go_onchain_before_fulfill {
8616 let txn_to_broadcast = match broadcast_alice {
8617 true => alice_txn.clone(),
8618 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8620 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8621 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8622 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8623 if broadcast_alice {
8624 check_closed_broadcast!(nodes[1], true);
8625 check_added_monitors!(nodes[1], 1);
8627 assert_eq!(bob_txn.len(), 1);
8628 check_spends!(bob_txn[0], chan_ab.3);
8632 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8633 // process of removing the HTLC from their commitment transactions.
8634 assert!(nodes[2].node.claim_funds(payment_preimage));
8635 check_added_monitors!(nodes[2], 1);
8636 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8637 assert!(carol_updates.update_add_htlcs.is_empty());
8638 assert!(carol_updates.update_fail_htlcs.is_empty());
8639 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8640 assert!(carol_updates.update_fee.is_none());
8641 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8643 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8644 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8645 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8646 if !go_onchain_before_fulfill && broadcast_alice {
8647 let events = nodes[1].node.get_and_clear_pending_msg_events();
8648 assert_eq!(events.len(), 1);
8650 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8651 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8653 _ => panic!("Unexpected event"),
8656 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8657 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8658 // Carol<->Bob's updated commitment transaction info.
8659 check_added_monitors!(nodes[1], 2);
8661 let events = nodes[1].node.get_and_clear_pending_msg_events();
8662 assert_eq!(events.len(), 2);
8663 let bob_revocation = match events[0] {
8664 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8665 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8668 _ => panic!("Unexpected event"),
8670 let bob_updates = match events[1] {
8671 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8672 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8675 _ => panic!("Unexpected event"),
8678 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8679 check_added_monitors!(nodes[2], 1);
8680 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8681 check_added_monitors!(nodes[2], 1);
8683 let events = nodes[2].node.get_and_clear_pending_msg_events();
8684 assert_eq!(events.len(), 1);
8685 let carol_revocation = match events[0] {
8686 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8687 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8690 _ => panic!("Unexpected event"),
8692 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8693 check_added_monitors!(nodes[1], 1);
8695 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8696 // here's where we put said channel's commitment tx on-chain.
8697 let mut txn_to_broadcast = alice_txn.clone();
8698 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8699 if !go_onchain_before_fulfill {
8700 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8701 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8702 // If Bob was the one to force-close, he will have already passed these checks earlier.
8703 if broadcast_alice {
8704 check_closed_broadcast!(nodes[1], true);
8705 check_added_monitors!(nodes[1], 1);
8707 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8708 if broadcast_alice {
8709 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8710 // new block being connected. The ChannelManager being notified triggers a monitor update,
8711 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8712 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8714 assert_eq!(bob_txn.len(), 3);
8715 check_spends!(bob_txn[1], chan_ab.3);
8717 assert_eq!(bob_txn.len(), 2);
8718 check_spends!(bob_txn[0], chan_ab.3);
8723 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8724 // broadcasted commitment transaction.
8726 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8727 if go_onchain_before_fulfill {
8728 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8729 assert_eq!(bob_txn.len(), 2);
8731 let script_weight = match broadcast_alice {
8732 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8733 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8735 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8736 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8737 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8738 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8739 if broadcast_alice && !go_onchain_before_fulfill {
8740 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8741 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8743 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8744 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8750 fn test_onchain_htlc_settlement_after_close() {
8751 do_test_onchain_htlc_settlement_after_close(true, true);
8752 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8753 do_test_onchain_htlc_settlement_after_close(true, false);
8754 do_test_onchain_htlc_settlement_after_close(false, false);
8758 fn test_duplicate_chan_id() {
8759 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8760 // already open we reject it and keep the old channel.
8762 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8763 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8764 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8765 // updating logic for the existing channel.
8766 let chanmon_cfgs = create_chanmon_cfgs(2);
8767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8771 // Create an initial channel
8772 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8773 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8774 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8775 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()));
8777 // Try to create a second channel with the same temporary_channel_id as the first and check
8778 // that it is rejected.
8779 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8781 let events = nodes[1].node.get_and_clear_pending_msg_events();
8782 assert_eq!(events.len(), 1);
8784 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8785 // Technically, at this point, nodes[1] would be justified in thinking both the
8786 // first (valid) and second (invalid) channels are closed, given they both have
8787 // the same non-temporary channel_id. However, currently we do not, so we just
8788 // move forward with it.
8789 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8790 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8792 _ => panic!("Unexpected event"),
8796 // Move the first channel through the funding flow...
8797 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8799 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8800 check_added_monitors!(nodes[0], 0);
8802 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8803 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8805 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8806 assert_eq!(added_monitors.len(), 1);
8807 assert_eq!(added_monitors[0].0, funding_output);
8808 added_monitors.clear();
8810 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8812 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8813 let channel_id = funding_outpoint.to_channel_id();
8815 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8818 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8819 // Technically this is allowed by the spec, but we don't support it and there's little reason
8820 // to. Still, it shouldn't cause any other issues.
8821 open_chan_msg.temporary_channel_id = channel_id;
8822 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8824 let events = nodes[1].node.get_and_clear_pending_msg_events();
8825 assert_eq!(events.len(), 1);
8827 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8828 // Technically, at this point, nodes[1] would be justified in thinking both
8829 // channels are closed, but currently we do not, so we just move forward with it.
8830 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8831 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8833 _ => panic!("Unexpected event"),
8837 // Now try to create a second channel which has a duplicate funding output.
8838 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8839 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8840 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8841 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()));
8842 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8844 let funding_created = {
8845 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8846 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8847 let logger = test_utils::TestLogger::new();
8848 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8850 check_added_monitors!(nodes[0], 0);
8851 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8852 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8853 // still needs to be cleared here.
8854 check_added_monitors!(nodes[1], 1);
8856 // ...still, nodes[1] will reject the duplicate channel.
8858 let events = nodes[1].node.get_and_clear_pending_msg_events();
8859 assert_eq!(events.len(), 1);
8861 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8862 // Technically, at this point, nodes[1] would be justified in thinking both
8863 // channels are closed, but currently we do not, so we just move forward with it.
8864 assert_eq!(msg.channel_id, channel_id);
8865 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8867 _ => panic!("Unexpected event"),
8871 // finally, finish creating the original channel and send a payment over it to make sure
8872 // everything is functional.
8873 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8875 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8876 assert_eq!(added_monitors.len(), 1);
8877 assert_eq!(added_monitors[0].0, funding_output);
8878 added_monitors.clear();
8881 let events_4 = nodes[0].node.get_and_clear_pending_events();
8882 assert_eq!(events_4.len(), 0);
8883 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8884 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8886 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8887 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8888 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8889 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8893 fn test_error_chans_closed() {
8894 // Test that we properly handle error messages, closing appropriate channels.
8896 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8897 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8898 // we can test various edge cases around it to ensure we don't regress.
8899 let chanmon_cfgs = create_chanmon_cfgs(3);
8900 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8901 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8902 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8904 // Create some initial channels
8905 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8906 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8907 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8909 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8910 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8911 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8913 // Closing a channel from a different peer has no effect
8914 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8915 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8917 // Closing one channel doesn't impact others
8918 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8919 check_added_monitors!(nodes[0], 1);
8920 check_closed_broadcast!(nodes[0], false);
8921 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8922 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8923 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);
8924 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);
8926 // A null channel ID should close all channels
8927 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8928 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8929 check_added_monitors!(nodes[0], 2);
8930 let events = nodes[0].node.get_and_clear_pending_msg_events();
8931 assert_eq!(events.len(), 2);
8933 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8934 assert_eq!(msg.contents.flags & 2, 2);
8936 _ => panic!("Unexpected event"),
8939 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8940 assert_eq!(msg.contents.flags & 2, 2);
8942 _ => panic!("Unexpected event"),
8944 // Note that at this point users of a standard PeerHandler will end up calling
8945 // peer_disconnected with no_connection_possible set to false, duplicating the
8946 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8947 // users with their own peer handling logic. We duplicate the call here, however.
8948 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8949 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8951 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8952 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8953 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8957 fn test_invalid_funding_tx() {
8958 // Test that we properly handle invalid funding transactions sent to us from a peer.
8960 // Previously, all other major lightning implementations had failed to properly sanitize
8961 // funding transactions from their counterparties, leading to a multi-implementation critical
8962 // security vulnerability (though we always sanitized properly, we've previously had
8963 // un-released crashes in the sanitization process).
8964 let chanmon_cfgs = create_chanmon_cfgs(2);
8965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8967 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8969 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8970 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()));
8971 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()));
8973 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8974 for output in tx.output.iter_mut() {
8975 // Make the confirmed funding transaction have a bogus script_pubkey
8976 output.script_pubkey = bitcoin::Script::new();
8979 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8980 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()));
8981 check_added_monitors!(nodes[1], 1);
8983 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()));
8984 check_added_monitors!(nodes[0], 1);
8986 let events_1 = nodes[0].node.get_and_clear_pending_events();
8987 assert_eq!(events_1.len(), 0);
8989 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8990 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8991 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8993 confirm_transaction_at(&nodes[1], &tx, 1);
8994 check_added_monitors!(nodes[1], 1);
8995 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8996 assert_eq!(events_2.len(), 1);
8997 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8998 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8999 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9000 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9001 } else { panic!(); }
9002 } else { panic!(); }
9003 assert_eq!(nodes[1].node.list_channels().len(), 0);
9006 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9007 // In the first version of the chain::Confirm interface, after a refactor was made to not
9008 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9009 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9010 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9011 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9012 // spending transaction until height N+1 (or greater). This was due to the way
9013 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9014 // spending transaction at the height the input transaction was confirmed at, not whether we
9015 // should broadcast a spending transaction at the current height.
9016 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9017 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9018 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9019 // until we learned about an additional block.
9021 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9022 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9023 let chanmon_cfgs = create_chanmon_cfgs(3);
9024 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9025 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9026 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9027 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9029 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9030 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9031 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9032 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9033 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9035 nodes[1].node.force_close_channel(&channel_id).unwrap();
9036 check_closed_broadcast!(nodes[1], true);
9037 check_added_monitors!(nodes[1], 1);
9038 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9039 assert_eq!(node_txn.len(), 1);
9041 let conf_height = nodes[1].best_block_info().1;
9042 if !test_height_before_timelock {
9043 connect_blocks(&nodes[1], 24 * 6);
9045 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9046 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9047 if test_height_before_timelock {
9048 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9049 // generate any events or broadcast any transactions
9050 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9051 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9053 // We should broadcast an HTLC transaction spending our funding transaction first
9054 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9055 assert_eq!(spending_txn.len(), 2);
9056 assert_eq!(spending_txn[0], node_txn[0]);
9057 check_spends!(spending_txn[1], node_txn[0]);
9058 // We should also generate a SpendableOutputs event with the to_self output (as its
9060 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9061 assert_eq!(descriptor_spend_txn.len(), 1);
9063 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9064 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9065 // additional block built on top of the current chain.
9066 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9067 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9068 expect_pending_htlcs_forwardable!(nodes[1]);
9069 check_added_monitors!(nodes[1], 1);
9071 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9072 assert!(updates.update_add_htlcs.is_empty());
9073 assert!(updates.update_fulfill_htlcs.is_empty());
9074 assert_eq!(updates.update_fail_htlcs.len(), 1);
9075 assert!(updates.update_fail_malformed_htlcs.is_empty());
9076 assert!(updates.update_fee.is_none());
9077 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9078 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9079 expect_payment_failed!(nodes[0], payment_hash, false);
9080 expect_payment_failure_chan_update!(nodes[0], chan_announce.contents.short_channel_id, true);
9085 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9086 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9087 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9091 fn test_keysend_payments_to_public_node() {
9092 let chanmon_cfgs = create_chanmon_cfgs(2);
9093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9097 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9098 let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
9099 let payer_pubkey = nodes[0].node.get_our_node_id();
9100 let payee_pubkey = nodes[1].node.get_our_node_id();
9101 let route = get_route(&payer_pubkey, &network_graph, &payee_pubkey, None,
9102 None, &vec![], 10000, 40,
9103 nodes[0].logger).unwrap();
9105 let test_preimage = PaymentPreimage([42; 32]);
9106 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9107 check_added_monitors!(nodes[0], 1);
9108 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9109 assert_eq!(events.len(), 1);
9110 let event = events.pop().unwrap();
9111 let path = vec![&nodes[1]];
9112 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9113 claim_payment(&nodes[0], &path, test_preimage);
9117 fn test_keysend_payments_to_private_node() {
9118 let chanmon_cfgs = create_chanmon_cfgs(2);
9119 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9120 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9121 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9123 let payer_pubkey = nodes[0].node.get_our_node_id();
9124 let payee_pubkey = nodes[1].node.get_our_node_id();
9125 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9126 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9128 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9129 let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
9130 let first_hops = nodes[0].node.list_usable_channels();
9131 let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9132 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9133 nodes[0].logger).unwrap();
9135 let test_preimage = PaymentPreimage([42; 32]);
9136 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9137 check_added_monitors!(nodes[0], 1);
9138 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9139 assert_eq!(events.len(), 1);
9140 let event = events.pop().unwrap();
9141 let path = vec![&nodes[1]];
9142 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9143 claim_payment(&nodes[0], &path, test_preimage);
9146 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, at_forward: bool, on_holder_tx: bool) {
9147 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat` policy.
9149 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9150 // trimmed-to-dust HTLC outbound balance and this new payment as included on next counterparty
9151 // commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the update.
9152 // At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC inbound
9153 // and trimmed-to-dust HTLC outbound balance and this new received HTLC as included on next
9154 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail the update.
9155 // Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel might be
9156 // available again for HTLC processing once the dust bandwidth has cleared up.
9158 let chanmon_cfgs = create_chanmon_cfgs(2);
9159 let mut config = test_default_channel_config();
9160 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9161 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9162 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(config)]);
9163 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9165 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9166 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9167 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9168 open_channel.max_accepted_htlcs = 60;
9169 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9170 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9172 accept_channel.dust_limit_satoshis = 660;
9174 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9176 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9179 if let Some(mut chan) = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9180 chan.holder_dust_limit_satoshis = 660;
9184 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9185 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()));
9186 check_added_monitors!(nodes[1], 1);
9188 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()));
9189 check_added_monitors!(nodes[0], 1);
9191 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9192 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9193 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9196 if dust_outbound_balance {
9198 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 2_300_000);
9199 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9203 route_payment(&nodes[0], &[&nodes[1]], 2_300_000);
9207 if dust_outbound_balance {
9209 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
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]], 200_000); // + 167_000 msat of HTLC-timeout tx at 253 sats/kWU
9220 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 });
9221 let mut config = UserConfig::default();
9223 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)));
9225 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)));
9228 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 });
9229 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9230 check_added_monitors!(nodes[0], 1);
9231 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9232 assert_eq!(events.len(), 1);
9233 let payment_event = SendEvent::from_event(events.remove(0));
9234 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9236 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);
9238 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);
9242 let _ = nodes[1].node.get_and_clear_pending_msg_events();
9243 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9244 added_monitors.clear();
9248 fn test_max_dust_htlc_exposure() {
9249 do_test_max_dust_htlc_exposure(true, true, true);
9250 do_test_max_dust_htlc_exposure(false, true, true);
9251 do_test_max_dust_htlc_exposure(false, false, true);
9252 do_test_max_dust_htlc_exposure(false, false, false);
9253 do_test_max_dust_htlc_exposure(true, true, false);
9254 do_test_max_dust_htlc_exposure(true, false, false);
9255 do_test_max_dust_htlc_exposure(true, false, true);
9256 do_test_max_dust_htlc_exposure(false, true, false);