1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::BaseSign;
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::HTLC_SUCCESS_TX_WEIGHT;
26 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_route};
27 use routing::network_graph::{NetworkUpdate, RoutingFees};
28 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
30 use ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
31 use util::enforcing_trait_impls::EnforcingSigner;
32 use util::{byte_utils, test_utils};
33 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider, PaymentPurpose, ClosureReason};
34 use util::errors::APIError;
35 use util::ser::{Writeable, ReadableArgs};
36 use util::config::UserConfig;
38 use bitcoin::hash_types::{Txid, BlockHash};
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
45 use bitcoin::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::Hash;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use sync::{Arc, Mutex};
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
63 fn test_insane_channel_opens() {
64 // Stand up a network of 2 nodes
65 let chanmon_cfgs = create_chanmon_cfgs(2);
66 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
67 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
68 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
70 // Instantiate channel parameters where we push the maximum msats given our
72 let channel_value_sat = 31337; // same as funding satoshis
73 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
74 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
76 // Have node0 initiate a channel to node1 with aforementioned parameters
77 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
79 // Extract the channel open message from node0 to node1
80 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
82 // Test helper that asserts we get the correct error string given a mutator
83 // that supposedly makes the channel open message insane
84 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
85 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
86 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
87 assert_eq!(msg_events.len(), 1);
88 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
89 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
91 &ErrorAction::SendErrorMessage { .. } => {
92 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
94 _ => panic!("unexpected event!"),
96 } else { assert!(false); }
99 use ln::channel::MAX_FUNDING_SATOSHIS;
100 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102 // Test all mutations that would make the channel open message insane
103 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
105 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
107 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
109 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
111 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
113 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
115 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
117 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 fn test_async_inbound_update_fee() {
124 let chanmon_cfgs = create_chanmon_cfgs(2);
125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
127 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
128 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
129 let logger = test_utils::TestLogger::new();
132 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
136 // send (1) commitment_signed -.
137 // <- update_add_htlc/commitment_signed
138 // send (2) RAA (awaiting remote revoke) -.
139 // (1) commitment_signed is delivered ->
140 // .- send (3) RAA (awaiting remote revoke)
141 // (2) RAA is delivered ->
142 // .- send (4) commitment_signed
143 // <- (3) RAA is delivered
144 // send (5) commitment_signed -.
145 // <- (4) commitment_signed is delivered
147 // (5) commitment_signed is delivered ->
149 // (6) RAA is delivered ->
151 // First nodes[0] generates an update_fee
153 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
156 nodes[0].node.timer_tick_occurred();
157 check_added_monitors!(nodes[0], 1);
159 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
160 assert_eq!(events_0.len(), 1);
161 let (update_msg, commitment_signed) = match events_0[0] { // (1)
162 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
163 (update_fee.as_ref(), commitment_signed)
165 _ => panic!("Unexpected event"),
168 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
170 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
171 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
172 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
173 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &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();
174 check_added_monitors!(nodes[1], 1);
176 let payment_event = {
177 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
178 assert_eq!(events_1.len(), 1);
179 SendEvent::from_event(events_1.remove(0))
181 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
182 assert_eq!(payment_event.msgs.len(), 1);
184 // ...now when the messages get delivered everyone should be happy
185 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
186 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
187 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
188 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
189 check_added_monitors!(nodes[0], 1);
191 // deliver(1), generate (3):
192 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
193 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
194 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
195 check_added_monitors!(nodes[1], 1);
197 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
198 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
199 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
202 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
203 assert!(bs_update.update_fee.is_none()); // (4)
204 check_added_monitors!(nodes[1], 1);
206 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
207 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
208 assert!(as_update.update_add_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
211 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
212 assert!(as_update.update_fee.is_none()); // (5)
213 check_added_monitors!(nodes[0], 1);
215 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
216 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
217 // only (6) so get_event_msg's assert(len == 1) passes
218 check_added_monitors!(nodes[0], 1);
220 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
221 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
222 check_added_monitors!(nodes[1], 1);
224 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
225 check_added_monitors!(nodes[0], 1);
227 let events_2 = nodes[0].node.get_and_clear_pending_events();
228 assert_eq!(events_2.len(), 1);
230 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
231 _ => panic!("Unexpected event"),
234 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
235 check_added_monitors!(nodes[1], 1);
239 fn test_update_fee_unordered_raa() {
240 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
241 // crash in an earlier version of the update_fee patch)
242 let chanmon_cfgs = create_chanmon_cfgs(2);
243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
245 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
246 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247 let logger = test_utils::TestLogger::new();
250 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
252 // First nodes[0] generates an update_fee
254 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
257 nodes[0].node.timer_tick_occurred();
258 check_added_monitors!(nodes[0], 1);
260 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
261 assert_eq!(events_0.len(), 1);
262 let update_msg = match events_0[0] { // (1)
263 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
266 _ => panic!("Unexpected event"),
269 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
271 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
272 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
273 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
274 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &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();
275 check_added_monitors!(nodes[1], 1);
277 let payment_event = {
278 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
279 assert_eq!(events_1.len(), 1);
280 SendEvent::from_event(events_1.remove(0))
282 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
283 assert_eq!(payment_event.msgs.len(), 1);
285 // ...now when the messages get delivered everyone should be happy
286 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
288 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
289 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
290 check_added_monitors!(nodes[0], 1);
292 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
293 check_added_monitors!(nodes[1], 1);
295 // We can't continue, sadly, because our (1) now has a bogus signature
299 fn test_multi_flight_update_fee() {
300 let chanmon_cfgs = create_chanmon_cfgs(2);
301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
303 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
304 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
307 // update_fee/commitment_signed ->
308 // .- send (1) RAA and (2) commitment_signed
309 // update_fee (never committed) ->
311 // We have to manually generate the above update_fee, it is allowed by the protocol but we
312 // don't track which updates correspond to which revoke_and_ack responses so we're in
313 // AwaitingRAA mode and will not generate the update_fee yet.
314 // <- (1) RAA delivered
315 // (3) is generated and send (4) CS -.
316 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
317 // know the per_commitment_point to use for it.
318 // <- (2) commitment_signed delivered
320 // B should send no response here
321 // (4) commitment_signed delivered ->
322 // <- RAA/commitment_signed delivered
325 // First nodes[0] generates an update_fee
328 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
329 initial_feerate = *feerate_lock;
330 *feerate_lock = initial_feerate + 20;
332 nodes[0].node.timer_tick_occurred();
333 check_added_monitors!(nodes[0], 1);
335 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
336 assert_eq!(events_0.len(), 1);
337 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
338 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
339 (update_fee.as_ref().unwrap(), commitment_signed)
341 _ => panic!("Unexpected event"),
344 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
345 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
346 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
347 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
348 check_added_monitors!(nodes[1], 1);
350 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
353 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
354 *feerate_lock = initial_feerate + 40;
356 nodes[0].node.timer_tick_occurred();
357 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
358 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
360 // Create the (3) update_fee message that nodes[0] will generate before it does...
361 let mut update_msg_2 = msgs::UpdateFee {
362 channel_id: update_msg_1.channel_id.clone(),
363 feerate_per_kw: (initial_feerate + 30) as u32,
366 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
368 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
370 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
372 // Deliver (1), generating (3) and (4)
373 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
374 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
375 check_added_monitors!(nodes[0], 1);
376 assert!(as_second_update.update_add_htlcs.is_empty());
377 assert!(as_second_update.update_fulfill_htlcs.is_empty());
378 assert!(as_second_update.update_fail_htlcs.is_empty());
379 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
380 // Check that the update_fee newly generated matches what we delivered:
381 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
382 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
384 // Deliver (2) commitment_signed
385 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
386 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
387 check_added_monitors!(nodes[0], 1);
388 // No commitment_signed so get_event_msg's assert(len == 1) passes
390 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
391 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
392 check_added_monitors!(nodes[1], 1);
395 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
396 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
397 check_added_monitors!(nodes[1], 1);
399 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
400 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
401 check_added_monitors!(nodes[0], 1);
403 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
404 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
405 // No commitment_signed so get_event_msg's assert(len == 1) passes
406 check_added_monitors!(nodes[0], 1);
408 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
409 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
410 check_added_monitors!(nodes[1], 1);
413 fn do_test_1_conf_open(connect_style: ConnectStyle) {
414 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
415 // tests that we properly send one in that case.
416 let mut alice_config = UserConfig::default();
417 alice_config.own_channel_config.minimum_depth = 1;
418 alice_config.channel_options.announced_channel = true;
419 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
420 let mut bob_config = UserConfig::default();
421 bob_config.own_channel_config.minimum_depth = 1;
422 bob_config.channel_options.announced_channel = true;
423 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
424 let chanmon_cfgs = create_chanmon_cfgs(2);
425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
427 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
428 *nodes[0].connect_style.borrow_mut() = connect_style;
430 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
431 mine_transaction(&nodes[1], &tx);
432 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()));
434 mine_transaction(&nodes[0], &tx);
435 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
436 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
439 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
440 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
441 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
445 fn test_1_conf_open() {
446 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
447 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
448 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
451 fn do_test_sanity_on_in_flight_opens(steps: u8) {
452 // Previously, we had issues deserializing channels when we hadn't connected the first block
453 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
454 // serialization round-trips and simply do steps towards opening a channel and then drop the
457 let chanmon_cfgs = create_chanmon_cfgs(2);
458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
460 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
462 if steps & 0b1000_0000 != 0{
464 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
467 connect_block(&nodes[0], &block);
468 connect_block(&nodes[1], &block);
471 if steps & 0x0f == 0 { return; }
472 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
473 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
475 if steps & 0x0f == 1 { return; }
476 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
477 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
479 if steps & 0x0f == 2 { return; }
480 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
482 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
484 if steps & 0x0f == 3 { return; }
485 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
486 check_added_monitors!(nodes[0], 0);
487 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
489 if steps & 0x0f == 4 { return; }
490 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
492 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
493 assert_eq!(added_monitors.len(), 1);
494 assert_eq!(added_monitors[0].0, funding_output);
495 added_monitors.clear();
497 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
499 if steps & 0x0f == 5 { return; }
500 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
502 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
503 assert_eq!(added_monitors.len(), 1);
504 assert_eq!(added_monitors[0].0, funding_output);
505 added_monitors.clear();
508 let events_4 = nodes[0].node.get_and_clear_pending_events();
509 assert_eq!(events_4.len(), 0);
511 if steps & 0x0f == 6 { return; }
512 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
514 if steps & 0x0f == 7 { return; }
515 confirm_transaction_at(&nodes[0], &tx, 2);
516 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
517 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
521 fn test_sanity_on_in_flight_opens() {
522 do_test_sanity_on_in_flight_opens(0);
523 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(1);
525 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(2);
527 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
528 do_test_sanity_on_in_flight_opens(3);
529 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
530 do_test_sanity_on_in_flight_opens(4);
531 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
532 do_test_sanity_on_in_flight_opens(5);
533 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
534 do_test_sanity_on_in_flight_opens(6);
535 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
536 do_test_sanity_on_in_flight_opens(7);
537 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
538 do_test_sanity_on_in_flight_opens(8);
539 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
543 fn test_update_fee_vanilla() {
544 let chanmon_cfgs = create_chanmon_cfgs(2);
545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
548 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
551 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
554 nodes[0].node.timer_tick_occurred();
555 check_added_monitors!(nodes[0], 1);
557 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
558 assert_eq!(events_0.len(), 1);
559 let (update_msg, commitment_signed) = match events_0[0] {
560 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 } } => {
561 (update_fee.as_ref(), commitment_signed)
563 _ => panic!("Unexpected event"),
565 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
567 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
568 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
569 check_added_monitors!(nodes[1], 1);
571 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
572 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
573 check_added_monitors!(nodes[0], 1);
575 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
576 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
577 // No commitment_signed so get_event_msg's assert(len == 1) passes
578 check_added_monitors!(nodes[0], 1);
580 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
581 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
582 check_added_monitors!(nodes[1], 1);
586 fn test_update_fee_that_funder_cannot_afford() {
587 let chanmon_cfgs = create_chanmon_cfgs(2);
588 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
589 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
590 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
591 let channel_value = 1888;
592 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
593 let channel_id = chan.2;
597 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
598 *feerate_lock = feerate;
600 nodes[0].node.timer_tick_occurred();
601 check_added_monitors!(nodes[0], 1);
602 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
604 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
606 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
608 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
609 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
611 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
613 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
614 let num_htlcs = commitment_tx.output.len() - 2;
615 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
616 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
617 actual_fee = channel_value - actual_fee;
618 assert_eq!(total_fee, actual_fee);
621 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
622 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
624 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
625 *feerate_lock = feerate + 2;
627 nodes[0].node.timer_tick_occurred();
628 check_added_monitors!(nodes[0], 1);
630 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
632 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
634 //While producing the commitment_signed response after handling a received update_fee request the
635 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
636 //Should produce and error.
637 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
638 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
639 check_added_monitors!(nodes[1], 1);
640 check_closed_broadcast!(nodes[1], true);
641 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
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, &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);
742 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
743 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
747 fn test_update_fee() {
748 let chanmon_cfgs = create_chanmon_cfgs(2);
749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
751 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
752 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
753 let channel_id = chan.2;
756 // (1) update_fee/commitment_signed ->
757 // <- (2) revoke_and_ack
758 // .- send (3) commitment_signed
759 // (4) update_fee/commitment_signed ->
760 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
761 // <- (3) commitment_signed delivered
762 // send (6) revoke_and_ack -.
763 // <- (5) deliver revoke_and_ack
764 // (6) deliver revoke_and_ack ->
765 // .- send (7) commitment_signed in response to (4)
766 // <- (7) deliver commitment_signed
769 // Create and deliver (1)...
772 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
773 feerate = *feerate_lock;
774 *feerate_lock = feerate + 20;
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 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 } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
789 // Generate (2) and (3):
790 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
791 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
792 check_added_monitors!(nodes[1], 1);
795 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797 check_added_monitors!(nodes[0], 1);
799 // Create and deliver (4)...
801 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
802 *feerate_lock = feerate + 30;
804 nodes[0].node.timer_tick_occurred();
805 check_added_monitors!(nodes[0], 1);
806 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
807 assert_eq!(events_0.len(), 1);
808 let (update_msg, commitment_signed) = match events_0[0] {
809 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 } } => {
810 (update_fee.as_ref(), commitment_signed)
812 _ => panic!("Unexpected event"),
815 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
816 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
817 check_added_monitors!(nodes[1], 1);
819 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
820 // No commitment_signed so get_event_msg's assert(len == 1) passes
822 // Handle (3), creating (6):
823 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
824 check_added_monitors!(nodes[0], 1);
825 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
826 // No commitment_signed so get_event_msg's assert(len == 1) passes
829 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
830 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
831 check_added_monitors!(nodes[0], 1);
833 // Deliver (6), creating (7):
834 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
835 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836 assert!(commitment_update.update_add_htlcs.is_empty());
837 assert!(commitment_update.update_fulfill_htlcs.is_empty());
838 assert!(commitment_update.update_fail_htlcs.is_empty());
839 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
840 assert!(commitment_update.update_fee.is_none());
841 check_added_monitors!(nodes[1], 1);
844 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
845 check_added_monitors!(nodes[0], 1);
846 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
847 // No commitment_signed so get_event_msg's assert(len == 1) passes
849 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
850 check_added_monitors!(nodes[1], 1);
851 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
853 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
854 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
855 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
856 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
857 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
861 fn fake_network_test() {
862 // Simple test which builds a network of ChannelManagers, connects them to each other, and
863 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
864 let chanmon_cfgs = create_chanmon_cfgs(4);
865 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
866 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
867 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
869 // Create some initial channels
870 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
871 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
872 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
874 // Rebalance the network a bit by relaying one payment through all the channels...
875 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
876 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
877 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
878 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
880 // Send some more payments
881 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
882 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
883 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
885 // Test failure packets
886 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
887 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
889 // Add a new channel that skips 3
890 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
892 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
893 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
894 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
895 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
896 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
897 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
898 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
900 // Do some rebalance loop payments, simultaneously
901 let mut hops = Vec::with_capacity(3);
903 pubkey: nodes[2].node.get_our_node_id(),
904 node_features: NodeFeatures::empty(),
905 short_channel_id: chan_2.0.contents.short_channel_id,
906 channel_features: ChannelFeatures::empty(),
908 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
911 pubkey: nodes[3].node.get_our_node_id(),
912 node_features: NodeFeatures::empty(),
913 short_channel_id: chan_3.0.contents.short_channel_id,
914 channel_features: ChannelFeatures::empty(),
916 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
919 pubkey: nodes[1].node.get_our_node_id(),
920 node_features: NodeFeatures::known(),
921 short_channel_id: chan_4.0.contents.short_channel_id,
922 channel_features: ChannelFeatures::known(),
924 cltv_expiry_delta: TEST_FINAL_CLTV,
926 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;
927 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;
928 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
930 let mut hops = Vec::with_capacity(3);
932 pubkey: nodes[3].node.get_our_node_id(),
933 node_features: NodeFeatures::empty(),
934 short_channel_id: chan_4.0.contents.short_channel_id,
935 channel_features: ChannelFeatures::empty(),
937 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
940 pubkey: nodes[2].node.get_our_node_id(),
941 node_features: NodeFeatures::empty(),
942 short_channel_id: chan_3.0.contents.short_channel_id,
943 channel_features: ChannelFeatures::empty(),
945 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
948 pubkey: nodes[1].node.get_our_node_id(),
949 node_features: NodeFeatures::known(),
950 short_channel_id: chan_2.0.contents.short_channel_id,
951 channel_features: ChannelFeatures::known(),
953 cltv_expiry_delta: TEST_FINAL_CLTV,
955 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;
956 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;
957 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
959 // Claim the rebalances...
960 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
961 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
963 // Add a duplicate new channel from 2 to 4
964 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
966 // Send some payments across both channels
967 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
968 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
969 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
972 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
973 let events = nodes[0].node.get_and_clear_pending_msg_events();
974 assert_eq!(events.len(), 0);
975 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);
977 //TODO: Test that routes work again here as we've been notified that the channel is full
979 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
980 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
981 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
983 // Close down the channels...
984 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
985 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
986 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
987 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
988 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
989 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
990 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
991 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
992 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
993 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
994 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
995 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
996 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
997 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
998 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1002 fn holding_cell_htlc_counting() {
1003 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1004 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1005 // commitment dance rounds.
1006 let chanmon_cfgs = create_chanmon_cfgs(3);
1007 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1008 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1009 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1010 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1011 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1012 let logger = test_utils::TestLogger::new();
1014 let mut payments = Vec::new();
1015 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1016 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
1017 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1018 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1019 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1020 payments.push((payment_preimage, payment_hash));
1022 check_added_monitors!(nodes[1], 1);
1024 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1025 assert_eq!(events.len(), 1);
1026 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1027 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1029 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1030 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1032 let (_, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[2]);
1034 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1035 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1036 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1037 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1038 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1039 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1042 // This should also be true if we try to forward a payment.
1043 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[2]);
1045 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1046 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1047 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1048 check_added_monitors!(nodes[0], 1);
1051 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1052 assert_eq!(events.len(), 1);
1053 let payment_event = SendEvent::from_event(events.pop().unwrap());
1054 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1056 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1057 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1058 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1059 // fails), the second will process the resulting failure and fail the HTLC backward.
1060 expect_pending_htlcs_forwardable!(nodes[1]);
1061 expect_pending_htlcs_forwardable!(nodes[1]);
1062 check_added_monitors!(nodes[1], 1);
1064 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1066 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1068 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1070 // Now forward all the pending HTLCs and claim them back
1071 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1072 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1073 check_added_monitors!(nodes[2], 1);
1075 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1076 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1077 check_added_monitors!(nodes[1], 1);
1078 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1080 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1081 check_added_monitors!(nodes[1], 1);
1082 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1084 for ref update in as_updates.update_add_htlcs.iter() {
1085 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1087 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1088 check_added_monitors!(nodes[2], 1);
1089 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1090 check_added_monitors!(nodes[2], 1);
1091 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1093 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1094 check_added_monitors!(nodes[1], 1);
1095 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1096 check_added_monitors!(nodes[1], 1);
1097 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1099 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1100 check_added_monitors!(nodes[2], 1);
1102 expect_pending_htlcs_forwardable!(nodes[2]);
1104 let events = nodes[2].node.get_and_clear_pending_events();
1105 assert_eq!(events.len(), payments.len());
1106 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1108 &Event::PaymentReceived { ref payment_hash, .. } => {
1109 assert_eq!(*payment_hash, *hash);
1111 _ => panic!("Unexpected event"),
1115 for (preimage, _) in payments.drain(..) {
1116 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1119 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1123 fn duplicate_htlc_test() {
1124 // Test that we accept duplicate payment_hash HTLCs across the network and that
1125 // claiming/failing them are all separate and don't affect each other
1126 let chanmon_cfgs = create_chanmon_cfgs(6);
1127 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1128 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1129 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1131 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1132 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1133 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1134 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1135 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1136 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1138 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1140 *nodes[0].network_payment_count.borrow_mut() -= 1;
1141 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1143 *nodes[0].network_payment_count.borrow_mut() -= 1;
1144 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1146 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1147 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1148 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1152 fn test_duplicate_htlc_different_direction_onchain() {
1153 // Test that ChannelMonitor doesn't generate 2 preimage txn
1154 // when we have 2 HTLCs with same preimage that go across a node
1155 // in opposite directions, even with the same payment secret.
1156 let chanmon_cfgs = create_chanmon_cfgs(2);
1157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1159 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1161 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1162 let logger = test_utils::TestLogger::new();
1165 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1167 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1169 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1170 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1171 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1172 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1174 // Provide preimage to node 0 by claiming payment
1175 nodes[0].node.claim_funds(payment_preimage);
1176 check_added_monitors!(nodes[0], 1);
1178 // Broadcast node 1 commitment txn
1179 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1181 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1182 let mut has_both_htlcs = 0; // check htlcs match ones committed
1183 for outp in remote_txn[0].output.iter() {
1184 if outp.value == 800_000 / 1000 {
1185 has_both_htlcs += 1;
1186 } else if outp.value == 900_000 / 1000 {
1187 has_both_htlcs += 1;
1190 assert_eq!(has_both_htlcs, 2);
1192 mine_transaction(&nodes[0], &remote_txn[0]);
1193 check_added_monitors!(nodes[0], 1);
1194 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1195 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1197 // Check we only broadcast 1 timeout tx
1198 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1199 assert_eq!(claim_txn.len(), 8);
1200 assert_eq!(claim_txn[1], claim_txn[4]);
1201 assert_eq!(claim_txn[2], claim_txn[5]);
1202 check_spends!(claim_txn[1], chan_1.3);
1203 check_spends!(claim_txn[2], claim_txn[1]);
1204 check_spends!(claim_txn[7], claim_txn[1]);
1206 assert_eq!(claim_txn[0].input.len(), 1);
1207 assert_eq!(claim_txn[3].input.len(), 1);
1208 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1210 assert_eq!(claim_txn[0].input.len(), 1);
1211 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1212 check_spends!(claim_txn[0], remote_txn[0]);
1213 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1214 assert_eq!(claim_txn[6].input.len(), 1);
1215 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1216 check_spends!(claim_txn[6], remote_txn[0]);
1217 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1219 let events = nodes[0].node.get_and_clear_pending_msg_events();
1220 assert_eq!(events.len(), 3);
1223 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1224 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1225 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1226 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1228 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, .. } } => {
1229 assert!(update_add_htlcs.is_empty());
1230 assert!(update_fail_htlcs.is_empty());
1231 assert_eq!(update_fulfill_htlcs.len(), 1);
1232 assert!(update_fail_malformed_htlcs.is_empty());
1233 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1235 _ => panic!("Unexpected event"),
1241 fn test_basic_channel_reserve() {
1242 let chanmon_cfgs = create_chanmon_cfgs(2);
1243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1245 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1246 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1247 let logger = test_utils::TestLogger::new();
1249 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1250 let channel_reserve = chan_stat.channel_reserve_msat;
1252 // The 2* and +1 are for the fee spike reserve.
1253 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
1254 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1255 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1256 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1257 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1258 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1260 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1262 &APIError::ChannelUnavailable{ref err} =>
1263 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1264 _ => panic!("Unexpected error variant"),
1267 _ => panic!("Unexpected error variant"),
1269 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1270 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);
1272 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1276 fn test_fee_spike_violation_fails_htlc() {
1277 let chanmon_cfgs = create_chanmon_cfgs(2);
1278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1280 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1281 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1283 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1284 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1285 let secp_ctx = Secp256k1::new();
1286 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1288 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1290 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1291 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1292 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1293 let msg = msgs::UpdateAddHTLC {
1296 amount_msat: htlc_msat,
1297 payment_hash: payment_hash,
1298 cltv_expiry: htlc_cltv,
1299 onion_routing_packet: onion_packet,
1302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1304 // Now manually create the commitment_signed message corresponding to the update_add
1305 // nodes[0] just sent. In the code for construction of this message, "local" refers
1306 // to the sender of the message, and "remote" refers to the receiver.
1308 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1310 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1312 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1313 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1314 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1315 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1316 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1317 let chan_signer = local_chan.get_signer();
1318 // Make the signer believe we validated another commitment, so we can release the secret
1319 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1321 let pubkeys = chan_signer.pubkeys();
1322 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1323 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1324 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1325 chan_signer.pubkeys().funding_pubkey)
1327 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1328 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1329 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1330 let chan_signer = remote_chan.get_signer();
1331 let pubkeys = chan_signer.pubkeys();
1332 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1333 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1334 chan_signer.pubkeys().funding_pubkey)
1337 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1338 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1339 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1341 // Build the remote commitment transaction so we can sign it, and then later use the
1342 // signature for the commitment_signed message.
1343 let local_chan_balance = 1313;
1345 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1347 amount_msat: 3460001,
1348 cltv_expiry: htlc_cltv,
1350 transaction_output_index: Some(1),
1353 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1356 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1357 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1358 let local_chan_signer = local_chan.get_signer();
1359 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1363 false, local_funding, remote_funding,
1364 commit_tx_keys.clone(),
1366 &mut vec![(accepted_htlc_info, ())],
1367 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1369 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1372 let commit_signed_msg = msgs::CommitmentSigned {
1375 htlc_signatures: res.1
1378 // Send the commitment_signed message to the nodes[1].
1379 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1380 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1382 // Send the RAA to nodes[1].
1383 let raa_msg = msgs::RevokeAndACK {
1385 per_commitment_secret: local_secret,
1386 next_per_commitment_point: next_local_point
1388 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1390 let events = nodes[1].node.get_and_clear_pending_msg_events();
1391 assert_eq!(events.len(), 1);
1392 // Make sure the HTLC failed in the way we expect.
1394 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1395 assert_eq!(update_fail_htlcs.len(), 1);
1396 update_fail_htlcs[0].clone()
1398 _ => panic!("Unexpected event"),
1400 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1401 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1403 check_added_monitors!(nodes[1], 2);
1407 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1408 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1409 // Set the fee rate for the channel very high, to the point where the fundee
1410 // sending any above-dust amount would result in a channel reserve violation.
1411 // In this test we check that we would be prevented from sending an HTLC in
1413 let feerate_per_kw = 253;
1414 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1415 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1418 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1420 let mut push_amt = 100_000_000;
1421 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1422 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1424 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1426 // Sending exactly enough to hit the reserve amount should be accepted
1427 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1429 // However one more HTLC should be significantly over the reserve amount and fail.
1430 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1431 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1432 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1433 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1434 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);
1438 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1439 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1440 // Set the fee rate for the channel very high, to the point where the funder
1441 // receiving 1 update_add_htlc would result in them closing the channel due
1442 // to channel reserve violation. This close could also happen if the fee went
1443 // up a more realistic amount, but many HTLCs were outstanding at the time of
1444 // the update_add_htlc.
1445 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1446 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1447 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1449 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1450 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1452 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1453 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1454 let secp_ctx = Secp256k1::new();
1455 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1456 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1457 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1458 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1459 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1460 let msg = msgs::UpdateAddHTLC {
1463 amount_msat: htlc_msat + 1,
1464 payment_hash: payment_hash,
1465 cltv_expiry: htlc_cltv,
1466 onion_routing_packet: onion_packet,
1469 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1470 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1471 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);
1472 assert_eq!(nodes[0].node.list_channels().len(), 0);
1473 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1474 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1475 check_added_monitors!(nodes[0], 1);
1476 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1480 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1481 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1482 // calculating our commitment transaction fee (this was previously broken).
1483 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1484 let feerate_per_kw = 253;
1485 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1486 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1490 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1492 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1493 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1494 // transaction fee with 0 HTLCs (183 sats)).
1495 let mut push_amt = 100_000_000;
1496 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1497 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1498 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1500 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1501 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1502 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1503 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1504 // commitment transaction fee.
1505 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1507 // One more than the dust amt should fail, however.
1508 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1509 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1510 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1514 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1515 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1516 // calculating our counterparty's commitment transaction fee (this was previously broken).
1517 let chanmon_cfgs = create_chanmon_cfgs(2);
1518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1520 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1523 let payment_amt = 46000; // Dust amount
1524 // In the previous code, these first four payments would succeed.
1525 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1526 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1527 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1528 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1530 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1531 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1532 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1533 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1534 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1535 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1537 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1538 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1539 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1540 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1544 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1545 let chanmon_cfgs = create_chanmon_cfgs(3);
1546 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1547 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1548 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1549 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1550 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1553 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1554 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1555 let feerate = get_feerate!(nodes[0], chan.2);
1557 // Add a 2* and +1 for the fee spike reserve.
1558 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1559 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;
1560 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1562 // Add a pending HTLC.
1563 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1564 let payment_event_1 = {
1565 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1566 check_added_monitors!(nodes[0], 1);
1568 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1569 assert_eq!(events.len(), 1);
1570 SendEvent::from_event(events.remove(0))
1572 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1574 // Attempt to trigger a channel reserve violation --> payment failure.
1575 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1576 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;
1577 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1578 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1580 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1581 let secp_ctx = Secp256k1::new();
1582 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1583 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1584 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1585 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1586 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1587 let msg = msgs::UpdateAddHTLC {
1590 amount_msat: htlc_msat + 1,
1591 payment_hash: our_payment_hash_1,
1592 cltv_expiry: htlc_cltv,
1593 onion_routing_packet: onion_packet,
1596 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1597 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1598 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1599 assert_eq!(nodes[1].node.list_channels().len(), 1);
1600 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1601 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1602 check_added_monitors!(nodes[1], 1);
1603 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1607 fn test_inbound_outbound_capacity_is_not_zero() {
1608 let chanmon_cfgs = create_chanmon_cfgs(2);
1609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1612 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1613 let channels0 = node_chanmgrs[0].list_channels();
1614 let channels1 = node_chanmgrs[1].list_channels();
1615 assert_eq!(channels0.len(), 1);
1616 assert_eq!(channels1.len(), 1);
1618 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1619 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1620 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1622 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1623 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1626 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1627 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1631 fn test_channel_reserve_holding_cell_htlcs() {
1632 let chanmon_cfgs = create_chanmon_cfgs(3);
1633 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1634 // When this test was written, the default base fee floated based on the HTLC count.
1635 // It is now fixed, so we simply set the fee to the expected value here.
1636 let mut config = test_default_channel_config();
1637 config.channel_options.forwarding_fee_base_msat = 239;
1638 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1639 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1640 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1641 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1643 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1644 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1646 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1647 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1649 macro_rules! expect_forward {
1651 let mut events = $node.node.get_and_clear_pending_msg_events();
1652 assert_eq!(events.len(), 1);
1653 check_added_monitors!($node, 1);
1654 let payment_event = SendEvent::from_event(events.remove(0));
1659 let feemsat = 239; // set above
1660 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1661 let feerate = get_feerate!(nodes[0], chan_1.2);
1663 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1665 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1667 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1668 route.paths[0].last_mut().unwrap().fee_msat += 1;
1669 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1670 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1671 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)));
1672 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1673 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);
1676 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1677 // nodes[0]'s wealth
1679 let amt_msat = recv_value_0 + total_fee_msat;
1680 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1681 // Also, ensure that each payment has enough to be over the dust limit to
1682 // ensure it'll be included in each commit tx fee calculation.
1683 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1684 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1685 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1688 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1690 let (stat01_, stat11_, stat12_, stat22_) = (
1691 get_channel_value_stat!(nodes[0], chan_1.2),
1692 get_channel_value_stat!(nodes[1], chan_1.2),
1693 get_channel_value_stat!(nodes[1], chan_2.2),
1694 get_channel_value_stat!(nodes[2], chan_2.2),
1697 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1698 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1699 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1700 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1701 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1704 // adding pending output.
1705 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1706 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1707 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1708 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1709 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1710 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1711 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1712 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1713 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1715 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1716 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1717 let amt_msat_1 = recv_value_1 + total_fee_msat;
1719 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);
1720 let payment_event_1 = {
1721 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1722 check_added_monitors!(nodes[0], 1);
1724 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1725 assert_eq!(events.len(), 1);
1726 SendEvent::from_event(events.remove(0))
1728 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1730 // channel reserve test with htlc pending output > 0
1731 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1733 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1734 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1735 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1736 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1739 // split the rest to test holding cell
1740 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1741 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1742 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1743 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1745 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1746 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);
1749 // now see if they go through on both sides
1750 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);
1751 // but this will stuck in the holding cell
1752 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1753 check_added_monitors!(nodes[0], 0);
1754 let events = nodes[0].node.get_and_clear_pending_events();
1755 assert_eq!(events.len(), 0);
1757 // test with outbound holding cell amount > 0
1759 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1760 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1761 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1762 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1763 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);
1766 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);
1767 // this will also stuck in the holding cell
1768 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1769 check_added_monitors!(nodes[0], 0);
1770 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1771 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1773 // flush the pending htlc
1774 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1775 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1776 check_added_monitors!(nodes[1], 1);
1778 // the pending htlc should be promoted to committed
1779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1780 check_added_monitors!(nodes[0], 1);
1781 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1783 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1784 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1785 // No commitment_signed so get_event_msg's assert(len == 1) passes
1786 check_added_monitors!(nodes[0], 1);
1788 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1789 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1790 check_added_monitors!(nodes[1], 1);
1792 expect_pending_htlcs_forwardable!(nodes[1]);
1794 let ref payment_event_11 = expect_forward!(nodes[1]);
1795 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1796 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1798 expect_pending_htlcs_forwardable!(nodes[2]);
1799 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1801 // flush the htlcs in the holding cell
1802 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1803 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1804 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1805 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1806 expect_pending_htlcs_forwardable!(nodes[1]);
1808 let ref payment_event_3 = expect_forward!(nodes[1]);
1809 assert_eq!(payment_event_3.msgs.len(), 2);
1810 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1811 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1813 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1814 expect_pending_htlcs_forwardable!(nodes[2]);
1816 let events = nodes[2].node.get_and_clear_pending_events();
1817 assert_eq!(events.len(), 2);
1819 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1820 assert_eq!(our_payment_hash_21, *payment_hash);
1821 assert_eq!(recv_value_21, amt);
1823 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1824 assert!(payment_preimage.is_none());
1825 assert_eq!(our_payment_secret_21, *payment_secret);
1827 _ => panic!("expected PaymentPurpose::InvoicePayment")
1830 _ => panic!("Unexpected event"),
1833 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1834 assert_eq!(our_payment_hash_22, *payment_hash);
1835 assert_eq!(recv_value_22, amt);
1837 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1838 assert!(payment_preimage.is_none());
1839 assert_eq!(our_payment_secret_22, *payment_secret);
1841 _ => panic!("expected PaymentPurpose::InvoicePayment")
1844 _ => panic!("Unexpected event"),
1847 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1848 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1849 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1851 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1852 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1853 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1855 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1856 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);
1857 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1858 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1859 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1861 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1862 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1866 fn channel_reserve_in_flight_removes() {
1867 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1868 // can send to its counterparty, but due to update ordering, the other side may not yet have
1869 // considered those HTLCs fully removed.
1870 // This tests that we don't count HTLCs which will not be included in the next remote
1871 // commitment transaction towards the reserve value (as it implies no commitment transaction
1872 // will be generated which violates the remote reserve value).
1873 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1875 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1876 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1877 // you only consider the value of the first HTLC, it may not),
1878 // * start routing a third HTLC from A to B,
1879 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1880 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1881 // * deliver the first fulfill from B
1882 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1884 // * deliver A's response CS and RAA.
1885 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1886 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1887 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1888 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1889 let chanmon_cfgs = create_chanmon_cfgs(2);
1890 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1891 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1892 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1893 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1894 let logger = test_utils::TestLogger::new();
1896 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1897 // Route the first two HTLCs.
1898 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1899 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1901 // Start routing the third HTLC (this is just used to get everyone in the right state).
1902 let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
1904 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1905 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
1906 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1907 check_added_monitors!(nodes[0], 1);
1908 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1909 assert_eq!(events.len(), 1);
1910 SendEvent::from_event(events.remove(0))
1913 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1914 // initial fulfill/CS.
1915 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1916 check_added_monitors!(nodes[1], 1);
1917 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1919 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1920 // remove the second HTLC when we send the HTLC back from B to A.
1921 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1922 check_added_monitors!(nodes[1], 1);
1923 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1925 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1926 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1927 check_added_monitors!(nodes[0], 1);
1928 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1929 expect_payment_sent!(nodes[0], payment_preimage_1);
1931 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1932 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1933 check_added_monitors!(nodes[1], 1);
1934 // B is already AwaitingRAA, so cant generate a CS here
1935 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1937 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1938 check_added_monitors!(nodes[1], 1);
1939 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1941 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1942 check_added_monitors!(nodes[0], 1);
1943 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1945 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1946 check_added_monitors!(nodes[1], 1);
1947 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1949 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1950 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1951 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1952 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1953 // on-chain as necessary).
1954 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1956 check_added_monitors!(nodes[0], 1);
1957 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1958 expect_payment_sent!(nodes[0], payment_preimage_2);
1960 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1961 check_added_monitors!(nodes[1], 1);
1962 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1964 expect_pending_htlcs_forwardable!(nodes[1]);
1965 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1967 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1968 // resolve the second HTLC from A's point of view.
1969 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1970 check_added_monitors!(nodes[0], 1);
1971 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1973 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1974 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1975 let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
1977 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1978 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
1979 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1980 check_added_monitors!(nodes[1], 1);
1981 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1982 assert_eq!(events.len(), 1);
1983 SendEvent::from_event(events.remove(0))
1986 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1988 check_added_monitors!(nodes[0], 1);
1989 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1991 // Now just resolve all the outstanding messages/HTLCs for completeness...
1993 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1994 check_added_monitors!(nodes[1], 1);
1995 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1997 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1998 check_added_monitors!(nodes[1], 1);
2000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2001 check_added_monitors!(nodes[0], 1);
2002 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2004 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2005 check_added_monitors!(nodes[1], 1);
2006 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2008 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2009 check_added_monitors!(nodes[0], 1);
2011 expect_pending_htlcs_forwardable!(nodes[0]);
2012 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2014 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2015 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2019 fn channel_monitor_network_test() {
2020 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2021 // tests that ChannelMonitor is able to recover from various states.
2022 let chanmon_cfgs = create_chanmon_cfgs(5);
2023 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2024 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2025 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2027 // Create some initial channels
2028 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2030 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2031 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2033 // Make sure all nodes are at the same starting height
2034 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2035 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2036 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2037 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2038 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2040 // Rebalance the network a bit by relaying one payment through all the channels...
2041 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2042 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2043 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2044 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2046 // Simple case with no pending HTLCs:
2047 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2048 check_added_monitors!(nodes[1], 1);
2049 check_closed_broadcast!(nodes[1], false);
2051 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2052 assert_eq!(node_txn.len(), 1);
2053 mine_transaction(&nodes[0], &node_txn[0]);
2054 check_added_monitors!(nodes[0], 1);
2055 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2057 check_closed_broadcast!(nodes[0], true);
2058 assert_eq!(nodes[0].node.list_channels().len(), 0);
2059 assert_eq!(nodes[1].node.list_channels().len(), 1);
2060 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2061 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2063 // One pending HTLC is discarded by the force-close:
2064 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2066 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2067 // broadcasted until we reach the timelock time).
2068 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2069 check_closed_broadcast!(nodes[1], false);
2070 check_added_monitors!(nodes[1], 1);
2072 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2073 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2074 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2075 mine_transaction(&nodes[2], &node_txn[0]);
2076 check_added_monitors!(nodes[2], 1);
2077 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2079 check_closed_broadcast!(nodes[2], true);
2080 assert_eq!(nodes[1].node.list_channels().len(), 0);
2081 assert_eq!(nodes[2].node.list_channels().len(), 1);
2082 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2083 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2085 macro_rules! claim_funds {
2086 ($node: expr, $prev_node: expr, $preimage: expr) => {
2088 assert!($node.node.claim_funds($preimage));
2089 check_added_monitors!($node, 1);
2091 let events = $node.node.get_and_clear_pending_msg_events();
2092 assert_eq!(events.len(), 1);
2094 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2095 assert!(update_add_htlcs.is_empty());
2096 assert!(update_fail_htlcs.is_empty());
2097 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2099 _ => panic!("Unexpected event"),
2105 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2106 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2107 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2108 check_added_monitors!(nodes[2], 1);
2109 check_closed_broadcast!(nodes[2], false);
2110 let node2_commitment_txid;
2112 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2113 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2114 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2115 node2_commitment_txid = node_txn[0].txid();
2117 // Claim the payment on nodes[3], giving it knowledge of the preimage
2118 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2119 mine_transaction(&nodes[3], &node_txn[0]);
2120 check_added_monitors!(nodes[3], 1);
2121 check_preimage_claim(&nodes[3], &node_txn);
2123 check_closed_broadcast!(nodes[3], true);
2124 assert_eq!(nodes[2].node.list_channels().len(), 0);
2125 assert_eq!(nodes[3].node.list_channels().len(), 1);
2126 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2127 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2129 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2130 // confusing us in the following tests.
2131 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2133 // One pending HTLC to time out:
2134 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2135 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2138 let (close_chan_update_1, close_chan_update_2) = {
2139 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2140 let events = nodes[3].node.get_and_clear_pending_msg_events();
2141 assert_eq!(events.len(), 2);
2142 let close_chan_update_1 = match events[0] {
2143 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2146 _ => panic!("Unexpected event"),
2149 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2150 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2152 _ => panic!("Unexpected event"),
2154 check_added_monitors!(nodes[3], 1);
2156 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2158 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2159 node_txn.retain(|tx| {
2160 if tx.input[0].previous_output.txid == node2_commitment_txid {
2166 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2168 // Claim the payment on nodes[4], giving it knowledge of the preimage
2169 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2171 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2172 let events = nodes[4].node.get_and_clear_pending_msg_events();
2173 assert_eq!(events.len(), 2);
2174 let close_chan_update_2 = match events[0] {
2175 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2178 _ => panic!("Unexpected event"),
2181 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2182 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2184 _ => panic!("Unexpected event"),
2186 check_added_monitors!(nodes[4], 1);
2187 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2189 mine_transaction(&nodes[4], &node_txn[0]);
2190 check_preimage_claim(&nodes[4], &node_txn);
2191 (close_chan_update_1, close_chan_update_2)
2193 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2194 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2195 assert_eq!(nodes[3].node.list_channels().len(), 0);
2196 assert_eq!(nodes[4].node.list_channels().len(), 0);
2198 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2199 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2200 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2204 fn test_justice_tx() {
2205 // Test justice txn built on revoked HTLC-Success tx, against both sides
2206 let mut alice_config = UserConfig::default();
2207 alice_config.channel_options.announced_channel = true;
2208 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2209 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2210 let mut bob_config = UserConfig::default();
2211 bob_config.channel_options.announced_channel = true;
2212 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2213 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2214 let user_cfgs = [Some(alice_config), Some(bob_config)];
2215 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2216 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2217 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2218 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2219 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2220 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2221 // Create some new channels:
2222 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2224 // A pending HTLC which will be revoked:
2225 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2226 // Get the will-be-revoked local txn from nodes[0]
2227 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2228 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2229 assert_eq!(revoked_local_txn[0].input.len(), 1);
2230 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2231 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2232 assert_eq!(revoked_local_txn[1].input.len(), 1);
2233 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2234 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2235 // Revoke the old state
2236 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2239 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2241 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2242 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2243 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2245 check_spends!(node_txn[0], revoked_local_txn[0]);
2246 node_txn.swap_remove(0);
2247 node_txn.truncate(1);
2249 check_added_monitors!(nodes[1], 1);
2250 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2251 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2253 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2254 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2255 // Verify broadcast of revoked HTLC-timeout
2256 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2257 check_added_monitors!(nodes[0], 1);
2258 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2259 // Broadcast revoked HTLC-timeout on node 1
2260 mine_transaction(&nodes[1], &node_txn[1]);
2261 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2263 get_announce_close_broadcast_events(&nodes, 0, 1);
2265 assert_eq!(nodes[0].node.list_channels().len(), 0);
2266 assert_eq!(nodes[1].node.list_channels().len(), 0);
2268 // We test justice_tx build by A on B's revoked HTLC-Success tx
2269 // Create some new channels:
2270 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2272 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2276 // A pending HTLC which will be revoked:
2277 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2278 // Get the will-be-revoked local txn from B
2279 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2280 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2281 assert_eq!(revoked_local_txn[0].input.len(), 1);
2282 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2283 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2284 // Revoke the old state
2285 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2287 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2289 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2290 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2291 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2293 check_spends!(node_txn[0], revoked_local_txn[0]);
2294 node_txn.swap_remove(0);
2296 check_added_monitors!(nodes[0], 1);
2297 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2299 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2300 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2301 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2302 check_added_monitors!(nodes[1], 1);
2303 mine_transaction(&nodes[0], &node_txn[1]);
2304 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2305 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2307 get_announce_close_broadcast_events(&nodes, 0, 1);
2308 assert_eq!(nodes[0].node.list_channels().len(), 0);
2309 assert_eq!(nodes[1].node.list_channels().len(), 0);
2313 fn revoked_output_claim() {
2314 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2315 // transaction is broadcast by its counterparty
2316 let chanmon_cfgs = create_chanmon_cfgs(2);
2317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2319 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2320 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2321 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2322 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2323 assert_eq!(revoked_local_txn.len(), 1);
2324 // Only output is the full channel value back to nodes[0]:
2325 assert_eq!(revoked_local_txn[0].output.len(), 1);
2326 // Send a payment through, updating everyone's latest commitment txn
2327 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2329 // Inform nodes[1] that nodes[0] broadcast a stale tx
2330 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2331 check_added_monitors!(nodes[1], 1);
2332 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2333 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2334 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2336 check_spends!(node_txn[0], revoked_local_txn[0]);
2337 check_spends!(node_txn[1], chan_1.3);
2339 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2340 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2341 get_announce_close_broadcast_events(&nodes, 0, 1);
2342 check_added_monitors!(nodes[0], 1);
2343 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2347 fn claim_htlc_outputs_shared_tx() {
2348 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2349 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2350 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2351 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2352 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2353 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2355 // Create some new channel:
2356 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2358 // Rebalance the network to generate htlc in the two directions
2359 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2360 // 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
2361 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2362 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2364 // Get the will-be-revoked local txn from node[0]
2365 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2366 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2367 assert_eq!(revoked_local_txn[0].input.len(), 1);
2368 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2369 assert_eq!(revoked_local_txn[1].input.len(), 1);
2370 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2371 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2372 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2374 //Revoke the old state
2375 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2378 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2379 check_added_monitors!(nodes[0], 1);
2380 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2381 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2382 check_added_monitors!(nodes[1], 1);
2383 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2384 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2385 expect_payment_failed!(nodes[1], payment_hash_2, true);
2387 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2388 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2390 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2391 check_spends!(node_txn[0], revoked_local_txn[0]);
2393 let mut witness_lens = BTreeSet::new();
2394 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2395 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2396 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2397 assert_eq!(witness_lens.len(), 3);
2398 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2399 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2400 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2402 // Next nodes[1] broadcasts its current local tx state:
2403 assert_eq!(node_txn[1].input.len(), 1);
2404 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2406 get_announce_close_broadcast_events(&nodes, 0, 1);
2407 assert_eq!(nodes[0].node.list_channels().len(), 0);
2408 assert_eq!(nodes[1].node.list_channels().len(), 0);
2412 fn claim_htlc_outputs_single_tx() {
2413 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2414 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2415 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2420 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2422 // Rebalance the network to generate htlc in the two directions
2423 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2424 // 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
2425 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2426 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2427 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2429 // Get the will-be-revoked local txn from node[0]
2430 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2432 //Revoke the old state
2433 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2436 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2437 check_added_monitors!(nodes[0], 1);
2438 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2439 check_added_monitors!(nodes[1], 1);
2440 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2441 let mut events = nodes[0].node.get_and_clear_pending_events();
2442 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2444 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2445 _ => panic!("Unexpected event"),
2448 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2449 expect_payment_failed!(nodes[1], payment_hash_2, true);
2451 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2452 assert_eq!(node_txn.len(), 9);
2453 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2454 // ChannelManager: local commmitment + local HTLC-timeout (2)
2455 // 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)
2456 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2458 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2459 assert_eq!(node_txn[0].input.len(), 1);
2460 check_spends!(node_txn[0], chan_1.3);
2461 assert_eq!(node_txn[1].input.len(), 1);
2462 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2463 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2464 check_spends!(node_txn[1], node_txn[0]);
2466 // Justice transactions are indices 1-2-4
2467 assert_eq!(node_txn[2].input.len(), 1);
2468 assert_eq!(node_txn[3].input.len(), 1);
2469 assert_eq!(node_txn[4].input.len(), 1);
2471 check_spends!(node_txn[2], revoked_local_txn[0]);
2472 check_spends!(node_txn[3], revoked_local_txn[0]);
2473 check_spends!(node_txn[4], revoked_local_txn[0]);
2475 let mut witness_lens = BTreeSet::new();
2476 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2477 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2478 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2479 assert_eq!(witness_lens.len(), 3);
2480 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2481 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2482 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2484 get_announce_close_broadcast_events(&nodes, 0, 1);
2485 assert_eq!(nodes[0].node.list_channels().len(), 0);
2486 assert_eq!(nodes[1].node.list_channels().len(), 0);
2490 fn test_htlc_on_chain_success() {
2491 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2492 // the preimage backward accordingly. So here we test that ChannelManager is
2493 // broadcasting the right event to other nodes in payment path.
2494 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2495 // A --------------------> B ----------------------> C (preimage)
2496 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2497 // commitment transaction was broadcast.
2498 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2500 // B should be able to claim via preimage if A then broadcasts its local tx.
2501 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2502 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2503 // PaymentSent event).
2505 let chanmon_cfgs = create_chanmon_cfgs(3);
2506 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2507 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2508 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2510 // Create some initial channels
2511 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2512 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2514 // Ensure all nodes are at the same height
2515 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2516 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2517 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2518 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2520 // Rebalance the network a bit by relaying one payment through all the channels...
2521 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2522 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2524 let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2525 let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2527 // Broadcast legit commitment tx from C on B's chain
2528 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2529 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2530 assert_eq!(commitment_tx.len(), 1);
2531 check_spends!(commitment_tx[0], chan_2.3);
2532 nodes[2].node.claim_funds(our_payment_preimage);
2533 nodes[2].node.claim_funds(our_payment_preimage_2);
2534 check_added_monitors!(nodes[2], 2);
2535 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2536 assert!(updates.update_add_htlcs.is_empty());
2537 assert!(updates.update_fail_htlcs.is_empty());
2538 assert!(updates.update_fail_malformed_htlcs.is_empty());
2539 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2541 mine_transaction(&nodes[2], &commitment_tx[0]);
2542 check_closed_broadcast!(nodes[2], true);
2543 check_added_monitors!(nodes[2], 1);
2544 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2545 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)
2546 assert_eq!(node_txn.len(), 5);
2547 assert_eq!(node_txn[0], node_txn[3]);
2548 assert_eq!(node_txn[1], node_txn[4]);
2549 assert_eq!(node_txn[2], commitment_tx[0]);
2550 check_spends!(node_txn[0], commitment_tx[0]);
2551 check_spends!(node_txn[1], commitment_tx[0]);
2552 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2553 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2554 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2555 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2556 assert_eq!(node_txn[0].lock_time, 0);
2557 assert_eq!(node_txn[1].lock_time, 0);
2559 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2560 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2561 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2562 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2564 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2565 assert_eq!(added_monitors.len(), 1);
2566 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2567 added_monitors.clear();
2569 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2570 assert_eq!(forwarded_events.len(), 3);
2571 match forwarded_events[0] {
2572 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2573 _ => panic!("Unexpected event"),
2575 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2576 } else { panic!(); }
2577 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2578 } else { panic!(); }
2579 let events = nodes[1].node.get_and_clear_pending_msg_events();
2581 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2582 assert_eq!(added_monitors.len(), 2);
2583 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2584 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2585 added_monitors.clear();
2587 assert_eq!(events.len(), 3);
2589 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2590 _ => panic!("Unexpected event"),
2593 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2594 _ => panic!("Unexpected event"),
2598 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, .. } } => {
2599 assert!(update_add_htlcs.is_empty());
2600 assert!(update_fail_htlcs.is_empty());
2601 assert_eq!(update_fulfill_htlcs.len(), 1);
2602 assert!(update_fail_malformed_htlcs.is_empty());
2603 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2605 _ => panic!("Unexpected event"),
2607 macro_rules! check_tx_local_broadcast {
2608 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2609 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2610 assert_eq!(node_txn.len(), 3);
2611 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2612 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2613 check_spends!(node_txn[1], $commitment_tx);
2614 check_spends!(node_txn[2], $commitment_tx);
2615 assert_ne!(node_txn[1].lock_time, 0);
2616 assert_ne!(node_txn[2].lock_time, 0);
2618 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2619 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2620 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2621 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2623 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2624 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2625 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2626 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2628 check_spends!(node_txn[0], $chan_tx);
2629 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2633 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2634 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2635 // timeout-claim of the output that nodes[2] just claimed via success.
2636 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2638 // Broadcast legit commitment tx from A on B's chain
2639 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2640 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2641 check_spends!(node_a_commitment_tx[0], chan_1.3);
2642 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2643 check_closed_broadcast!(nodes[1], true);
2644 check_added_monitors!(nodes[1], 1);
2645 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2646 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2647 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2648 let commitment_spend =
2649 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2650 check_spends!(node_txn[1], commitment_tx[0]);
2651 check_spends!(node_txn[2], commitment_tx[0]);
2652 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2655 check_spends!(node_txn[0], commitment_tx[0]);
2656 check_spends!(node_txn[1], commitment_tx[0]);
2657 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2661 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2662 assert_eq!(commitment_spend.input.len(), 2);
2663 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2664 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2665 assert_eq!(commitment_spend.lock_time, 0);
2666 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2667 check_spends!(node_txn[3], chan_1.3);
2668 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2669 check_spends!(node_txn[4], node_txn[3]);
2670 check_spends!(node_txn[5], node_txn[3]);
2671 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2672 // we already checked the same situation with A.
2674 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2675 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2676 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2677 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2678 check_closed_broadcast!(nodes[0], true);
2679 check_added_monitors!(nodes[0], 1);
2680 let events = nodes[0].node.get_and_clear_pending_events();
2681 assert_eq!(events.len(), 3);
2682 let mut first_claimed = false;
2683 for event in events {
2685 Event::PaymentSent { payment_preimage } => {
2686 if payment_preimage == our_payment_preimage {
2687 assert!(!first_claimed);
2688 first_claimed = true;
2690 assert_eq!(payment_preimage, our_payment_preimage_2);
2693 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2694 _ => panic!("Unexpected event"),
2697 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2700 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2701 // Test that in case of a unilateral close onchain, we detect the state of output and
2702 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2703 // broadcasting the right event to other nodes in payment path.
2704 // A ------------------> B ----------------------> C (timeout)
2705 // B's commitment tx C's commitment tx
2707 // B's HTLC timeout tx B's timeout tx
2709 let chanmon_cfgs = create_chanmon_cfgs(3);
2710 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2711 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2712 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2713 *nodes[0].connect_style.borrow_mut() = connect_style;
2714 *nodes[1].connect_style.borrow_mut() = connect_style;
2715 *nodes[2].connect_style.borrow_mut() = connect_style;
2717 // Create some intial channels
2718 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2719 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2721 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2722 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2723 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2725 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2727 // Broadcast legit commitment tx from C on B's chain
2728 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2729 check_spends!(commitment_tx[0], chan_2.3);
2730 nodes[2].node.fail_htlc_backwards(&payment_hash);
2731 check_added_monitors!(nodes[2], 0);
2732 expect_pending_htlcs_forwardable!(nodes[2]);
2733 check_added_monitors!(nodes[2], 1);
2735 let events = nodes[2].node.get_and_clear_pending_msg_events();
2736 assert_eq!(events.len(), 1);
2738 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, .. } } => {
2739 assert!(update_add_htlcs.is_empty());
2740 assert!(!update_fail_htlcs.is_empty());
2741 assert!(update_fulfill_htlcs.is_empty());
2742 assert!(update_fail_malformed_htlcs.is_empty());
2743 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2745 _ => panic!("Unexpected event"),
2747 mine_transaction(&nodes[2], &commitment_tx[0]);
2748 check_closed_broadcast!(nodes[2], true);
2749 check_added_monitors!(nodes[2], 1);
2750 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2751 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2752 assert_eq!(node_txn.len(), 1);
2753 check_spends!(node_txn[0], chan_2.3);
2754 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2756 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2757 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2758 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2759 mine_transaction(&nodes[1], &commitment_tx[0]);
2760 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2763 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2764 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2765 assert_eq!(node_txn[0], node_txn[3]);
2766 assert_eq!(node_txn[1], node_txn[4]);
2768 check_spends!(node_txn[2], commitment_tx[0]);
2769 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771 check_spends!(node_txn[0], chan_2.3);
2772 check_spends!(node_txn[1], node_txn[0]);
2773 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2774 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2776 timeout_tx = node_txn[2].clone();
2780 mine_transaction(&nodes[1], &timeout_tx);
2781 check_added_monitors!(nodes[1], 1);
2782 check_closed_broadcast!(nodes[1], true);
2784 // B will rebroadcast a fee-bumped timeout transaction here.
2785 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2786 assert_eq!(node_txn.len(), 1);
2787 check_spends!(node_txn[0], commitment_tx[0]);
2790 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2792 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2793 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2794 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2795 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2796 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2797 if node_txn.len() == 1 {
2798 check_spends!(node_txn[0], chan_2.3);
2800 assert_eq!(node_txn.len(), 0);
2804 expect_pending_htlcs_forwardable!(nodes[1]);
2805 check_added_monitors!(nodes[1], 1);
2806 let events = nodes[1].node.get_and_clear_pending_msg_events();
2807 assert_eq!(events.len(), 1);
2809 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, .. } } => {
2810 assert!(update_add_htlcs.is_empty());
2811 assert!(!update_fail_htlcs.is_empty());
2812 assert!(update_fulfill_htlcs.is_empty());
2813 assert!(update_fail_malformed_htlcs.is_empty());
2814 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2816 _ => panic!("Unexpected event"),
2819 // Broadcast legit commitment tx from B on A's chain
2820 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2821 check_spends!(commitment_tx[0], chan_1.3);
2823 mine_transaction(&nodes[0], &commitment_tx[0]);
2824 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2826 check_closed_broadcast!(nodes[0], true);
2827 check_added_monitors!(nodes[0], 1);
2828 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2829 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2830 assert_eq!(node_txn.len(), 2);
2831 check_spends!(node_txn[0], chan_1.3);
2832 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2833 check_spends!(node_txn[1], commitment_tx[0]);
2834 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2838 fn test_htlc_on_chain_timeout() {
2839 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2840 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2841 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2845 fn test_simple_commitment_revoked_fail_backward() {
2846 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2847 // and fail backward accordingly.
2849 let chanmon_cfgs = create_chanmon_cfgs(3);
2850 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2851 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2852 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2854 // Create some initial channels
2855 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2856 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2858 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2859 // Get the will-be-revoked local txn from nodes[2]
2860 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2861 // Revoke the old state
2862 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2864 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2866 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2867 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2868 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2869 check_added_monitors!(nodes[1], 1);
2870 check_closed_broadcast!(nodes[1], true);
2872 expect_pending_htlcs_forwardable!(nodes[1]);
2873 check_added_monitors!(nodes[1], 1);
2874 let events = nodes[1].node.get_and_clear_pending_msg_events();
2875 assert_eq!(events.len(), 1);
2877 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, .. } } => {
2878 assert!(update_add_htlcs.is_empty());
2879 assert_eq!(update_fail_htlcs.len(), 1);
2880 assert!(update_fulfill_htlcs.is_empty());
2881 assert!(update_fail_malformed_htlcs.is_empty());
2882 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2884 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2885 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2886 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2888 _ => panic!("Unexpected event"),
2892 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2893 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2894 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2895 // commitment transaction anymore.
2896 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2897 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2898 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2899 // technically disallowed and we should probably handle it reasonably.
2900 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2901 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2903 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2904 // commitment_signed (implying it will be in the latest remote commitment transaction).
2905 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2906 // and once they revoke the previous commitment transaction (allowing us to send a new
2907 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2908 let chanmon_cfgs = create_chanmon_cfgs(3);
2909 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2910 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2911 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2913 // Create some initial channels
2914 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2915 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2917 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 });
2918 // Get the will-be-revoked local txn from nodes[2]
2919 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2920 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2921 // Revoke the old state
2922 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2924 let value = if use_dust {
2925 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2926 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2927 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2930 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2931 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2932 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2934 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2935 expect_pending_htlcs_forwardable!(nodes[2]);
2936 check_added_monitors!(nodes[2], 1);
2937 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2938 assert!(updates.update_add_htlcs.is_empty());
2939 assert!(updates.update_fulfill_htlcs.is_empty());
2940 assert!(updates.update_fail_malformed_htlcs.is_empty());
2941 assert_eq!(updates.update_fail_htlcs.len(), 1);
2942 assert!(updates.update_fee.is_none());
2943 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2944 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2945 // Drop the last RAA from 3 -> 2
2947 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2948 expect_pending_htlcs_forwardable!(nodes[2]);
2949 check_added_monitors!(nodes[2], 1);
2950 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2951 assert!(updates.update_add_htlcs.is_empty());
2952 assert!(updates.update_fulfill_htlcs.is_empty());
2953 assert!(updates.update_fail_malformed_htlcs.is_empty());
2954 assert_eq!(updates.update_fail_htlcs.len(), 1);
2955 assert!(updates.update_fee.is_none());
2956 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2957 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2958 check_added_monitors!(nodes[1], 1);
2959 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2960 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2961 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2962 check_added_monitors!(nodes[2], 1);
2964 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2965 expect_pending_htlcs_forwardable!(nodes[2]);
2966 check_added_monitors!(nodes[2], 1);
2967 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2968 assert!(updates.update_add_htlcs.is_empty());
2969 assert!(updates.update_fulfill_htlcs.is_empty());
2970 assert!(updates.update_fail_malformed_htlcs.is_empty());
2971 assert_eq!(updates.update_fail_htlcs.len(), 1);
2972 assert!(updates.update_fee.is_none());
2973 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2974 // At this point first_payment_hash has dropped out of the latest two commitment
2975 // transactions that nodes[1] is tracking...
2976 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2977 check_added_monitors!(nodes[1], 1);
2978 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2979 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2980 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2981 check_added_monitors!(nodes[2], 1);
2983 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2984 // on nodes[2]'s RAA.
2985 let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
2986 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2987 let logger = test_utils::TestLogger::new();
2988 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
2989 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2990 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2991 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2992 check_added_monitors!(nodes[1], 0);
2995 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2996 // One monitor for the new revocation preimage, no second on as we won't generate a new
2997 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2998 check_added_monitors!(nodes[1], 1);
2999 let events = nodes[1].node.get_and_clear_pending_events();
3000 assert_eq!(events.len(), 1);
3002 Event::PendingHTLCsForwardable { .. } => { },
3003 _ => panic!("Unexpected event"),
3005 // Deliberately don't process the pending fail-back so they all fail back at once after
3006 // block connection just like the !deliver_bs_raa case
3009 let mut failed_htlcs = HashSet::new();
3010 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3012 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3013 check_added_monitors!(nodes[1], 1);
3014 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3016 let events = nodes[1].node.get_and_clear_pending_events();
3017 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3019 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3020 _ => panic!("Unexepected event"),
3023 Event::PaymentPathFailed { ref payment_hash, .. } => {
3024 assert_eq!(*payment_hash, fourth_payment_hash);
3026 _ => panic!("Unexpected event"),
3028 if !deliver_bs_raa {
3030 Event::PendingHTLCsForwardable { .. } => { },
3031 _ => panic!("Unexpected event"),
3034 nodes[1].node.process_pending_htlc_forwards();
3035 check_added_monitors!(nodes[1], 1);
3037 let events = nodes[1].node.get_and_clear_pending_msg_events();
3038 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3039 match events[if deliver_bs_raa { 1 } else { 0 }] {
3040 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3041 _ => panic!("Unexpected event"),
3043 match events[if deliver_bs_raa { 2 } else { 1 }] {
3044 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3045 assert_eq!(channel_id, chan_2.2);
3046 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3048 _ => panic!("Unexpected event"),
3052 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, .. } } => {
3053 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3054 assert_eq!(update_add_htlcs.len(), 1);
3055 assert!(update_fulfill_htlcs.is_empty());
3056 assert!(update_fail_htlcs.is_empty());
3057 assert!(update_fail_malformed_htlcs.is_empty());
3059 _ => panic!("Unexpected event"),
3062 match events[if deliver_bs_raa { 3 } else { 2 }] {
3063 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, .. } } => {
3064 assert!(update_add_htlcs.is_empty());
3065 assert_eq!(update_fail_htlcs.len(), 3);
3066 assert!(update_fulfill_htlcs.is_empty());
3067 assert!(update_fail_malformed_htlcs.is_empty());
3068 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3070 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3071 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3072 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3074 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3076 let events = nodes[0].node.get_and_clear_pending_events();
3077 assert_eq!(events.len(), 3);
3079 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3080 assert!(failed_htlcs.insert(payment_hash.0));
3081 // If we delivered B's RAA we got an unknown preimage error, not something
3082 // that we should update our routing table for.
3083 if !deliver_bs_raa {
3084 assert!(network_update.is_some());
3087 _ => panic!("Unexpected event"),
3090 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3091 assert!(failed_htlcs.insert(payment_hash.0));
3092 assert!(network_update.is_some());
3094 _ => panic!("Unexpected event"),
3097 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3098 assert!(failed_htlcs.insert(payment_hash.0));
3099 assert!(network_update.is_some());
3101 _ => panic!("Unexpected event"),
3104 _ => panic!("Unexpected event"),
3107 assert!(failed_htlcs.contains(&first_payment_hash.0));
3108 assert!(failed_htlcs.contains(&second_payment_hash.0));
3109 assert!(failed_htlcs.contains(&third_payment_hash.0));
3113 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3114 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3115 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3116 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3117 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3121 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3122 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3123 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3124 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3125 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3129 fn fail_backward_pending_htlc_upon_channel_failure() {
3130 let chanmon_cfgs = create_chanmon_cfgs(2);
3131 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3132 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3133 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3134 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3135 let logger = test_utils::TestLogger::new();
3137 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3139 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3140 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3141 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3142 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3143 check_added_monitors!(nodes[0], 1);
3145 let payment_event = {
3146 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3147 assert_eq!(events.len(), 1);
3148 SendEvent::from_event(events.remove(0))
3150 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3151 assert_eq!(payment_event.msgs.len(), 1);
3154 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3155 let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3157 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3158 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3159 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3160 check_added_monitors!(nodes[0], 0);
3162 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3165 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3167 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3169 let secp_ctx = Secp256k1::new();
3170 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3171 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3172 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3173 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3174 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3175 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3176 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3178 // Send a 0-msat update_add_htlc to fail the channel.
3179 let update_add_htlc = msgs::UpdateAddHTLC {
3185 onion_routing_packet,
3187 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3189 let events = nodes[0].node.get_and_clear_pending_events();
3190 assert_eq!(events.len(), 2);
3191 // Check that Alice fails backward the pending HTLC from the second payment.
3193 Event::PaymentPathFailed { payment_hash, .. } => {
3194 assert_eq!(payment_hash, failed_payment_hash);
3196 _ => panic!("Unexpected event"),
3199 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3200 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3202 _ => panic!("Unexpected event {:?}", events[1]),
3204 check_closed_broadcast!(nodes[0], true);
3205 check_added_monitors!(nodes[0], 1);
3209 fn test_htlc_ignore_latest_remote_commitment() {
3210 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3211 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3212 let chanmon_cfgs = create_chanmon_cfgs(2);
3213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3215 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3216 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3218 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3219 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3220 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3221 check_closed_broadcast!(nodes[0], true);
3222 check_added_monitors!(nodes[0], 1);
3223 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3225 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3226 assert_eq!(node_txn.len(), 3);
3227 assert_eq!(node_txn[0], node_txn[1]);
3229 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3230 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3231 check_closed_broadcast!(nodes[1], true);
3232 check_added_monitors!(nodes[1], 1);
3233 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3235 // Duplicate the connect_block call since this may happen due to other listeners
3236 // registering new transactions
3237 header.prev_blockhash = header.block_hash();
3238 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3242 fn test_force_close_fail_back() {
3243 // Check which HTLCs are failed-backwards on channel force-closure
3244 let chanmon_cfgs = create_chanmon_cfgs(3);
3245 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3246 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3247 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3248 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3249 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3250 let logger = test_utils::TestLogger::new();
3252 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3254 let mut payment_event = {
3255 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3256 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3257 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3258 check_added_monitors!(nodes[0], 1);
3260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3261 assert_eq!(events.len(), 1);
3262 SendEvent::from_event(events.remove(0))
3265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3266 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3268 expect_pending_htlcs_forwardable!(nodes[1]);
3270 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3271 assert_eq!(events_2.len(), 1);
3272 payment_event = SendEvent::from_event(events_2.remove(0));
3273 assert_eq!(payment_event.msgs.len(), 1);
3275 check_added_monitors!(nodes[1], 1);
3276 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3277 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3278 check_added_monitors!(nodes[2], 1);
3279 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3281 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3282 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3283 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3285 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3286 check_closed_broadcast!(nodes[2], true);
3287 check_added_monitors!(nodes[2], 1);
3288 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3290 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3291 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3292 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3293 // back to nodes[1] upon timeout otherwise.
3294 assert_eq!(node_txn.len(), 1);
3298 mine_transaction(&nodes[1], &tx);
3300 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3301 check_closed_broadcast!(nodes[1], true);
3302 check_added_monitors!(nodes[1], 1);
3303 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3305 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3307 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3308 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3309 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3311 mine_transaction(&nodes[2], &tx);
3312 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3313 assert_eq!(node_txn.len(), 1);
3314 assert_eq!(node_txn[0].input.len(), 1);
3315 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3316 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3317 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3319 check_spends!(node_txn[0], tx);
3323 fn test_dup_events_on_peer_disconnect() {
3324 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3325 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3326 // as we used to generate the event immediately upon receipt of the payment preimage in the
3327 // update_fulfill_htlc message.
3329 let chanmon_cfgs = create_chanmon_cfgs(2);
3330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3333 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3335 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3337 assert!(nodes[1].node.claim_funds(payment_preimage));
3338 check_added_monitors!(nodes[1], 1);
3339 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3340 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3341 expect_payment_sent!(nodes[0], payment_preimage);
3343 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3344 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3346 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3347 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3351 fn test_simple_peer_disconnect() {
3352 // Test that we can reconnect when there are no lost messages
3353 let chanmon_cfgs = create_chanmon_cfgs(3);
3354 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3355 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3356 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3357 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3358 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3360 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3361 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3362 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3364 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3365 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3366 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3367 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3369 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3370 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3371 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3373 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3374 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3375 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3376 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3378 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3379 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3381 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3382 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3384 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3386 let events = nodes[0].node.get_and_clear_pending_events();
3387 assert_eq!(events.len(), 2);
3389 Event::PaymentSent { payment_preimage } => {
3390 assert_eq!(payment_preimage, payment_preimage_3);
3392 _ => panic!("Unexpected event"),
3395 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3396 assert_eq!(payment_hash, payment_hash_5);
3397 assert!(rejected_by_dest);
3399 _ => panic!("Unexpected event"),
3403 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3404 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3407 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3408 // Test that we can reconnect when in-flight HTLC updates get dropped
3409 let chanmon_cfgs = create_chanmon_cfgs(2);
3410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3412 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3414 let mut as_funding_locked = None;
3415 if messages_delivered == 0 {
3416 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3417 as_funding_locked = Some(funding_locked);
3418 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3419 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3420 // it before the channel_reestablish message.
3422 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3425 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3427 let logger = test_utils::TestLogger::new();
3428 let payment_event = {
3429 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3430 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3431 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3432 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3433 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3434 check_added_monitors!(nodes[0], 1);
3436 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3437 assert_eq!(events.len(), 1);
3438 SendEvent::from_event(events.remove(0))
3440 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3442 if messages_delivered < 2 {
3443 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3445 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3446 if messages_delivered >= 3 {
3447 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3448 check_added_monitors!(nodes[1], 1);
3449 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3451 if messages_delivered >= 4 {
3452 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3453 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3454 check_added_monitors!(nodes[0], 1);
3456 if messages_delivered >= 5 {
3457 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3458 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3459 // No commitment_signed so get_event_msg's assert(len == 1) passes
3460 check_added_monitors!(nodes[0], 1);
3462 if messages_delivered >= 6 {
3463 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3464 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3465 check_added_monitors!(nodes[1], 1);
3472 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3473 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3474 if messages_delivered < 3 {
3475 if simulate_broken_lnd {
3476 // lnd has a long-standing bug where they send a funding_locked prior to a
3477 // channel_reestablish if you reconnect prior to funding_locked time.
3479 // Here we simulate that behavior, delivering a funding_locked immediately on
3480 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3481 // in `reconnect_nodes` but we currently don't fail based on that.
3483 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3484 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3486 // Even if the funding_locked messages get exchanged, as long as nothing further was
3487 // received on either side, both sides will need to resend them.
3488 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3489 } else if messages_delivered == 3 {
3490 // nodes[0] still wants its RAA + commitment_signed
3491 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3492 } else if messages_delivered == 4 {
3493 // nodes[0] still wants its commitment_signed
3494 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3495 } else if messages_delivered == 5 {
3496 // nodes[1] still wants its final RAA
3497 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3498 } else if messages_delivered == 6 {
3499 // Everything was delivered...
3500 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3503 let events_1 = nodes[1].node.get_and_clear_pending_events();
3504 assert_eq!(events_1.len(), 1);
3506 Event::PendingHTLCsForwardable { .. } => { },
3507 _ => panic!("Unexpected event"),
3510 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3511 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3512 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3514 nodes[1].node.process_pending_htlc_forwards();
3516 let events_2 = nodes[1].node.get_and_clear_pending_events();
3517 assert_eq!(events_2.len(), 1);
3519 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3520 assert_eq!(payment_hash_1, *payment_hash);
3521 assert_eq!(amt, 1000000);
3523 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3524 assert!(payment_preimage.is_none());
3525 assert_eq!(payment_secret_1, *payment_secret);
3527 _ => panic!("expected PaymentPurpose::InvoicePayment")
3530 _ => panic!("Unexpected event"),
3533 nodes[1].node.claim_funds(payment_preimage_1);
3534 check_added_monitors!(nodes[1], 1);
3536 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3537 assert_eq!(events_3.len(), 1);
3538 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3539 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3540 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3541 assert!(updates.update_add_htlcs.is_empty());
3542 assert!(updates.update_fail_htlcs.is_empty());
3543 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3544 assert!(updates.update_fail_malformed_htlcs.is_empty());
3545 assert!(updates.update_fee.is_none());
3546 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3548 _ => panic!("Unexpected event"),
3551 if messages_delivered >= 1 {
3552 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3554 let events_4 = nodes[0].node.get_and_clear_pending_events();
3555 assert_eq!(events_4.len(), 1);
3557 Event::PaymentSent { ref payment_preimage } => {
3558 assert_eq!(payment_preimage_1, *payment_preimage);
3560 _ => panic!("Unexpected event"),
3563 if messages_delivered >= 2 {
3564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3565 check_added_monitors!(nodes[0], 1);
3566 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3568 if messages_delivered >= 3 {
3569 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3570 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3571 check_added_monitors!(nodes[1], 1);
3573 if messages_delivered >= 4 {
3574 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3575 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3576 // No commitment_signed so get_event_msg's assert(len == 1) passes
3577 check_added_monitors!(nodes[1], 1);
3579 if messages_delivered >= 5 {
3580 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3581 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3582 check_added_monitors!(nodes[0], 1);
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);
3591 if messages_delivered < 2 {
3592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593 if messages_delivered < 1 {
3594 let events_4 = nodes[0].node.get_and_clear_pending_events();
3595 assert_eq!(events_4.len(), 1);
3597 Event::PaymentSent { ref payment_preimage } => {
3598 assert_eq!(payment_preimage_1, *payment_preimage);
3600 _ => panic!("Unexpected event"),
3603 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3605 } else if messages_delivered == 2 {
3606 // nodes[0] still wants its RAA + commitment_signed
3607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3608 } else if messages_delivered == 3 {
3609 // nodes[0] still wants its commitment_signed
3610 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3611 } else if messages_delivered == 4 {
3612 // nodes[1] still wants its final RAA
3613 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3614 } else if messages_delivered == 5 {
3615 // Everything was delivered...
3616 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3619 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3620 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3621 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3623 // Channel should still work fine...
3624 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3625 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3626 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3627 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3628 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3629 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3633 fn test_drop_messages_peer_disconnect_a() {
3634 do_test_drop_messages_peer_disconnect(0, true);
3635 do_test_drop_messages_peer_disconnect(0, false);
3636 do_test_drop_messages_peer_disconnect(1, false);
3637 do_test_drop_messages_peer_disconnect(2, false);
3641 fn test_drop_messages_peer_disconnect_b() {
3642 do_test_drop_messages_peer_disconnect(3, false);
3643 do_test_drop_messages_peer_disconnect(4, false);
3644 do_test_drop_messages_peer_disconnect(5, false);
3645 do_test_drop_messages_peer_disconnect(6, false);
3649 fn test_funding_peer_disconnect() {
3650 // Test that we can lock in our funding tx while disconnected
3651 let chanmon_cfgs = create_chanmon_cfgs(2);
3652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3654 let persister: test_utils::TestPersister;
3655 let new_chain_monitor: test_utils::TestChainMonitor;
3656 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3657 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3658 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3660 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3661 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3663 confirm_transaction(&nodes[0], &tx);
3664 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3665 assert_eq!(events_1.len(), 1);
3667 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3668 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3670 _ => panic!("Unexpected event"),
3673 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3675 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3676 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3678 confirm_transaction(&nodes[1], &tx);
3679 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3680 assert_eq!(events_2.len(), 2);
3681 let funding_locked = match events_2[0] {
3682 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3683 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3686 _ => panic!("Unexpected event"),
3688 let bs_announcement_sigs = match events_2[1] {
3689 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3690 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3693 _ => panic!("Unexpected event"),
3696 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3698 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3699 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3700 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3701 assert_eq!(events_3.len(), 2);
3702 let as_announcement_sigs = match events_3[0] {
3703 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3704 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3707 _ => panic!("Unexpected event"),
3709 let (as_announcement, as_update) = match events_3[1] {
3710 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3711 (msg.clone(), update_msg.clone())
3713 _ => panic!("Unexpected event"),
3716 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3717 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3718 assert_eq!(events_4.len(), 1);
3719 let (_, bs_update) = match events_4[0] {
3720 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3721 (msg.clone(), update_msg.clone())
3723 _ => panic!("Unexpected event"),
3726 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3727 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3728 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3730 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3731 let logger = test_utils::TestLogger::new();
3732 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3733 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3734 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3736 // Check that after deserialization and reconnection we can still generate an identical
3737 // channel_announcement from the cached signatures.
3738 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3740 let nodes_0_serialized = nodes[0].node.encode();
3741 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3742 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3744 persister = test_utils::TestPersister::new();
3745 let keys_manager = &chanmon_cfgs[0].keys_manager;
3746 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);
3747 nodes[0].chain_monitor = &new_chain_monitor;
3748 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3749 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3750 &mut chan_0_monitor_read, keys_manager).unwrap();
3751 assert!(chan_0_monitor_read.is_empty());
3753 let mut nodes_0_read = &nodes_0_serialized[..];
3754 let (_, nodes_0_deserialized_tmp) = {
3755 let mut channel_monitors = HashMap::new();
3756 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3757 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3758 default_config: UserConfig::default(),
3760 fee_estimator: node_cfgs[0].fee_estimator,
3761 chain_monitor: nodes[0].chain_monitor,
3762 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3763 logger: nodes[0].logger,
3767 nodes_0_deserialized = nodes_0_deserialized_tmp;
3768 assert!(nodes_0_read.is_empty());
3770 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3771 nodes[0].node = &nodes_0_deserialized;
3772 check_added_monitors!(nodes[0], 1);
3774 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3776 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3777 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3778 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3779 let mut found_announcement = false;
3780 for event in msgs.iter() {
3782 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3783 if *msg == as_announcement { found_announcement = true; }
3785 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3786 _ => panic!("Unexpected event"),
3789 assert!(found_announcement);
3793 fn test_drop_messages_peer_disconnect_dual_htlc() {
3794 // Test that we can handle reconnecting when both sides of a channel have pending
3795 // commitment_updates when we disconnect.
3796 let chanmon_cfgs = create_chanmon_cfgs(2);
3797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3800 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3801 let logger = test_utils::TestLogger::new();
3803 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3805 // Now try to send a second payment which will fail to send
3806 let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
3807 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3808 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3809 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3810 check_added_monitors!(nodes[0], 1);
3812 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3813 assert_eq!(events_1.len(), 1);
3815 MessageSendEvent::UpdateHTLCs { .. } => {},
3816 _ => panic!("Unexpected event"),
3819 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3820 check_added_monitors!(nodes[1], 1);
3822 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3823 assert_eq!(events_2.len(), 1);
3825 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 } } => {
3826 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3827 assert!(update_add_htlcs.is_empty());
3828 assert_eq!(update_fulfill_htlcs.len(), 1);
3829 assert!(update_fail_htlcs.is_empty());
3830 assert!(update_fail_malformed_htlcs.is_empty());
3831 assert!(update_fee.is_none());
3833 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3834 let events_3 = nodes[0].node.get_and_clear_pending_events();
3835 assert_eq!(events_3.len(), 1);
3837 Event::PaymentSent { ref payment_preimage } => {
3838 assert_eq!(*payment_preimage, payment_preimage_1);
3840 _ => panic!("Unexpected event"),
3843 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3844 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3845 // No commitment_signed so get_event_msg's assert(len == 1) passes
3846 check_added_monitors!(nodes[0], 1);
3848 _ => panic!("Unexpected event"),
3851 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3852 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3854 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3855 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3856 assert_eq!(reestablish_1.len(), 1);
3857 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3858 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3859 assert_eq!(reestablish_2.len(), 1);
3861 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3862 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3863 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3864 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3866 assert!(as_resp.0.is_none());
3867 assert!(bs_resp.0.is_none());
3869 assert!(bs_resp.1.is_none());
3870 assert!(bs_resp.2.is_none());
3872 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3874 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3875 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3876 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3877 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3878 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3879 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3880 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3881 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3882 // No commitment_signed so get_event_msg's assert(len == 1) passes
3883 check_added_monitors!(nodes[1], 1);
3885 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3886 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3887 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3888 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3889 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3890 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3891 assert!(bs_second_commitment_signed.update_fee.is_none());
3892 check_added_monitors!(nodes[1], 1);
3894 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3895 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3896 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3897 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3898 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3899 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3900 assert!(as_commitment_signed.update_fee.is_none());
3901 check_added_monitors!(nodes[0], 1);
3903 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3904 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3905 // No commitment_signed so get_event_msg's assert(len == 1) passes
3906 check_added_monitors!(nodes[0], 1);
3908 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3909 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3910 // No commitment_signed so get_event_msg's assert(len == 1) passes
3911 check_added_monitors!(nodes[1], 1);
3913 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3914 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3915 check_added_monitors!(nodes[1], 1);
3917 expect_pending_htlcs_forwardable!(nodes[1]);
3919 let events_5 = nodes[1].node.get_and_clear_pending_events();
3920 assert_eq!(events_5.len(), 1);
3922 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3923 assert_eq!(payment_hash_2, *payment_hash);
3925 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3926 assert!(payment_preimage.is_none());
3927 assert_eq!(payment_secret_2, *payment_secret);
3929 _ => panic!("expected PaymentPurpose::InvoicePayment")
3932 _ => panic!("Unexpected event"),
3935 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3936 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3937 check_added_monitors!(nodes[0], 1);
3939 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3942 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3943 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3944 // to avoid our counterparty failing the channel.
3945 let chanmon_cfgs = create_chanmon_cfgs(2);
3946 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3947 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3948 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3950 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3951 let logger = test_utils::TestLogger::new();
3953 let our_payment_hash = if send_partial_mpp {
3954 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3955 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3956 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
3957 // Use the utility function send_payment_along_path to send the payment with MPP data which
3958 // indicates there are more HTLCs coming.
3959 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.
3960 let payment_id = PaymentId([42; 32]);
3961 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3962 check_added_monitors!(nodes[0], 1);
3963 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3964 assert_eq!(events.len(), 1);
3965 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3966 // hop should *not* yet generate any PaymentReceived event(s).
3967 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3970 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3973 let mut block = Block {
3974 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3977 connect_block(&nodes[0], &block);
3978 connect_block(&nodes[1], &block);
3979 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3980 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3981 block.header.prev_blockhash = block.block_hash();
3982 connect_block(&nodes[0], &block);
3983 connect_block(&nodes[1], &block);
3986 expect_pending_htlcs_forwardable!(nodes[1]);
3988 check_added_monitors!(nodes[1], 1);
3989 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3990 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3991 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3992 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3993 assert!(htlc_timeout_updates.update_fee.is_none());
3995 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3996 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3997 // 100_000 msat as u64, followed by the height at which we failed back above
3998 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3999 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4000 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4004 fn test_htlc_timeout() {
4005 do_test_htlc_timeout(true);
4006 do_test_htlc_timeout(false);
4009 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4010 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4011 let chanmon_cfgs = create_chanmon_cfgs(3);
4012 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4013 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4014 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4015 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4016 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4018 // Make sure all nodes are at the same starting height
4019 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4020 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4021 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4023 let logger = test_utils::TestLogger::new();
4025 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4026 let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4028 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4029 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4030 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4032 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4033 check_added_monitors!(nodes[1], 1);
4035 // Now attempt to route a second payment, which should be placed in the holding cell
4036 let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4038 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4039 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4040 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
4041 check_added_monitors!(nodes[0], 1);
4042 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4044 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4045 expect_pending_htlcs_forwardable!(nodes[1]);
4046 check_added_monitors!(nodes[1], 0);
4048 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4049 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4050 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4051 check_added_monitors!(nodes[1], 0);
4054 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4055 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4056 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4057 connect_blocks(&nodes[1], 1);
4060 expect_pending_htlcs_forwardable!(nodes[1]);
4061 check_added_monitors!(nodes[1], 1);
4062 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4063 assert_eq!(fail_commit.len(), 1);
4064 match fail_commit[0] {
4065 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4066 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4067 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4069 _ => unreachable!(),
4071 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4073 expect_payment_failed!(nodes[1], second_payment_hash, true);
4078 fn test_holding_cell_htlc_add_timeouts() {
4079 do_test_holding_cell_htlc_add_timeouts(false);
4080 do_test_holding_cell_htlc_add_timeouts(true);
4084 fn test_no_txn_manager_serialize_deserialize() {
4085 let chanmon_cfgs = create_chanmon_cfgs(2);
4086 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4087 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4088 let logger: test_utils::TestLogger;
4089 let fee_estimator: test_utils::TestFeeEstimator;
4090 let persister: test_utils::TestPersister;
4091 let new_chain_monitor: test_utils::TestChainMonitor;
4092 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4093 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4095 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4097 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4099 let nodes_0_serialized = nodes[0].node.encode();
4100 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4101 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4103 logger = test_utils::TestLogger::new();
4104 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4105 persister = test_utils::TestPersister::new();
4106 let keys_manager = &chanmon_cfgs[0].keys_manager;
4107 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4108 nodes[0].chain_monitor = &new_chain_monitor;
4109 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4110 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4111 &mut chan_0_monitor_read, keys_manager).unwrap();
4112 assert!(chan_0_monitor_read.is_empty());
4114 let mut nodes_0_read = &nodes_0_serialized[..];
4115 let config = UserConfig::default();
4116 let (_, nodes_0_deserialized_tmp) = {
4117 let mut channel_monitors = HashMap::new();
4118 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4119 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4120 default_config: config,
4122 fee_estimator: &fee_estimator,
4123 chain_monitor: nodes[0].chain_monitor,
4124 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4129 nodes_0_deserialized = nodes_0_deserialized_tmp;
4130 assert!(nodes_0_read.is_empty());
4132 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4133 nodes[0].node = &nodes_0_deserialized;
4134 assert_eq!(nodes[0].node.list_channels().len(), 1);
4135 check_added_monitors!(nodes[0], 1);
4137 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4138 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4139 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4140 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4142 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4143 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4144 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4145 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4147 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4148 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4149 for node in nodes.iter() {
4150 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4151 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4152 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4155 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4160 let chanmon_cfgs = create_chanmon_cfgs(4);
4161 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4162 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4163 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4165 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4166 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4167 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4168 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4169 let logger = test_utils::TestLogger::new();
4171 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
4172 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4173 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
4174 let path = route.paths[0].clone();
4175 route.paths.push(path);
4176 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
4177 route.paths[0][0].short_channel_id = chan_1_id;
4178 route.paths[0][1].short_channel_id = chan_3_id;
4179 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
4180 route.paths[1][0].short_channel_id = chan_2_id;
4181 route.paths[1][1].short_channel_id = chan_4_id;
4182 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
4183 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
4187 fn test_dup_htlc_onchain_fails_on_reload() {
4188 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4189 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4190 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4191 // the ChannelMonitor tells it to.
4193 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4194 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4195 // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4196 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4197 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4198 // and de-duplicates ChannelMonitor events.
4200 // This tests that explicit tracking behavior.
4201 let chanmon_cfgs = create_chanmon_cfgs(2);
4202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4204 let persister: test_utils::TestPersister;
4205 let new_chain_monitor: test_utils::TestChainMonitor;
4206 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4207 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4209 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4211 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4213 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4214 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4215 check_closed_broadcast!(nodes[0], true);
4216 check_added_monitors!(nodes[0], 1);
4217 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4219 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4220 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4222 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4223 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4224 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4225 assert_eq!(node_txn.len(), 3);
4226 assert_eq!(node_txn[0], node_txn[1]);
4228 assert!(nodes[1].node.claim_funds(payment_preimage));
4229 check_added_monitors!(nodes[1], 1);
4231 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4232 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4233 check_closed_broadcast!(nodes[1], true);
4234 check_added_monitors!(nodes[1], 1);
4235 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4236 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4238 header.prev_blockhash = nodes[0].best_block_hash();
4239 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4241 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4242 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4243 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4244 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4245 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4247 header.prev_blockhash = nodes[0].best_block_hash();
4248 let claim_block = Block { header, txdata: claim_txn};
4249 connect_block(&nodes[0], &claim_block);
4250 expect_payment_sent!(nodes[0], payment_preimage);
4252 // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4253 // connected a highly-relevant block, it likely gets serialized out now.
4254 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4255 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4257 // Now reload nodes[0]...
4258 persister = test_utils::TestPersister::new();
4259 let keys_manager = &chanmon_cfgs[0].keys_manager;
4260 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);
4261 nodes[0].chain_monitor = &new_chain_monitor;
4262 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4263 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4264 &mut chan_0_monitor_read, keys_manager).unwrap();
4265 assert!(chan_0_monitor_read.is_empty());
4267 let (_, nodes_0_deserialized_tmp) = {
4268 let mut channel_monitors = HashMap::new();
4269 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4270 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4271 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4272 default_config: Default::default(),
4274 fee_estimator: node_cfgs[0].fee_estimator,
4275 chain_monitor: nodes[0].chain_monitor,
4276 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4277 logger: nodes[0].logger,
4281 nodes_0_deserialized = nodes_0_deserialized_tmp;
4283 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4284 check_added_monitors!(nodes[0], 1);
4285 nodes[0].node = &nodes_0_deserialized;
4287 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4288 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4289 // payment events should kick in, leaving us with no pending events here.
4290 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4291 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4292 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4296 fn test_manager_serialize_deserialize_events() {
4297 // This test makes sure the events field in ChannelManager survives de/serialization
4298 let chanmon_cfgs = create_chanmon_cfgs(2);
4299 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4300 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4301 let fee_estimator: test_utils::TestFeeEstimator;
4302 let persister: test_utils::TestPersister;
4303 let logger: test_utils::TestLogger;
4304 let new_chain_monitor: test_utils::TestChainMonitor;
4305 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4306 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4308 // Start creating a channel, but stop right before broadcasting the funding transaction
4309 let channel_value = 100000;
4310 let push_msat = 10001;
4311 let a_flags = InitFeatures::known();
4312 let b_flags = InitFeatures::known();
4313 let node_a = nodes.remove(0);
4314 let node_b = nodes.remove(0);
4315 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4316 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()));
4317 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()));
4319 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4321 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4322 check_added_monitors!(node_a, 0);
4324 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()));
4326 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4327 assert_eq!(added_monitors.len(), 1);
4328 assert_eq!(added_monitors[0].0, funding_output);
4329 added_monitors.clear();
4332 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()));
4334 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4335 assert_eq!(added_monitors.len(), 1);
4336 assert_eq!(added_monitors[0].0, funding_output);
4337 added_monitors.clear();
4339 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4344 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4345 let nodes_0_serialized = nodes[0].node.encode();
4346 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4347 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4349 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4350 logger = test_utils::TestLogger::new();
4351 persister = test_utils::TestPersister::new();
4352 let keys_manager = &chanmon_cfgs[0].keys_manager;
4353 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4354 nodes[0].chain_monitor = &new_chain_monitor;
4355 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4356 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4357 &mut chan_0_monitor_read, keys_manager).unwrap();
4358 assert!(chan_0_monitor_read.is_empty());
4360 let mut nodes_0_read = &nodes_0_serialized[..];
4361 let config = UserConfig::default();
4362 let (_, nodes_0_deserialized_tmp) = {
4363 let mut channel_monitors = HashMap::new();
4364 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4365 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4366 default_config: config,
4368 fee_estimator: &fee_estimator,
4369 chain_monitor: nodes[0].chain_monitor,
4370 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4375 nodes_0_deserialized = nodes_0_deserialized_tmp;
4376 assert!(nodes_0_read.is_empty());
4378 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4380 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4381 nodes[0].node = &nodes_0_deserialized;
4383 // After deserializing, make sure the funding_transaction is still held by the channel manager
4384 let events_4 = nodes[0].node.get_and_clear_pending_events();
4385 assert_eq!(events_4.len(), 0);
4386 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4387 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4389 // Make sure the channel is functioning as though the de/serialization never happened
4390 assert_eq!(nodes[0].node.list_channels().len(), 1);
4391 check_added_monitors!(nodes[0], 1);
4393 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4394 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4395 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4396 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4398 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4399 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4400 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4401 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4403 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4404 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4405 for node in nodes.iter() {
4406 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4407 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4408 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4411 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4415 fn test_simple_manager_serialize_deserialize() {
4416 let chanmon_cfgs = create_chanmon_cfgs(2);
4417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4419 let logger: test_utils::TestLogger;
4420 let fee_estimator: test_utils::TestFeeEstimator;
4421 let persister: test_utils::TestPersister;
4422 let new_chain_monitor: test_utils::TestChainMonitor;
4423 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4424 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4425 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4427 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4428 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4430 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4432 let nodes_0_serialized = nodes[0].node.encode();
4433 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4434 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4436 logger = test_utils::TestLogger::new();
4437 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4438 persister = test_utils::TestPersister::new();
4439 let keys_manager = &chanmon_cfgs[0].keys_manager;
4440 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4441 nodes[0].chain_monitor = &new_chain_monitor;
4442 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4443 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4444 &mut chan_0_monitor_read, keys_manager).unwrap();
4445 assert!(chan_0_monitor_read.is_empty());
4447 let mut nodes_0_read = &nodes_0_serialized[..];
4448 let (_, nodes_0_deserialized_tmp) = {
4449 let mut channel_monitors = HashMap::new();
4450 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4451 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4452 default_config: UserConfig::default(),
4454 fee_estimator: &fee_estimator,
4455 chain_monitor: nodes[0].chain_monitor,
4456 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4461 nodes_0_deserialized = nodes_0_deserialized_tmp;
4462 assert!(nodes_0_read.is_empty());
4464 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4465 nodes[0].node = &nodes_0_deserialized;
4466 check_added_monitors!(nodes[0], 1);
4468 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4470 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4471 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4475 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4476 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4477 let chanmon_cfgs = create_chanmon_cfgs(4);
4478 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4479 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4480 let logger: test_utils::TestLogger;
4481 let fee_estimator: test_utils::TestFeeEstimator;
4482 let persister: test_utils::TestPersister;
4483 let new_chain_monitor: test_utils::TestChainMonitor;
4484 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4485 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4486 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4487 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4488 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4490 let mut node_0_stale_monitors_serialized = Vec::new();
4491 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4492 let mut writer = test_utils::TestVecWriter(Vec::new());
4493 monitor.1.write(&mut writer).unwrap();
4494 node_0_stale_monitors_serialized.push(writer.0);
4497 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4499 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4500 let nodes_0_serialized = nodes[0].node.encode();
4502 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4503 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4504 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4505 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4507 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4509 let mut node_0_monitors_serialized = Vec::new();
4510 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4511 let mut writer = test_utils::TestVecWriter(Vec::new());
4512 monitor.1.write(&mut writer).unwrap();
4513 node_0_monitors_serialized.push(writer.0);
4516 logger = test_utils::TestLogger::new();
4517 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4518 persister = test_utils::TestPersister::new();
4519 let keys_manager = &chanmon_cfgs[0].keys_manager;
4520 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4521 nodes[0].chain_monitor = &new_chain_monitor;
4524 let mut node_0_stale_monitors = Vec::new();
4525 for serialized in node_0_stale_monitors_serialized.iter() {
4526 let mut read = &serialized[..];
4527 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4528 assert!(read.is_empty());
4529 node_0_stale_monitors.push(monitor);
4532 let mut node_0_monitors = Vec::new();
4533 for serialized in node_0_monitors_serialized.iter() {
4534 let mut read = &serialized[..];
4535 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4536 assert!(read.is_empty());
4537 node_0_monitors.push(monitor);
4540 let mut nodes_0_read = &nodes_0_serialized[..];
4541 if let Err(msgs::DecodeError::InvalidValue) =
4542 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4543 default_config: UserConfig::default(),
4545 fee_estimator: &fee_estimator,
4546 chain_monitor: nodes[0].chain_monitor,
4547 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4549 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4551 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4554 let mut nodes_0_read = &nodes_0_serialized[..];
4555 let (_, nodes_0_deserialized_tmp) =
4556 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4557 default_config: UserConfig::default(),
4559 fee_estimator: &fee_estimator,
4560 chain_monitor: nodes[0].chain_monitor,
4561 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4563 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4565 nodes_0_deserialized = nodes_0_deserialized_tmp;
4566 assert!(nodes_0_read.is_empty());
4568 { // Channel close should result in a commitment tx
4569 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4570 assert_eq!(txn.len(), 1);
4571 check_spends!(txn[0], funding_tx);
4572 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4575 for monitor in node_0_monitors.drain(..) {
4576 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4577 check_added_monitors!(nodes[0], 1);
4579 nodes[0].node = &nodes_0_deserialized;
4580 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4582 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4583 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4584 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4585 //... and we can even still claim the payment!
4586 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4588 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4589 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4590 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4591 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4592 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4593 assert_eq!(msg_events.len(), 1);
4594 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4596 &ErrorAction::SendErrorMessage { ref msg } => {
4597 assert_eq!(msg.channel_id, channel_id);
4599 _ => panic!("Unexpected event!"),
4604 macro_rules! check_spendable_outputs {
4605 ($node: expr, $keysinterface: expr) => {
4607 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4608 let mut txn = Vec::new();
4609 let mut all_outputs = Vec::new();
4610 let secp_ctx = Secp256k1::new();
4611 for event in events.drain(..) {
4613 Event::SpendableOutputs { mut outputs } => {
4614 for outp in outputs.drain(..) {
4615 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4616 all_outputs.push(outp);
4619 _ => panic!("Unexpected event"),
4622 if all_outputs.len() > 1 {
4623 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) {
4633 fn test_claim_sizeable_push_msat() {
4634 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4635 let chanmon_cfgs = create_chanmon_cfgs(2);
4636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4638 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4640 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4641 nodes[1].node.force_close_channel(&chan.2).unwrap();
4642 check_closed_broadcast!(nodes[1], true);
4643 check_added_monitors!(nodes[1], 1);
4644 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4645 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4646 assert_eq!(node_txn.len(), 1);
4647 check_spends!(node_txn[0], chan.3);
4648 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
4650 mine_transaction(&nodes[1], &node_txn[0]);
4651 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4653 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4654 assert_eq!(spend_txn.len(), 1);
4655 assert_eq!(spend_txn[0].input.len(), 1);
4656 check_spends!(spend_txn[0], node_txn[0]);
4657 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4661 fn test_claim_on_remote_sizeable_push_msat() {
4662 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4663 // to_remote output is encumbered by a P2WPKH
4664 let chanmon_cfgs = create_chanmon_cfgs(2);
4665 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4666 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4667 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4669 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4670 nodes[0].node.force_close_channel(&chan.2).unwrap();
4671 check_closed_broadcast!(nodes[0], true);
4672 check_added_monitors!(nodes[0], 1);
4673 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4675 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4676 assert_eq!(node_txn.len(), 1);
4677 check_spends!(node_txn[0], chan.3);
4678 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
4680 mine_transaction(&nodes[1], &node_txn[0]);
4681 check_closed_broadcast!(nodes[1], true);
4682 check_added_monitors!(nodes[1], 1);
4683 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4684 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4686 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4687 assert_eq!(spend_txn.len(), 1);
4688 check_spends!(spend_txn[0], node_txn[0]);
4692 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4693 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4694 // to_remote output is encumbered by a P2WPKH
4696 let chanmon_cfgs = create_chanmon_cfgs(2);
4697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4699 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4701 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4702 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4703 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4704 assert_eq!(revoked_local_txn[0].input.len(), 1);
4705 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4707 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4708 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4709 check_closed_broadcast!(nodes[1], true);
4710 check_added_monitors!(nodes[1], 1);
4711 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4713 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4714 mine_transaction(&nodes[1], &node_txn[0]);
4715 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4717 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4718 assert_eq!(spend_txn.len(), 3);
4719 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4720 check_spends!(spend_txn[1], node_txn[0]);
4721 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4725 fn test_static_spendable_outputs_preimage_tx() {
4726 let chanmon_cfgs = create_chanmon_cfgs(2);
4727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4731 // Create some initial channels
4732 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4734 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4736 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4737 assert_eq!(commitment_tx[0].input.len(), 1);
4738 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4740 // Settle A's commitment tx on B's chain
4741 assert!(nodes[1].node.claim_funds(payment_preimage));
4742 check_added_monitors!(nodes[1], 1);
4743 mine_transaction(&nodes[1], &commitment_tx[0]);
4744 check_added_monitors!(nodes[1], 1);
4745 let events = nodes[1].node.get_and_clear_pending_msg_events();
4747 MessageSendEvent::UpdateHTLCs { .. } => {},
4748 _ => panic!("Unexpected event"),
4751 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4752 _ => panic!("Unexepected event"),
4755 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4756 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4757 assert_eq!(node_txn.len(), 3);
4758 check_spends!(node_txn[0], commitment_tx[0]);
4759 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4760 check_spends!(node_txn[1], chan_1.3);
4761 check_spends!(node_txn[2], node_txn[1]);
4763 mine_transaction(&nodes[1], &node_txn[0]);
4764 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4765 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4767 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4768 assert_eq!(spend_txn.len(), 1);
4769 check_spends!(spend_txn[0], node_txn[0]);
4773 fn test_static_spendable_outputs_timeout_tx() {
4774 let chanmon_cfgs = create_chanmon_cfgs(2);
4775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4777 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779 // Create some initial channels
4780 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4782 // Rebalance the network a bit by relaying one payment through all the channels ...
4783 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4785 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4787 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4788 assert_eq!(commitment_tx[0].input.len(), 1);
4789 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4791 // Settle A's commitment tx on B' chain
4792 mine_transaction(&nodes[1], &commitment_tx[0]);
4793 check_added_monitors!(nodes[1], 1);
4794 let events = nodes[1].node.get_and_clear_pending_msg_events();
4796 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4797 _ => panic!("Unexpected event"),
4799 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4801 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4802 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4803 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4804 check_spends!(node_txn[0], chan_1.3.clone());
4805 check_spends!(node_txn[1], commitment_tx[0].clone());
4806 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4808 mine_transaction(&nodes[1], &node_txn[1]);
4809 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4810 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4811 expect_payment_failed!(nodes[1], our_payment_hash, true);
4813 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4814 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4815 check_spends!(spend_txn[0], commitment_tx[0]);
4816 check_spends!(spend_txn[1], node_txn[1]);
4817 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4821 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4822 let chanmon_cfgs = create_chanmon_cfgs(2);
4823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4825 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4827 // Create some initial channels
4828 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4830 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4831 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4832 assert_eq!(revoked_local_txn[0].input.len(), 1);
4833 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4835 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4837 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4838 check_closed_broadcast!(nodes[1], true);
4839 check_added_monitors!(nodes[1], 1);
4840 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4842 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4843 assert_eq!(node_txn.len(), 2);
4844 assert_eq!(node_txn[0].input.len(), 2);
4845 check_spends!(node_txn[0], revoked_local_txn[0]);
4847 mine_transaction(&nodes[1], &node_txn[0]);
4848 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4850 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4851 assert_eq!(spend_txn.len(), 1);
4852 check_spends!(spend_txn[0], node_txn[0]);
4856 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4857 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4858 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4863 // Create some initial channels
4864 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4866 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4867 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4868 assert_eq!(revoked_local_txn[0].input.len(), 1);
4869 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4871 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4873 // A will generate HTLC-Timeout from revoked commitment tx
4874 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4875 check_closed_broadcast!(nodes[0], true);
4876 check_added_monitors!(nodes[0], 1);
4877 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4878 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4880 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4881 assert_eq!(revoked_htlc_txn.len(), 2);
4882 check_spends!(revoked_htlc_txn[0], chan_1.3);
4883 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4884 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4885 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4886 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4888 // B will generate justice tx from A's revoked commitment/HTLC tx
4889 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4891 check_closed_broadcast!(nodes[1], true);
4892 check_added_monitors!(nodes[1], 1);
4893 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4895 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4896 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4897 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4898 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4899 // transactions next...
4900 assert_eq!(node_txn[0].input.len(), 3);
4901 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4903 assert_eq!(node_txn[1].input.len(), 2);
4904 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4905 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4906 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4908 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4909 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4912 assert_eq!(node_txn[2].input.len(), 1);
4913 check_spends!(node_txn[2], chan_1.3);
4915 mine_transaction(&nodes[1], &node_txn[1]);
4916 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4918 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4919 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4920 assert_eq!(spend_txn.len(), 1);
4921 assert_eq!(spend_txn[0].input.len(), 1);
4922 check_spends!(spend_txn[0], node_txn[1]);
4926 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4927 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4928 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4929 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4930 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4931 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4933 // Create some initial channels
4934 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4936 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4937 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4938 assert_eq!(revoked_local_txn[0].input.len(), 1);
4939 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4941 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4942 assert_eq!(revoked_local_txn[0].output.len(), 2);
4944 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4946 // B will generate HTLC-Success from revoked commitment tx
4947 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4948 check_closed_broadcast!(nodes[1], true);
4949 check_added_monitors!(nodes[1], 1);
4950 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4951 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4953 assert_eq!(revoked_htlc_txn.len(), 2);
4954 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4955 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4956 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4958 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4959 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4960 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4962 // A will generate justice tx from B's revoked commitment/HTLC tx
4963 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4964 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4965 check_closed_broadcast!(nodes[0], true);
4966 check_added_monitors!(nodes[0], 1);
4967 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4969 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4970 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4972 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4973 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4974 // transactions next...
4975 assert_eq!(node_txn[0].input.len(), 2);
4976 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4977 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4978 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4980 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4981 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4984 assert_eq!(node_txn[1].input.len(), 1);
4985 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4987 check_spends!(node_txn[2], chan_1.3);
4989 mine_transaction(&nodes[0], &node_txn[1]);
4990 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4992 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4993 // didn't try to generate any new transactions.
4995 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4996 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4997 assert_eq!(spend_txn.len(), 3);
4998 assert_eq!(spend_txn[0].input.len(), 1);
4999 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5000 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5001 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5002 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5006 fn test_onchain_to_onchain_claim() {
5007 // Test that in case of channel closure, we detect the state of output and claim HTLC
5008 // on downstream peer's remote commitment tx.
5009 // First, have C claim an HTLC against its own latest commitment transaction.
5010 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5012 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5015 let chanmon_cfgs = create_chanmon_cfgs(3);
5016 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5017 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5018 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5020 // Create some initial channels
5021 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5022 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5024 // Ensure all nodes are at the same height
5025 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5026 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5027 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5028 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5030 // Rebalance the network a bit by relaying one payment through all the channels ...
5031 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5032 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5034 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5035 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5036 check_spends!(commitment_tx[0], chan_2.3);
5037 nodes[2].node.claim_funds(payment_preimage);
5038 check_added_monitors!(nodes[2], 1);
5039 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5040 assert!(updates.update_add_htlcs.is_empty());
5041 assert!(updates.update_fail_htlcs.is_empty());
5042 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5043 assert!(updates.update_fail_malformed_htlcs.is_empty());
5045 mine_transaction(&nodes[2], &commitment_tx[0]);
5046 check_closed_broadcast!(nodes[2], true);
5047 check_added_monitors!(nodes[2], 1);
5048 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5050 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5051 assert_eq!(c_txn.len(), 3);
5052 assert_eq!(c_txn[0], c_txn[2]);
5053 assert_eq!(commitment_tx[0], c_txn[1]);
5054 check_spends!(c_txn[1], chan_2.3);
5055 check_spends!(c_txn[2], c_txn[1]);
5056 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5057 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5058 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5059 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5061 // 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
5062 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5063 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5064 check_added_monitors!(nodes[1], 1);
5065 let events = nodes[1].node.get_and_clear_pending_events();
5066 assert_eq!(events.len(), 2);
5068 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5069 _ => panic!("Unexpected event"),
5072 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5073 assert_eq!(fee_earned_msat, Some(1000));
5074 assert_eq!(claim_from_onchain_tx, true);
5076 _ => panic!("Unexpected event"),
5079 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5080 // ChannelMonitor: claim tx
5081 assert_eq!(b_txn.len(), 1);
5082 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5085 check_added_monitors!(nodes[1], 1);
5086 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5087 assert_eq!(msg_events.len(), 3);
5088 match msg_events[0] {
5089 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5090 _ => panic!("Unexpected event"),
5092 match msg_events[1] {
5093 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5094 _ => panic!("Unexpected event"),
5096 match msg_events[2] {
5097 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, .. } } => {
5098 assert!(update_add_htlcs.is_empty());
5099 assert!(update_fail_htlcs.is_empty());
5100 assert_eq!(update_fulfill_htlcs.len(), 1);
5101 assert!(update_fail_malformed_htlcs.is_empty());
5102 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5104 _ => panic!("Unexpected event"),
5106 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5107 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5108 mine_transaction(&nodes[1], &commitment_tx[0]);
5109 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5110 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5111 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5112 assert_eq!(b_txn.len(), 3);
5113 check_spends!(b_txn[1], chan_1.3);
5114 check_spends!(b_txn[2], b_txn[1]);
5115 check_spends!(b_txn[0], commitment_tx[0]);
5116 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5117 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5118 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5120 check_closed_broadcast!(nodes[1], true);
5121 check_added_monitors!(nodes[1], 1);
5125 fn test_duplicate_payment_hash_one_failure_one_success() {
5126 // Topology : A --> B --> C --> D
5127 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5128 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5129 // we forward one of the payments onwards to D.
5130 let chanmon_cfgs = create_chanmon_cfgs(4);
5131 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5132 // When this test was written, the default base fee floated based on the HTLC count.
5133 // It is now fixed, so we simply set the fee to the expected value here.
5134 let mut config = test_default_channel_config();
5135 config.channel_options.forwarding_fee_base_msat = 196;
5136 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5137 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5138 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5140 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5141 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5142 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5144 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5145 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5146 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5147 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5148 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5150 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5152 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5153 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5154 // script push size limit so that the below script length checks match
5155 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5156 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
5157 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5158 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5160 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5161 assert_eq!(commitment_txn[0].input.len(), 1);
5162 check_spends!(commitment_txn[0], chan_2.3);
5164 mine_transaction(&nodes[1], &commitment_txn[0]);
5165 check_closed_broadcast!(nodes[1], true);
5166 check_added_monitors!(nodes[1], 1);
5167 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5168 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5170 let htlc_timeout_tx;
5171 { // Extract one of the two HTLC-Timeout transaction
5172 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5173 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5174 assert_eq!(node_txn.len(), 4);
5175 check_spends!(node_txn[0], chan_2.3);
5177 check_spends!(node_txn[1], commitment_txn[0]);
5178 assert_eq!(node_txn[1].input.len(), 1);
5179 check_spends!(node_txn[2], commitment_txn[0]);
5180 assert_eq!(node_txn[2].input.len(), 1);
5181 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5182 check_spends!(node_txn[3], commitment_txn[0]);
5183 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5185 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5186 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5187 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5188 htlc_timeout_tx = node_txn[1].clone();
5191 nodes[2].node.claim_funds(our_payment_preimage);
5192 mine_transaction(&nodes[2], &commitment_txn[0]);
5193 check_added_monitors!(nodes[2], 2);
5194 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5195 let events = nodes[2].node.get_and_clear_pending_msg_events();
5197 MessageSendEvent::UpdateHTLCs { .. } => {},
5198 _ => panic!("Unexpected event"),
5201 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5202 _ => panic!("Unexepected event"),
5204 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5205 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)
5206 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5207 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5208 assert_eq!(htlc_success_txn[0].input.len(), 1);
5209 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5210 assert_eq!(htlc_success_txn[1].input.len(), 1);
5211 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5212 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5213 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5214 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5215 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5216 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5218 mine_transaction(&nodes[1], &htlc_timeout_tx);
5219 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5220 expect_pending_htlcs_forwardable!(nodes[1]);
5221 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5222 assert!(htlc_updates.update_add_htlcs.is_empty());
5223 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5224 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5225 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5226 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5227 check_added_monitors!(nodes[1], 1);
5229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5230 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5232 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5234 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5236 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5237 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5238 // and nodes[2] fee) is rounded down and then claimed in full.
5239 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5240 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5241 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5242 assert!(updates.update_add_htlcs.is_empty());
5243 assert!(updates.update_fail_htlcs.is_empty());
5244 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5245 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5246 assert!(updates.update_fail_malformed_htlcs.is_empty());
5247 check_added_monitors!(nodes[1], 1);
5249 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5250 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5252 let events = nodes[0].node.get_and_clear_pending_events();
5254 Event::PaymentSent { ref payment_preimage } => {
5255 assert_eq!(*payment_preimage, our_payment_preimage);
5257 _ => panic!("Unexpected event"),
5262 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5263 let chanmon_cfgs = create_chanmon_cfgs(2);
5264 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5265 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5266 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5268 // Create some initial channels
5269 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5271 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5272 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5273 assert_eq!(local_txn.len(), 1);
5274 assert_eq!(local_txn[0].input.len(), 1);
5275 check_spends!(local_txn[0], chan_1.3);
5277 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5278 nodes[1].node.claim_funds(payment_preimage);
5279 check_added_monitors!(nodes[1], 1);
5280 mine_transaction(&nodes[1], &local_txn[0]);
5281 check_added_monitors!(nodes[1], 1);
5282 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5283 let events = nodes[1].node.get_and_clear_pending_msg_events();
5285 MessageSendEvent::UpdateHTLCs { .. } => {},
5286 _ => panic!("Unexpected event"),
5289 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5290 _ => panic!("Unexepected event"),
5293 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5294 assert_eq!(node_txn.len(), 3);
5295 assert_eq!(node_txn[0], node_txn[2]);
5296 assert_eq!(node_txn[1], local_txn[0]);
5297 assert_eq!(node_txn[0].input.len(), 1);
5298 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5299 check_spends!(node_txn[0], local_txn[0]);
5303 mine_transaction(&nodes[1], &node_tx);
5304 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5306 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5307 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5308 assert_eq!(spend_txn.len(), 1);
5309 assert_eq!(spend_txn[0].input.len(), 1);
5310 check_spends!(spend_txn[0], node_tx);
5311 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5314 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5315 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5316 // unrevoked commitment transaction.
5317 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5318 // a remote RAA before they could be failed backwards (and combinations thereof).
5319 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5320 // use the same payment hashes.
5321 // Thus, we use a six-node network:
5326 // And test where C fails back to A/B when D announces its latest commitment transaction
5327 let chanmon_cfgs = create_chanmon_cfgs(6);
5328 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5329 // When this test was written, the default base fee floated based on the HTLC count.
5330 // It is now fixed, so we simply set the fee to the expected value here.
5331 let mut config = test_default_channel_config();
5332 config.channel_options.forwarding_fee_base_msat = 196;
5333 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5334 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5335 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5336 let logger = test_utils::TestLogger::new();
5338 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5339 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5340 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5341 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5342 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5344 // Rebalance and check output sanity...
5345 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5346 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5347 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5349 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5351 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
5353 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
5354 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5355 let our_node_id = &nodes[1].node.get_our_node_id();
5356 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5358 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
5360 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
5362 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5364 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5365 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5367 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());
5369 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());
5372 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5374 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5375 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
5378 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
5380 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5381 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());
5383 // Double-check that six of the new HTLC were added
5384 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5385 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5386 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5387 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5389 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5390 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5391 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5392 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5393 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5394 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5395 check_added_monitors!(nodes[4], 0);
5396 expect_pending_htlcs_forwardable!(nodes[4]);
5397 check_added_monitors!(nodes[4], 1);
5399 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5400 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5401 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5402 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5403 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5404 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5406 // Fail 3rd below-dust and 7th above-dust HTLCs
5407 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5408 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5409 check_added_monitors!(nodes[5], 0);
5410 expect_pending_htlcs_forwardable!(nodes[5]);
5411 check_added_monitors!(nodes[5], 1);
5413 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5414 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5415 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5416 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5418 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5420 expect_pending_htlcs_forwardable!(nodes[3]);
5421 check_added_monitors!(nodes[3], 1);
5422 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5423 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5424 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5425 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5426 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5427 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5428 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5429 if deliver_last_raa {
5430 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5432 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5435 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5436 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5437 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5438 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5440 // We now broadcast the latest commitment transaction, which *should* result in failures for
5441 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5442 // the non-broadcast above-dust HTLCs.
5444 // Alternatively, we may broadcast the previous commitment transaction, which should only
5445 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5446 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5448 if announce_latest {
5449 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5451 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5453 let events = nodes[2].node.get_and_clear_pending_events();
5454 let close_event = if deliver_last_raa {
5455 assert_eq!(events.len(), 2);
5458 assert_eq!(events.len(), 1);
5462 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5463 _ => panic!("Unexpected event"),
5466 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5467 check_closed_broadcast!(nodes[2], true);
5468 if deliver_last_raa {
5469 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5471 expect_pending_htlcs_forwardable!(nodes[2]);
5473 check_added_monitors!(nodes[2], 3);
5475 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5476 assert_eq!(cs_msgs.len(), 2);
5477 let mut a_done = false;
5478 for msg in cs_msgs {
5480 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5481 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5482 // should be failed-backwards here.
5483 let target = if *node_id == nodes[0].node.get_our_node_id() {
5484 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5485 for htlc in &updates.update_fail_htlcs {
5486 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 });
5488 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5493 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5494 for htlc in &updates.update_fail_htlcs {
5495 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5497 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5498 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5501 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5502 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5503 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5504 if announce_latest {
5505 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5506 if *node_id == nodes[0].node.get_our_node_id() {
5507 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5510 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5512 _ => panic!("Unexpected event"),
5516 let as_events = nodes[0].node.get_and_clear_pending_events();
5517 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5518 let mut as_failds = HashSet::new();
5519 let mut as_updates = 0;
5520 for event in as_events.iter() {
5521 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5522 assert!(as_failds.insert(*payment_hash));
5523 if *payment_hash != payment_hash_2 {
5524 assert_eq!(*rejected_by_dest, deliver_last_raa);
5526 assert!(!rejected_by_dest);
5528 if network_update.is_some() {
5531 } else { panic!("Unexpected event"); }
5533 assert!(as_failds.contains(&payment_hash_1));
5534 assert!(as_failds.contains(&payment_hash_2));
5535 if announce_latest {
5536 assert!(as_failds.contains(&payment_hash_3));
5537 assert!(as_failds.contains(&payment_hash_5));
5539 assert!(as_failds.contains(&payment_hash_6));
5541 let bs_events = nodes[1].node.get_and_clear_pending_events();
5542 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5543 let mut bs_failds = HashSet::new();
5544 let mut bs_updates = 0;
5545 for event in bs_events.iter() {
5546 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5547 assert!(bs_failds.insert(*payment_hash));
5548 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5549 assert_eq!(*rejected_by_dest, deliver_last_raa);
5551 assert!(!rejected_by_dest);
5553 if network_update.is_some() {
5556 } else { panic!("Unexpected event"); }
5558 assert!(bs_failds.contains(&payment_hash_1));
5559 assert!(bs_failds.contains(&payment_hash_2));
5560 if announce_latest {
5561 assert!(bs_failds.contains(&payment_hash_4));
5563 assert!(bs_failds.contains(&payment_hash_5));
5565 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5566 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5567 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5568 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5569 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5570 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5574 fn test_fail_backwards_latest_remote_announce_a() {
5575 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5579 fn test_fail_backwards_latest_remote_announce_b() {
5580 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5584 fn test_fail_backwards_previous_remote_announce() {
5585 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5586 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5587 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5591 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5592 let chanmon_cfgs = create_chanmon_cfgs(2);
5593 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5594 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5595 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5597 // Create some initial channels
5598 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5600 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5601 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5602 assert_eq!(local_txn[0].input.len(), 1);
5603 check_spends!(local_txn[0], chan_1.3);
5605 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5606 mine_transaction(&nodes[0], &local_txn[0]);
5607 check_closed_broadcast!(nodes[0], true);
5608 check_added_monitors!(nodes[0], 1);
5609 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5610 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5612 let htlc_timeout = {
5613 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5614 assert_eq!(node_txn.len(), 2);
5615 check_spends!(node_txn[0], chan_1.3);
5616 assert_eq!(node_txn[1].input.len(), 1);
5617 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5618 check_spends!(node_txn[1], local_txn[0]);
5622 mine_transaction(&nodes[0], &htlc_timeout);
5623 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5624 expect_payment_failed!(nodes[0], our_payment_hash, true);
5626 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5627 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5628 assert_eq!(spend_txn.len(), 3);
5629 check_spends!(spend_txn[0], local_txn[0]);
5630 assert_eq!(spend_txn[1].input.len(), 1);
5631 check_spends!(spend_txn[1], htlc_timeout);
5632 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5633 assert_eq!(spend_txn[2].input.len(), 2);
5634 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5635 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5636 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5640 fn test_key_derivation_params() {
5641 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5642 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5643 // let us re-derive the channel key set to then derive a delayed_payment_key.
5645 let chanmon_cfgs = create_chanmon_cfgs(3);
5647 // We manually create the node configuration to backup the seed.
5648 let seed = [42; 32];
5649 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5650 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);
5651 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() };
5652 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5653 node_cfgs.remove(0);
5654 node_cfgs.insert(0, node);
5656 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5657 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5659 // Create some initial channels
5660 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5662 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5663 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5664 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5666 // Ensure all nodes are at the same height
5667 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5668 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5669 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5670 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5672 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5673 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5674 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5675 assert_eq!(local_txn_1[0].input.len(), 1);
5676 check_spends!(local_txn_1[0], chan_1.3);
5678 // We check funding pubkey are unique
5679 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]));
5680 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]));
5681 if from_0_funding_key_0 == from_1_funding_key_0
5682 || from_0_funding_key_0 == from_1_funding_key_1
5683 || from_0_funding_key_1 == from_1_funding_key_0
5684 || from_0_funding_key_1 == from_1_funding_key_1 {
5685 panic!("Funding pubkeys aren't unique");
5688 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5689 mine_transaction(&nodes[0], &local_txn_1[0]);
5690 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5691 check_closed_broadcast!(nodes[0], true);
5692 check_added_monitors!(nodes[0], 1);
5693 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5695 let htlc_timeout = {
5696 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5697 assert_eq!(node_txn[1].input.len(), 1);
5698 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5699 check_spends!(node_txn[1], local_txn_1[0]);
5703 mine_transaction(&nodes[0], &htlc_timeout);
5704 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5705 expect_payment_failed!(nodes[0], our_payment_hash, true);
5707 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5708 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5709 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5710 assert_eq!(spend_txn.len(), 3);
5711 check_spends!(spend_txn[0], local_txn_1[0]);
5712 assert_eq!(spend_txn[1].input.len(), 1);
5713 check_spends!(spend_txn[1], htlc_timeout);
5714 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5715 assert_eq!(spend_txn[2].input.len(), 2);
5716 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5717 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5718 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5722 fn test_static_output_closing_tx() {
5723 let chanmon_cfgs = create_chanmon_cfgs(2);
5724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5726 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5728 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5730 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5731 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5733 mine_transaction(&nodes[0], &closing_tx);
5734 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5735 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5737 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5738 assert_eq!(spend_txn.len(), 1);
5739 check_spends!(spend_txn[0], closing_tx);
5741 mine_transaction(&nodes[1], &closing_tx);
5742 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5743 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5745 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5746 assert_eq!(spend_txn.len(), 1);
5747 check_spends!(spend_txn[0], closing_tx);
5750 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5751 let chanmon_cfgs = create_chanmon_cfgs(2);
5752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5757 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5759 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5760 // present in B's local commitment transaction, but none of A's commitment transactions.
5761 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5762 check_added_monitors!(nodes[1], 1);
5764 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5765 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5766 let events = nodes[0].node.get_and_clear_pending_events();
5767 assert_eq!(events.len(), 1);
5769 Event::PaymentSent { payment_preimage } => {
5770 assert_eq!(payment_preimage, our_payment_preimage);
5772 _ => panic!("Unexpected event"),
5775 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5776 check_added_monitors!(nodes[0], 1);
5777 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5778 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5779 check_added_monitors!(nodes[1], 1);
5781 let starting_block = nodes[1].best_block_info();
5782 let mut block = Block {
5783 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5786 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5787 connect_block(&nodes[1], &block);
5788 block.header.prev_blockhash = block.block_hash();
5790 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5791 check_closed_broadcast!(nodes[1], true);
5792 check_added_monitors!(nodes[1], 1);
5793 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5796 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5797 let chanmon_cfgs = create_chanmon_cfgs(2);
5798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5800 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5801 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802 let logger = test_utils::TestLogger::new();
5804 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
5805 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5806 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5807 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5808 check_added_monitors!(nodes[0], 1);
5810 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5812 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5813 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5814 // to "time out" the HTLC.
5816 let starting_block = nodes[1].best_block_info();
5817 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5819 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5820 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5821 header.prev_blockhash = header.block_hash();
5823 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5824 check_closed_broadcast!(nodes[0], true);
5825 check_added_monitors!(nodes[0], 1);
5826 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5829 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5830 let chanmon_cfgs = create_chanmon_cfgs(3);
5831 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5832 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5833 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5834 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5836 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5837 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5838 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5839 // actually revoked.
5840 let htlc_value = if use_dust { 50000 } else { 3000000 };
5841 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5842 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5843 expect_pending_htlcs_forwardable!(nodes[1]);
5844 check_added_monitors!(nodes[1], 1);
5846 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5847 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5848 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5849 check_added_monitors!(nodes[0], 1);
5850 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5851 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5852 check_added_monitors!(nodes[1], 1);
5853 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5854 check_added_monitors!(nodes[1], 1);
5855 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5857 if check_revoke_no_close {
5858 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5859 check_added_monitors!(nodes[0], 1);
5862 let starting_block = nodes[1].best_block_info();
5863 let mut block = Block {
5864 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5867 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5868 connect_block(&nodes[0], &block);
5869 block.header.prev_blockhash = block.block_hash();
5871 if !check_revoke_no_close {
5872 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5873 check_closed_broadcast!(nodes[0], true);
5874 check_added_monitors!(nodes[0], 1);
5875 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5877 expect_payment_failed!(nodes[0], our_payment_hash, true);
5881 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5882 // There are only a few cases to test here:
5883 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5884 // broadcastable commitment transactions result in channel closure,
5885 // * its included in an unrevoked-but-previous remote commitment transaction,
5886 // * its included in the latest remote or local commitment transactions.
5887 // We test each of the three possible commitment transactions individually and use both dust and
5889 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5890 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5891 // tested for at least one of the cases in other tests.
5893 fn htlc_claim_single_commitment_only_a() {
5894 do_htlc_claim_local_commitment_only(true);
5895 do_htlc_claim_local_commitment_only(false);
5897 do_htlc_claim_current_remote_commitment_only(true);
5898 do_htlc_claim_current_remote_commitment_only(false);
5902 fn htlc_claim_single_commitment_only_b() {
5903 do_htlc_claim_previous_remote_commitment_only(true, false);
5904 do_htlc_claim_previous_remote_commitment_only(false, false);
5905 do_htlc_claim_previous_remote_commitment_only(true, true);
5906 do_htlc_claim_previous_remote_commitment_only(false, true);
5911 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5912 let chanmon_cfgs = create_chanmon_cfgs(2);
5913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5916 //Force duplicate channel ids
5917 for node in nodes.iter() {
5918 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5921 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5922 let channel_value_satoshis=10000;
5923 let push_msat=10001;
5924 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5925 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5926 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5928 //Create a second channel with a channel_id collision
5929 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5933 fn bolt2_open_channel_sending_node_checks_part2() {
5934 let chanmon_cfgs = create_chanmon_cfgs(2);
5935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5939 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5940 let channel_value_satoshis=2^24;
5941 let push_msat=10001;
5942 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5944 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5945 let channel_value_satoshis=10000;
5946 // Test when push_msat is equal to 1000 * funding_satoshis.
5947 let push_msat=1000*channel_value_satoshis+1;
5948 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5950 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5951 let channel_value_satoshis=10000;
5952 let push_msat=10001;
5953 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
5954 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5955 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5957 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5958 // 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
5959 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5961 // 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.
5962 assert!(BREAKDOWN_TIMEOUT>0);
5963 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5965 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5966 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5967 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5969 // 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.
5970 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5971 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5972 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5973 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5974 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5978 fn bolt2_open_channel_sane_dust_limit() {
5979 let chanmon_cfgs = create_chanmon_cfgs(2);
5980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5984 let channel_value_satoshis=1000000;
5985 let push_msat=10001;
5986 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5987 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5988 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5989 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5991 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5992 let events = nodes[1].node.get_and_clear_pending_msg_events();
5993 let err_msg = match events[0] {
5994 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5997 _ => panic!("Unexpected event"),
5999 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6002 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6003 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6004 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6005 // is no longer affordable once it's freed.
6007 fn test_fail_holding_cell_htlc_upon_free() {
6008 let chanmon_cfgs = create_chanmon_cfgs(2);
6009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6011 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6012 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6013 let logger = test_utils::TestLogger::new();
6015 // First nodes[0] generates an update_fee, setting the channel's
6016 // pending_update_fee.
6018 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6019 *feerate_lock += 20;
6021 nodes[0].node.timer_tick_occurred();
6022 check_added_monitors!(nodes[0], 1);
6024 let events = nodes[0].node.get_and_clear_pending_msg_events();
6025 assert_eq!(events.len(), 1);
6026 let (update_msg, commitment_signed) = match events[0] {
6027 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6028 (update_fee.as_ref(), commitment_signed)
6030 _ => panic!("Unexpected event"),
6033 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6035 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6036 let channel_reserve = chan_stat.channel_reserve_msat;
6037 let feerate = get_feerate!(nodes[0], chan.2);
6039 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6040 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6041 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6042 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6043 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6045 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6046 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6047 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6048 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6050 // Flush the pending fee update.
6051 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6052 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6053 check_added_monitors!(nodes[1], 1);
6054 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6055 check_added_monitors!(nodes[0], 1);
6057 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6058 // HTLC, but now that the fee has been raised the payment will now fail, causing
6059 // us to surface its failure to the user.
6060 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6061 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6062 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);
6063 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 {}",
6064 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6065 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6067 // Check that the payment failed to be sent out.
6068 let events = nodes[0].node.get_and_clear_pending_events();
6069 assert_eq!(events.len(), 1);
6071 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref error_code, ref error_data, ref all_paths_failed, path: _ } => {
6072 assert_eq!(our_payment_hash.clone(), *payment_hash);
6073 assert_eq!(*rejected_by_dest, false);
6074 assert_eq!(*all_paths_failed, true);
6075 assert_eq!(*network_update, None);
6076 assert_eq!(*error_code, None);
6077 assert_eq!(*error_data, None);
6079 _ => panic!("Unexpected event"),
6083 // Test that if multiple HTLCs are released from the holding cell and one is
6084 // valid but the other is no longer valid upon release, the valid HTLC can be
6085 // successfully completed while the other one fails as expected.
6087 fn test_free_and_fail_holding_cell_htlcs() {
6088 let chanmon_cfgs = create_chanmon_cfgs(2);
6089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6091 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6092 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6093 let logger = test_utils::TestLogger::new();
6095 // First nodes[0] generates an update_fee, setting the channel's
6096 // pending_update_fee.
6098 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6099 *feerate_lock += 200;
6101 nodes[0].node.timer_tick_occurred();
6102 check_added_monitors!(nodes[0], 1);
6104 let events = nodes[0].node.get_and_clear_pending_msg_events();
6105 assert_eq!(events.len(), 1);
6106 let (update_msg, commitment_signed) = match events[0] {
6107 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6108 (update_fee.as_ref(), commitment_signed)
6110 _ => panic!("Unexpected event"),
6113 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6115 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6116 let channel_reserve = chan_stat.channel_reserve_msat;
6117 let feerate = get_feerate!(nodes[0], chan.2);
6119 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6120 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6122 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6123 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6124 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6125 let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6126 let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6128 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6129 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6130 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6131 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6132 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6133 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6134 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6136 // Flush the pending fee update.
6137 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6138 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6139 check_added_monitors!(nodes[1], 1);
6140 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6141 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6142 check_added_monitors!(nodes[0], 2);
6144 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6145 // but now that the fee has been raised the second payment will now fail, causing us
6146 // to surface its failure to the user. The first payment should succeed.
6147 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6148 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6149 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);
6150 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 {}",
6151 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6152 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6154 // Check that the second payment failed to be sent out.
6155 let events = nodes[0].node.get_and_clear_pending_events();
6156 assert_eq!(events.len(), 1);
6158 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref error_code, ref error_data, ref all_paths_failed, path: _ } => {
6159 assert_eq!(payment_hash_2.clone(), *payment_hash);
6160 assert_eq!(*rejected_by_dest, false);
6161 assert_eq!(*all_paths_failed, true);
6162 assert_eq!(*network_update, None);
6163 assert_eq!(*error_code, None);
6164 assert_eq!(*error_data, None);
6166 _ => panic!("Unexpected event"),
6169 // Complete the first payment and the RAA from the fee update.
6170 let (payment_event, send_raa_event) = {
6171 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6172 assert_eq!(msgs.len(), 2);
6173 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6175 let raa = match send_raa_event {
6176 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6177 _ => panic!("Unexpected event"),
6179 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6180 check_added_monitors!(nodes[1], 1);
6181 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6182 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6183 let events = nodes[1].node.get_and_clear_pending_events();
6184 assert_eq!(events.len(), 1);
6186 Event::PendingHTLCsForwardable { .. } => {},
6187 _ => panic!("Unexpected event"),
6189 nodes[1].node.process_pending_htlc_forwards();
6190 let events = nodes[1].node.get_and_clear_pending_events();
6191 assert_eq!(events.len(), 1);
6193 Event::PaymentReceived { .. } => {},
6194 _ => panic!("Unexpected event"),
6196 nodes[1].node.claim_funds(payment_preimage_1);
6197 check_added_monitors!(nodes[1], 1);
6198 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6199 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6200 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6201 let events = nodes[0].node.get_and_clear_pending_events();
6202 assert_eq!(events.len(), 1);
6204 Event::PaymentSent { ref payment_preimage } => {
6205 assert_eq!(*payment_preimage, payment_preimage_1);
6207 _ => panic!("Unexpected event"),
6211 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6212 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6213 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6216 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6217 let chanmon_cfgs = create_chanmon_cfgs(3);
6218 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6219 // When this test was written, the default base fee floated based on the HTLC count.
6220 // It is now fixed, so we simply set the fee to the expected value here.
6221 let mut config = test_default_channel_config();
6222 config.channel_options.forwarding_fee_base_msat = 196;
6223 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6224 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6225 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6226 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6227 let logger = test_utils::TestLogger::new();
6229 // First nodes[1] generates an update_fee, setting the channel's
6230 // pending_update_fee.
6232 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6233 *feerate_lock += 20;
6235 nodes[1].node.timer_tick_occurred();
6236 check_added_monitors!(nodes[1], 1);
6238 let events = nodes[1].node.get_and_clear_pending_msg_events();
6239 assert_eq!(events.len(), 1);
6240 let (update_msg, commitment_signed) = match events[0] {
6241 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6242 (update_fee.as_ref(), commitment_signed)
6244 _ => panic!("Unexpected event"),
6247 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6249 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6250 let channel_reserve = chan_stat.channel_reserve_msat;
6251 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6253 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6255 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6256 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6257 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6258 let payment_event = {
6259 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6260 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6261 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6262 check_added_monitors!(nodes[0], 1);
6264 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6265 assert_eq!(events.len(), 1);
6267 SendEvent::from_event(events.remove(0))
6269 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6270 check_added_monitors!(nodes[1], 0);
6271 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6272 expect_pending_htlcs_forwardable!(nodes[1]);
6274 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6275 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6277 // Flush the pending fee update.
6278 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6279 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6280 check_added_monitors!(nodes[2], 1);
6281 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6282 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6283 check_added_monitors!(nodes[1], 2);
6285 // A final RAA message is generated to finalize the fee update.
6286 let events = nodes[1].node.get_and_clear_pending_msg_events();
6287 assert_eq!(events.len(), 1);
6289 let raa_msg = match &events[0] {
6290 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6293 _ => panic!("Unexpected event"),
6296 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6297 check_added_monitors!(nodes[2], 1);
6298 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6300 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6301 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6302 assert_eq!(process_htlc_forwards_event.len(), 1);
6303 match &process_htlc_forwards_event[0] {
6304 &Event::PendingHTLCsForwardable { .. } => {},
6305 _ => panic!("Unexpected event"),
6308 // In response, we call ChannelManager's process_pending_htlc_forwards
6309 nodes[1].node.process_pending_htlc_forwards();
6310 check_added_monitors!(nodes[1], 1);
6312 // This causes the HTLC to be failed backwards.
6313 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6314 assert_eq!(fail_event.len(), 1);
6315 let (fail_msg, commitment_signed) = match &fail_event[0] {
6316 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6317 assert_eq!(updates.update_add_htlcs.len(), 0);
6318 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6319 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6320 assert_eq!(updates.update_fail_htlcs.len(), 1);
6321 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6323 _ => panic!("Unexpected event"),
6326 // Pass the failure messages back to nodes[0].
6327 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6328 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6330 // Complete the HTLC failure+removal process.
6331 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6332 check_added_monitors!(nodes[0], 1);
6333 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6334 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6335 check_added_monitors!(nodes[1], 2);
6336 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6337 assert_eq!(final_raa_event.len(), 1);
6338 let raa = match &final_raa_event[0] {
6339 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6340 _ => panic!("Unexpected event"),
6342 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6343 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6344 check_added_monitors!(nodes[0], 1);
6347 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6348 // 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.
6349 //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.
6352 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6353 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6354 let chanmon_cfgs = create_chanmon_cfgs(2);
6355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6357 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6358 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6360 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6361 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6362 let logger = test_utils::TestLogger::new();
6363 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6364 route.paths[0][0].fee_msat = 100;
6366 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6367 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6368 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6369 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6373 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6374 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6375 let chanmon_cfgs = create_chanmon_cfgs(2);
6376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6378 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6379 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6380 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6382 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6383 let logger = test_utils::TestLogger::new();
6384 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6385 route.paths[0][0].fee_msat = 0;
6386 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6387 assert_eq!(err, "Cannot send 0-msat HTLC"));
6389 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6390 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6394 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6395 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6396 let chanmon_cfgs = create_chanmon_cfgs(2);
6397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6399 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6400 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6402 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6403 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6404 let logger = test_utils::TestLogger::new();
6405 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6406 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6407 check_added_monitors!(nodes[0], 1);
6408 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6409 updates.update_add_htlcs[0].amount_msat = 0;
6411 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6412 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6413 check_closed_broadcast!(nodes[1], true).unwrap();
6414 check_added_monitors!(nodes[1], 1);
6415 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6419 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6420 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6421 //It is enforced when constructing a route.
6422 let chanmon_cfgs = create_chanmon_cfgs(2);
6423 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6427 let logger = test_utils::TestLogger::new();
6429 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6431 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6432 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000000, 500000001, &logger).unwrap();
6433 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6434 assert_eq!(err, &"Channel CLTV overflowed?"));
6438 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6439 //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.
6440 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6441 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6442 let chanmon_cfgs = create_chanmon_cfgs(2);
6443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6445 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6446 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6447 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6449 let logger = test_utils::TestLogger::new();
6450 for i in 0..max_accepted_htlcs {
6451 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6452 let payment_event = {
6453 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6454 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, 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);
6458 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6459 assert_eq!(events.len(), 1);
6460 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6461 assert_eq!(htlcs[0].htlc_id, i);
6465 SendEvent::from_event(events.remove(0))
6467 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6468 check_added_monitors!(nodes[1], 0);
6469 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6471 expect_pending_htlcs_forwardable!(nodes[1]);
6472 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6474 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6475 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6476 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6477 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6478 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6480 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6481 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6485 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6486 //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.
6487 let chanmon_cfgs = create_chanmon_cfgs(2);
6488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6490 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6491 let channel_value = 100000;
6492 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6493 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6495 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6497 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6498 // Manually create a route over our max in flight (which our router normally automatically
6500 let route = Route { paths: vec![vec![RouteHop {
6501 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6502 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6503 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6505 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6506 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)));
6508 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6509 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);
6511 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6514 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6516 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6517 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6518 let chanmon_cfgs = create_chanmon_cfgs(2);
6519 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6520 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6521 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6522 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6523 let htlc_minimum_msat: u64;
6525 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6526 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6527 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6530 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6531 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6532 let logger = test_utils::TestLogger::new();
6533 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6534 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6535 check_added_monitors!(nodes[0], 1);
6536 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6537 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6538 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6539 assert!(nodes[1].node.list_channels().is_empty());
6540 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6541 assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6542 check_added_monitors!(nodes[1], 1);
6543 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6547 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6548 //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
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, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6554 let logger = test_utils::TestLogger::new();
6556 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6557 let channel_reserve = chan_stat.channel_reserve_msat;
6558 let feerate = get_feerate!(nodes[0], chan.2);
6559 // The 2* and +1 are for the fee spike reserve.
6560 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6562 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6563 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6564 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6565 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6566 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6567 check_added_monitors!(nodes[0], 1);
6568 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6570 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6571 // at this time channel-initiatee receivers are not required to enforce that senders
6572 // respect the fee_spike_reserve.
6573 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6574 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6576 assert!(nodes[1].node.list_channels().is_empty());
6577 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6578 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6579 check_added_monitors!(nodes[1], 1);
6580 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6584 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6585 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6586 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6587 let chanmon_cfgs = create_chanmon_cfgs(2);
6588 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6589 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6590 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6591 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6592 let logger = test_utils::TestLogger::new();
6594 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6595 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6597 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6598 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6600 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6601 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6602 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6603 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6605 let mut msg = msgs::UpdateAddHTLC {
6609 payment_hash: our_payment_hash,
6610 cltv_expiry: htlc_cltv,
6611 onion_routing_packet: onion_packet.clone(),
6614 for i in 0..super::channel::OUR_MAX_HTLCS {
6615 msg.htlc_id = i as u64;
6616 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6618 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6619 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6621 assert!(nodes[1].node.list_channels().is_empty());
6622 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6623 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6624 check_added_monitors!(nodes[1], 1);
6625 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6629 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6630 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6631 let chanmon_cfgs = create_chanmon_cfgs(2);
6632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6634 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6635 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6636 let logger = test_utils::TestLogger::new();
6638 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6639 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6640 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6641 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6642 check_added_monitors!(nodes[0], 1);
6643 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6644 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6645 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6647 assert!(nodes[1].node.list_channels().is_empty());
6648 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6649 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6650 check_added_monitors!(nodes[1], 1);
6651 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6655 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6656 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6657 let chanmon_cfgs = create_chanmon_cfgs(2);
6658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6660 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6661 let logger = test_utils::TestLogger::new();
6663 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6664 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6665 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6666 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6667 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6668 check_added_monitors!(nodes[0], 1);
6669 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6670 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6671 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673 assert!(nodes[1].node.list_channels().is_empty());
6674 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6675 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6676 check_added_monitors!(nodes[1], 1);
6677 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6681 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6682 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6683 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6684 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6685 let chanmon_cfgs = create_chanmon_cfgs(2);
6686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689 let logger = test_utils::TestLogger::new();
6691 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6692 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6693 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6694 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6695 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6696 check_added_monitors!(nodes[0], 1);
6697 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6698 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6700 //Disconnect and Reconnect
6701 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6702 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6703 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6704 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6705 assert_eq!(reestablish_1.len(), 1);
6706 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6707 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6708 assert_eq!(reestablish_2.len(), 1);
6709 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6710 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6711 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6712 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6715 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6716 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6717 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6718 check_added_monitors!(nodes[1], 1);
6719 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6721 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6723 assert!(nodes[1].node.list_channels().is_empty());
6724 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6725 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6726 check_added_monitors!(nodes[1], 1);
6727 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6731 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6732 //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.
6734 let chanmon_cfgs = create_chanmon_cfgs(2);
6735 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6736 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6737 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6738 let logger = test_utils::TestLogger::new();
6739 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6740 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6741 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6742 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6743 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6745 check_added_monitors!(nodes[0], 1);
6746 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6747 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6749 let update_msg = msgs::UpdateFulfillHTLC{
6752 payment_preimage: our_payment_preimage,
6755 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6757 assert!(nodes[0].node.list_channels().is_empty());
6758 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6759 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()));
6760 check_added_monitors!(nodes[0], 1);
6761 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6765 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6766 //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.
6768 let chanmon_cfgs = create_chanmon_cfgs(2);
6769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6771 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6772 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6773 let logger = test_utils::TestLogger::new();
6775 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6776 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6777 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6778 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6779 check_added_monitors!(nodes[0], 1);
6780 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6781 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6783 let update_msg = msgs::UpdateFailHTLC{
6786 reason: msgs::OnionErrorPacket { data: Vec::new()},
6789 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6791 assert!(nodes[0].node.list_channels().is_empty());
6792 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6793 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()));
6794 check_added_monitors!(nodes[0], 1);
6795 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6799 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6800 //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.
6802 let chanmon_cfgs = create_chanmon_cfgs(2);
6803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6805 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6806 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6807 let logger = test_utils::TestLogger::new();
6809 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6810 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6811 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6812 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6813 check_added_monitors!(nodes[0], 1);
6814 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6815 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6816 let update_msg = msgs::UpdateFailMalformedHTLC{
6819 sha256_of_onion: [1; 32],
6820 failure_code: 0x8000,
6823 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6825 assert!(nodes[0].node.list_channels().is_empty());
6826 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6827 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()));
6828 check_added_monitors!(nodes[0], 1);
6829 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6833 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6834 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6836 let chanmon_cfgs = create_chanmon_cfgs(2);
6837 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6838 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6839 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6840 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6842 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6844 nodes[1].node.claim_funds(our_payment_preimage);
6845 check_added_monitors!(nodes[1], 1);
6847 let events = nodes[1].node.get_and_clear_pending_msg_events();
6848 assert_eq!(events.len(), 1);
6849 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6851 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, .. } } => {
6852 assert!(update_add_htlcs.is_empty());
6853 assert_eq!(update_fulfill_htlcs.len(), 1);
6854 assert!(update_fail_htlcs.is_empty());
6855 assert!(update_fail_malformed_htlcs.is_empty());
6856 assert!(update_fee.is_none());
6857 update_fulfill_htlcs[0].clone()
6859 _ => panic!("Unexpected event"),
6863 update_fulfill_msg.htlc_id = 1;
6865 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6867 assert!(nodes[0].node.list_channels().is_empty());
6868 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6869 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6870 check_added_monitors!(nodes[0], 1);
6871 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6875 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6876 //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.
6878 let chanmon_cfgs = create_chanmon_cfgs(2);
6879 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6880 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6881 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6882 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6884 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6886 nodes[1].node.claim_funds(our_payment_preimage);
6887 check_added_monitors!(nodes[1], 1);
6889 let events = nodes[1].node.get_and_clear_pending_msg_events();
6890 assert_eq!(events.len(), 1);
6891 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6893 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, .. } } => {
6894 assert!(update_add_htlcs.is_empty());
6895 assert_eq!(update_fulfill_htlcs.len(), 1);
6896 assert!(update_fail_htlcs.is_empty());
6897 assert!(update_fail_malformed_htlcs.is_empty());
6898 assert!(update_fee.is_none());
6899 update_fulfill_htlcs[0].clone()
6901 _ => panic!("Unexpected event"),
6905 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6907 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6909 assert!(nodes[0].node.list_channels().is_empty());
6910 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6911 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6912 check_added_monitors!(nodes[0], 1);
6913 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6917 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6918 //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.
6920 let chanmon_cfgs = create_chanmon_cfgs(2);
6921 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6922 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6923 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6924 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6925 let logger = test_utils::TestLogger::new();
6927 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6928 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6929 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6930 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6931 check_added_monitors!(nodes[0], 1);
6933 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6934 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6936 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6937 check_added_monitors!(nodes[1], 0);
6938 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6940 let events = nodes[1].node.get_and_clear_pending_msg_events();
6942 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6944 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6945 assert!(update_add_htlcs.is_empty());
6946 assert!(update_fulfill_htlcs.is_empty());
6947 assert!(update_fail_htlcs.is_empty());
6948 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6949 assert!(update_fee.is_none());
6950 update_fail_malformed_htlcs[0].clone()
6952 _ => panic!("Unexpected event"),
6955 update_msg.failure_code &= !0x8000;
6956 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6958 assert!(nodes[0].node.list_channels().is_empty());
6959 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6960 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6961 check_added_monitors!(nodes[0], 1);
6962 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6966 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6967 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6968 // * 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.
6970 let chanmon_cfgs = create_chanmon_cfgs(3);
6971 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6972 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6973 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6974 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6975 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6976 let logger = test_utils::TestLogger::new();
6978 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6981 let mut payment_event = {
6982 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6983 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6984 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6985 check_added_monitors!(nodes[0], 1);
6986 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6987 assert_eq!(events.len(), 1);
6988 SendEvent::from_event(events.remove(0))
6990 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6991 check_added_monitors!(nodes[1], 0);
6992 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6993 expect_pending_htlcs_forwardable!(nodes[1]);
6994 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6995 assert_eq!(events_2.len(), 1);
6996 check_added_monitors!(nodes[1], 1);
6997 payment_event = SendEvent::from_event(events_2.remove(0));
6998 assert_eq!(payment_event.msgs.len(), 1);
7001 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7002 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7003 check_added_monitors!(nodes[2], 0);
7004 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7006 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7007 assert_eq!(events_3.len(), 1);
7008 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7010 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 } } => {
7011 assert!(update_add_htlcs.is_empty());
7012 assert!(update_fulfill_htlcs.is_empty());
7013 assert!(update_fail_htlcs.is_empty());
7014 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7015 assert!(update_fee.is_none());
7016 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7018 _ => panic!("Unexpected event"),
7022 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7024 check_added_monitors!(nodes[1], 0);
7025 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7026 expect_pending_htlcs_forwardable!(nodes[1]);
7027 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7028 assert_eq!(events_4.len(), 1);
7030 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7032 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, .. } } => {
7033 assert!(update_add_htlcs.is_empty());
7034 assert!(update_fulfill_htlcs.is_empty());
7035 assert_eq!(update_fail_htlcs.len(), 1);
7036 assert!(update_fail_malformed_htlcs.is_empty());
7037 assert!(update_fee.is_none());
7039 _ => panic!("Unexpected event"),
7042 check_added_monitors!(nodes[1], 1);
7045 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7046 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7047 // 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
7048 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7050 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7051 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7052 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7053 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7054 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7055 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7057 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7059 // We route 2 dust-HTLCs between A and B
7060 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7061 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7062 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7064 // Cache one local commitment tx as previous
7065 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7067 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7068 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7069 check_added_monitors!(nodes[1], 0);
7070 expect_pending_htlcs_forwardable!(nodes[1]);
7071 check_added_monitors!(nodes[1], 1);
7073 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7074 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7075 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7076 check_added_monitors!(nodes[0], 1);
7078 // Cache one local commitment tx as lastest
7079 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7081 let events = nodes[0].node.get_and_clear_pending_msg_events();
7083 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7084 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7086 _ => panic!("Unexpected event"),
7089 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7090 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7092 _ => panic!("Unexpected event"),
7095 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7096 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7097 if announce_latest {
7098 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7100 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7103 check_closed_broadcast!(nodes[0], true);
7104 check_added_monitors!(nodes[0], 1);
7105 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7107 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7108 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7109 let events = nodes[0].node.get_and_clear_pending_events();
7110 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7111 assert_eq!(events.len(), 2);
7112 let mut first_failed = false;
7113 for event in events {
7115 Event::PaymentPathFailed { payment_hash, .. } => {
7116 if payment_hash == payment_hash_1 {
7117 assert!(!first_failed);
7118 first_failed = true;
7120 assert_eq!(payment_hash, payment_hash_2);
7123 _ => panic!("Unexpected event"),
7129 fn test_failure_delay_dust_htlc_local_commitment() {
7130 do_test_failure_delay_dust_htlc_local_commitment(true);
7131 do_test_failure_delay_dust_htlc_local_commitment(false);
7134 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7135 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7136 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7137 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7138 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7139 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7140 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7142 let chanmon_cfgs = create_chanmon_cfgs(3);
7143 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7144 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7145 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7146 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7148 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7150 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7151 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7153 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7154 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7156 // We revoked bs_commitment_tx
7158 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7159 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7162 let mut timeout_tx = Vec::new();
7164 // We fail dust-HTLC 1 by broadcast of local commitment tx
7165 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7166 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7167 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7168 expect_payment_failed!(nodes[0], dust_hash, true);
7170 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7171 check_closed_broadcast!(nodes[0], true);
7172 check_added_monitors!(nodes[0], 1);
7173 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7174 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7175 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7176 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7177 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7178 mine_transaction(&nodes[0], &timeout_tx[0]);
7179 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7180 expect_payment_failed!(nodes[0], non_dust_hash, true);
7182 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7183 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7184 check_closed_broadcast!(nodes[0], true);
7185 check_added_monitors!(nodes[0], 1);
7186 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7187 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7188 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7189 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7191 expect_payment_failed!(nodes[0], dust_hash, true);
7192 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7193 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7194 mine_transaction(&nodes[0], &timeout_tx[0]);
7195 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7196 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7197 expect_payment_failed!(nodes[0], non_dust_hash, true);
7199 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7201 let events = nodes[0].node.get_and_clear_pending_events();
7202 assert_eq!(events.len(), 2);
7205 Event::PaymentPathFailed { payment_hash, .. } => {
7206 if payment_hash == dust_hash { first = true; }
7207 else { first = false; }
7209 _ => panic!("Unexpected event"),
7212 Event::PaymentPathFailed { payment_hash, .. } => {
7213 if first { assert_eq!(payment_hash, non_dust_hash); }
7214 else { assert_eq!(payment_hash, dust_hash); }
7216 _ => panic!("Unexpected event"),
7223 fn test_sweep_outbound_htlc_failure_update() {
7224 do_test_sweep_outbound_htlc_failure_update(false, true);
7225 do_test_sweep_outbound_htlc_failure_update(false, false);
7226 do_test_sweep_outbound_htlc_failure_update(true, false);
7230 fn test_user_configurable_csv_delay() {
7231 // We test our channel constructors yield errors when we pass them absurd csv delay
7233 let mut low_our_to_self_config = UserConfig::default();
7234 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7235 let mut high_their_to_self_config = UserConfig::default();
7236 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7237 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7238 let chanmon_cfgs = create_chanmon_cfgs(2);
7239 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7240 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7241 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7243 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7244 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) {
7246 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())); },
7247 _ => panic!("Unexpected event"),
7249 } else { assert!(false) }
7251 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7252 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7253 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7254 open_channel.to_self_delay = 200;
7255 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) {
7257 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())); },
7258 _ => panic!("Unexpected event"),
7260 } else { assert!(false); }
7262 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7263 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7264 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()));
7265 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7266 accept_channel.to_self_delay = 200;
7267 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7269 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7271 &ErrorAction::SendErrorMessage { ref msg } => {
7272 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()));
7273 reason_msg = msg.data.clone();
7277 } else { panic!(); }
7278 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7280 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7281 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7282 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7283 open_channel.to_self_delay = 200;
7284 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) {
7286 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())); },
7287 _ => panic!("Unexpected event"),
7289 } else { assert!(false); }
7293 fn test_data_loss_protect() {
7294 // We want to be sure that :
7295 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7296 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7297 // * we close channel in case of detecting other being fallen behind
7298 // * we are able to claim our own outputs thanks to to_remote being static
7299 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7305 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7306 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7307 // during signing due to revoked tx
7308 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7309 let keys_manager = &chanmon_cfgs[0].keys_manager;
7312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7314 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7316 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7318 // Cache node A state before any channel update
7319 let previous_node_state = nodes[0].node.encode();
7320 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7321 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7323 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7324 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7326 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7327 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7329 // Restore node A from previous state
7330 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7331 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7332 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7333 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7334 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7335 persister = test_utils::TestPersister::new();
7336 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7338 let mut channel_monitors = HashMap::new();
7339 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7340 <(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 {
7341 keys_manager: keys_manager,
7342 fee_estimator: &fee_estimator,
7343 chain_monitor: &monitor,
7345 tx_broadcaster: &tx_broadcaster,
7346 default_config: UserConfig::default(),
7350 nodes[0].node = &node_state_0;
7351 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7352 nodes[0].chain_monitor = &monitor;
7353 nodes[0].chain_source = &chain_source;
7355 check_added_monitors!(nodes[0], 1);
7357 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7358 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7360 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7362 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7363 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7364 check_added_monitors!(nodes[0], 1);
7367 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7368 assert_eq!(node_txn.len(), 0);
7371 let mut reestablish_1 = Vec::with_capacity(1);
7372 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7373 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7374 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7375 reestablish_1.push(msg.clone());
7376 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7377 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7379 &ErrorAction::SendErrorMessage { ref msg } => {
7380 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");
7382 _ => panic!("Unexpected event!"),
7385 panic!("Unexpected event")
7389 // Check we close channel detecting A is fallen-behind
7390 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7391 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7392 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7393 check_added_monitors!(nodes[1], 1);
7395 // Check A is able to claim to_remote output
7396 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7397 assert_eq!(node_txn.len(), 1);
7398 check_spends!(node_txn[0], chan.3);
7399 assert_eq!(node_txn[0].output.len(), 2);
7400 mine_transaction(&nodes[0], &node_txn[0]);
7401 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7402 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can\'t do any automated broadcasting".to_string() });
7403 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7404 assert_eq!(spend_txn.len(), 1);
7405 check_spends!(spend_txn[0], node_txn[0]);
7409 fn test_check_htlc_underpaying() {
7410 // Send payment through A -> B but A is maliciously
7411 // sending a probe payment (i.e less than expected value0
7412 // to B, B should refuse payment.
7414 let chanmon_cfgs = create_chanmon_cfgs(2);
7415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7417 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7419 // Create some initial channels
7420 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7422 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7423 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7424 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7425 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7426 check_added_monitors!(nodes[0], 1);
7428 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7429 assert_eq!(events.len(), 1);
7430 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7431 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7432 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7434 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7435 // and then will wait a second random delay before failing the HTLC back:
7436 expect_pending_htlcs_forwardable!(nodes[1]);
7437 expect_pending_htlcs_forwardable!(nodes[1]);
7439 // Node 3 is expecting payment of 100_000 but received 10_000,
7440 // it should fail htlc like we didn't know the preimage.
7441 nodes[1].node.process_pending_htlc_forwards();
7443 let events = nodes[1].node.get_and_clear_pending_msg_events();
7444 assert_eq!(events.len(), 1);
7445 let (update_fail_htlc, commitment_signed) = match events[0] {
7446 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 } } => {
7447 assert!(update_add_htlcs.is_empty());
7448 assert!(update_fulfill_htlcs.is_empty());
7449 assert_eq!(update_fail_htlcs.len(), 1);
7450 assert!(update_fail_malformed_htlcs.is_empty());
7451 assert!(update_fee.is_none());
7452 (update_fail_htlcs[0].clone(), commitment_signed)
7454 _ => panic!("Unexpected event"),
7456 check_added_monitors!(nodes[1], 1);
7458 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7459 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7461 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7462 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7463 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7464 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7468 fn test_announce_disable_channels() {
7469 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7470 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7472 let chanmon_cfgs = create_chanmon_cfgs(2);
7473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7477 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7478 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7479 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7482 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7483 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7485 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7486 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7487 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7488 assert_eq!(msg_events.len(), 3);
7489 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7490 for e in msg_events {
7492 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7493 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7494 // Check that each channel gets updated exactly once
7495 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7496 panic!("Generated ChannelUpdate for wrong chan!");
7499 _ => panic!("Unexpected event"),
7503 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7504 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7505 assert_eq!(reestablish_1.len(), 3);
7506 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7507 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7508 assert_eq!(reestablish_2.len(), 3);
7510 // Reestablish chan_1
7511 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7512 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7513 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7514 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7515 // Reestablish chan_2
7516 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7517 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7518 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7519 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7520 // Reestablish chan_3
7521 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7522 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7523 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7524 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7526 nodes[0].node.timer_tick_occurred();
7527 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7528 nodes[0].node.timer_tick_occurred();
7529 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7530 assert_eq!(msg_events.len(), 3);
7531 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7532 for e in msg_events {
7534 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7535 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7536 // Check that each channel gets updated exactly once
7537 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7538 panic!("Generated ChannelUpdate for wrong chan!");
7541 _ => panic!("Unexpected event"),
7547 fn test_priv_forwarding_rejection() {
7548 // If we have a private channel with outbound liquidity, and
7549 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7550 // to forward through that channel.
7551 let chanmon_cfgs = create_chanmon_cfgs(3);
7552 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7553 let mut no_announce_cfg = test_default_channel_config();
7554 no_announce_cfg.channel_options.announced_channel = false;
7555 no_announce_cfg.accept_forwards_to_priv_channels = false;
7556 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7557 let persister: test_utils::TestPersister;
7558 let new_chain_monitor: test_utils::TestChainMonitor;
7559 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7560 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7562 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7564 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7565 // not send for private channels.
7566 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7567 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7568 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7569 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7570 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7572 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7573 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7574 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()));
7575 check_added_monitors!(nodes[2], 1);
7577 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()));
7578 check_added_monitors!(nodes[1], 1);
7580 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7581 confirm_transaction_at(&nodes[1], &tx, conf_height);
7582 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7583 confirm_transaction_at(&nodes[2], &tx, conf_height);
7584 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7585 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7586 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()));
7587 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7588 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7589 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7591 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7592 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7593 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7595 // We should always be able to forward through nodes[1] as long as its out through a public
7597 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7599 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7600 // to nodes[2], which should be rejected:
7601 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7602 let route = get_route(&nodes[0].node.get_our_node_id(),
7603 &nodes[0].net_graph_msg_handler.network_graph,
7604 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
7605 &[&RouteHint(vec![RouteHintHop {
7606 src_node_id: nodes[1].node.get_our_node_id(),
7607 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7608 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7609 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7610 htlc_minimum_msat: None,
7611 htlc_maximum_msat: None,
7612 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7614 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7615 check_added_monitors!(nodes[0], 1);
7616 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7617 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7618 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7620 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7621 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7622 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7623 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7624 assert!(htlc_fail_updates.update_fee.is_none());
7626 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7627 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7628 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7630 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7631 // to true. Sadly there is currently no way to change it at runtime.
7633 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7634 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7636 let nodes_1_serialized = nodes[1].node.encode();
7637 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7638 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7640 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7641 let mut mon_iter = mons.iter();
7642 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7643 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7646 persister = test_utils::TestPersister::new();
7647 let keys_manager = &chanmon_cfgs[1].keys_manager;
7648 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);
7649 nodes[1].chain_monitor = &new_chain_monitor;
7651 let mut monitor_a_read = &monitor_a_serialized.0[..];
7652 let mut monitor_b_read = &monitor_b_serialized.0[..];
7653 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7654 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7655 assert!(monitor_a_read.is_empty());
7656 assert!(monitor_b_read.is_empty());
7658 no_announce_cfg.accept_forwards_to_priv_channels = true;
7660 let mut nodes_1_read = &nodes_1_serialized[..];
7661 let (_, nodes_1_deserialized_tmp) = {
7662 let mut channel_monitors = HashMap::new();
7663 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7664 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7665 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7666 default_config: no_announce_cfg,
7668 fee_estimator: node_cfgs[1].fee_estimator,
7669 chain_monitor: nodes[1].chain_monitor,
7670 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7671 logger: nodes[1].logger,
7675 assert!(nodes_1_read.is_empty());
7676 nodes_1_deserialized = nodes_1_deserialized_tmp;
7678 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7679 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7680 check_added_monitors!(nodes[1], 2);
7681 nodes[1].node = &nodes_1_deserialized;
7683 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7684 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7685 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7686 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7687 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7688 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7689 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7690 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7692 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7693 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7694 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7695 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7696 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7697 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7698 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7699 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7701 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7702 check_added_monitors!(nodes[0], 1);
7703 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7704 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7708 fn test_bump_penalty_txn_on_revoked_commitment() {
7709 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7710 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7712 let chanmon_cfgs = create_chanmon_cfgs(2);
7713 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7714 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7715 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7717 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7718 let logger = test_utils::TestLogger::new();
7720 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7721 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7722 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7723 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7725 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7726 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7727 assert_eq!(revoked_txn[0].output.len(), 4);
7728 assert_eq!(revoked_txn[0].input.len(), 1);
7729 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7730 let revoked_txid = revoked_txn[0].txid();
7732 let mut penalty_sum = 0;
7733 for outp in revoked_txn[0].output.iter() {
7734 if outp.script_pubkey.is_v0_p2wsh() {
7735 penalty_sum += outp.value;
7739 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7740 let header_114 = connect_blocks(&nodes[1], 14);
7742 // Actually revoke tx by claiming a HTLC
7743 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7744 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7745 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7746 check_added_monitors!(nodes[1], 1);
7748 // One or more justice tx should have been broadcast, check it
7752 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7753 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7754 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7755 assert_eq!(node_txn[0].output.len(), 1);
7756 check_spends!(node_txn[0], revoked_txn[0]);
7757 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7758 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7759 penalty_1 = node_txn[0].txid();
7763 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7764 connect_blocks(&nodes[1], 15);
7765 let mut penalty_2 = penalty_1;
7766 let mut feerate_2 = 0;
7768 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7769 assert_eq!(node_txn.len(), 1);
7770 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7771 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7772 assert_eq!(node_txn[0].output.len(), 1);
7773 check_spends!(node_txn[0], revoked_txn[0]);
7774 penalty_2 = node_txn[0].txid();
7775 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7776 assert_ne!(penalty_2, penalty_1);
7777 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7778 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7779 // Verify 25% bump heuristic
7780 assert!(feerate_2 * 100 >= feerate_1 * 125);
7784 assert_ne!(feerate_2, 0);
7786 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7787 connect_blocks(&nodes[1], 1);
7789 let mut feerate_3 = 0;
7791 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7792 assert_eq!(node_txn.len(), 1);
7793 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7794 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7795 assert_eq!(node_txn[0].output.len(), 1);
7796 check_spends!(node_txn[0], revoked_txn[0]);
7797 penalty_3 = node_txn[0].txid();
7798 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7799 assert_ne!(penalty_3, penalty_2);
7800 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7801 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7802 // Verify 25% bump heuristic
7803 assert!(feerate_3 * 100 >= feerate_2 * 125);
7807 assert_ne!(feerate_3, 0);
7809 nodes[1].node.get_and_clear_pending_events();
7810 nodes[1].node.get_and_clear_pending_msg_events();
7814 fn test_bump_penalty_txn_on_revoked_htlcs() {
7815 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7816 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7818 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7819 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7824 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7825 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7826 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7827 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7828 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7829 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7830 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7831 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7833 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7834 assert_eq!(revoked_local_txn[0].input.len(), 1);
7835 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7837 // Revoke local commitment tx
7838 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7840 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7841 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7842 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7843 check_closed_broadcast!(nodes[1], true);
7844 check_added_monitors!(nodes[1], 1);
7845 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7846 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7848 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7849 assert_eq!(revoked_htlc_txn.len(), 3);
7850 check_spends!(revoked_htlc_txn[1], chan.3);
7852 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7853 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7854 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7856 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7857 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7858 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7859 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7861 // Broadcast set of revoked txn on A
7862 let hash_128 = connect_blocks(&nodes[0], 40);
7863 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7864 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7865 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7866 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7867 let events = nodes[0].node.get_and_clear_pending_events();
7868 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7870 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7871 _ => panic!("Unexpected event"),
7877 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7878 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7879 // Verify claim tx are spending revoked HTLC txn
7881 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7882 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7883 // which are included in the same block (they are broadcasted because we scan the
7884 // transactions linearly and generate claims as we go, they likely should be removed in the
7886 assert_eq!(node_txn[0].input.len(), 1);
7887 check_spends!(node_txn[0], revoked_local_txn[0]);
7888 assert_eq!(node_txn[1].input.len(), 1);
7889 check_spends!(node_txn[1], revoked_local_txn[0]);
7890 assert_eq!(node_txn[2].input.len(), 1);
7891 check_spends!(node_txn[2], revoked_local_txn[0]);
7893 // Each of the three justice transactions claim a separate (single) output of the three
7894 // available, which we check here:
7895 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7896 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7897 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7899 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7900 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7902 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7903 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7904 // a remote commitment tx has already been confirmed).
7905 check_spends!(node_txn[3], chan.3);
7907 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7908 // output, checked above).
7909 assert_eq!(node_txn[4].input.len(), 2);
7910 assert_eq!(node_txn[4].output.len(), 1);
7911 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7913 first = node_txn[4].txid();
7914 // Store both feerates for later comparison
7915 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7916 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7917 penalty_txn = vec![node_txn[2].clone()];
7921 // Connect one more block to see if bumped penalty are issued for HTLC txn
7922 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7923 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7924 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7927 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7928 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7930 check_spends!(node_txn[0], revoked_local_txn[0]);
7931 check_spends!(node_txn[1], revoked_local_txn[0]);
7932 // Note that these are both bogus - they spend outputs already claimed in block 129:
7933 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7934 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7936 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7937 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7943 // Few more blocks to confirm penalty txn
7944 connect_blocks(&nodes[0], 4);
7945 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7946 let header_144 = connect_blocks(&nodes[0], 9);
7948 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7949 assert_eq!(node_txn.len(), 1);
7951 assert_eq!(node_txn[0].input.len(), 2);
7952 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7953 // Verify bumped tx is different and 25% bump heuristic
7954 assert_ne!(first, node_txn[0].txid());
7955 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7956 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7957 assert!(feerate_2 * 100 > feerate_1 * 125);
7958 let txn = vec![node_txn[0].clone()];
7962 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7963 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7964 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7965 connect_blocks(&nodes[0], 20);
7967 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7968 // We verify than no new transaction has been broadcast because previously
7969 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7970 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7971 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7972 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7973 // up bumped justice generation.
7974 assert_eq!(node_txn.len(), 0);
7977 check_closed_broadcast!(nodes[0], true);
7978 check_added_monitors!(nodes[0], 1);
7982 fn test_bump_penalty_txn_on_remote_commitment() {
7983 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7984 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7987 // Provide preimage for one
7988 // Check aggregation
7990 let chanmon_cfgs = create_chanmon_cfgs(2);
7991 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7992 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7993 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7995 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7996 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7997 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7999 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8000 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8001 assert_eq!(remote_txn[0].output.len(), 4);
8002 assert_eq!(remote_txn[0].input.len(), 1);
8003 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8005 // Claim a HTLC without revocation (provide B monitor with preimage)
8006 nodes[1].node.claim_funds(payment_preimage);
8007 mine_transaction(&nodes[1], &remote_txn[0]);
8008 check_added_monitors!(nodes[1], 2);
8009 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8011 // One or more claim tx should have been broadcast, check it
8015 let feerate_timeout;
8016 let feerate_preimage;
8018 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8019 // 9 transactions including:
8020 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8021 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8022 // 2 * HTLC-Success (one RBF bump we'll check later)
8024 assert_eq!(node_txn.len(), 8);
8025 assert_eq!(node_txn[0].input.len(), 1);
8026 assert_eq!(node_txn[6].input.len(), 1);
8027 check_spends!(node_txn[0], remote_txn[0]);
8028 check_spends!(node_txn[6], remote_txn[0]);
8029 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
8030 preimage_bump = node_txn[3].clone();
8032 check_spends!(node_txn[1], chan.3);
8033 check_spends!(node_txn[2], node_txn[1]);
8034 assert_eq!(node_txn[1], node_txn[4]);
8035 assert_eq!(node_txn[2], node_txn[5]);
8037 timeout = node_txn[6].txid();
8038 let index = node_txn[6].input[0].previous_output.vout;
8039 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8040 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8042 preimage = node_txn[0].txid();
8043 let index = node_txn[0].input[0].previous_output.vout;
8044 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8045 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8049 assert_ne!(feerate_timeout, 0);
8050 assert_ne!(feerate_preimage, 0);
8052 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8053 connect_blocks(&nodes[1], 15);
8055 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8056 assert_eq!(node_txn.len(), 1);
8057 assert_eq!(node_txn[0].input.len(), 1);
8058 assert_eq!(preimage_bump.input.len(), 1);
8059 check_spends!(node_txn[0], remote_txn[0]);
8060 check_spends!(preimage_bump, remote_txn[0]);
8062 let index = preimage_bump.input[0].previous_output.vout;
8063 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8064 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8065 assert!(new_feerate * 100 > feerate_timeout * 125);
8066 assert_ne!(timeout, preimage_bump.txid());
8068 let index = node_txn[0].input[0].previous_output.vout;
8069 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8070 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8071 assert!(new_feerate * 100 > feerate_preimage * 125);
8072 assert_ne!(preimage, node_txn[0].txid());
8077 nodes[1].node.get_and_clear_pending_events();
8078 nodes[1].node.get_and_clear_pending_msg_events();
8082 fn test_counterparty_raa_skip_no_crash() {
8083 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8084 // commitment transaction, we would have happily carried on and provided them the next
8085 // commitment transaction based on one RAA forward. This would probably eventually have led to
8086 // channel closure, but it would not have resulted in funds loss. Still, our
8087 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8088 // check simply that the channel is closed in response to such an RAA, but don't check whether
8089 // we decide to punish our counterparty for revoking their funds (as we don't currently
8091 let chanmon_cfgs = create_chanmon_cfgs(2);
8092 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8093 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8094 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8095 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8097 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8098 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8100 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8102 // Make signer believe we got a counterparty signature, so that it allows the revocation
8103 keys.get_enforcement_state().last_holder_commitment -= 1;
8104 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8106 // Must revoke without gaps
8107 keys.get_enforcement_state().last_holder_commitment -= 1;
8108 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8110 keys.get_enforcement_state().last_holder_commitment -= 1;
8111 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8112 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8114 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8115 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8116 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8117 check_added_monitors!(nodes[1], 1);
8118 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8122 fn test_bump_txn_sanitize_tracking_maps() {
8123 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8124 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8126 let chanmon_cfgs = create_chanmon_cfgs(2);
8127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8129 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8131 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8132 // Lock HTLC in both directions
8133 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8134 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8136 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8137 assert_eq!(revoked_local_txn[0].input.len(), 1);
8138 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8140 // Revoke local commitment tx
8141 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8143 // Broadcast set of revoked txn on A
8144 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8145 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8146 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8148 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8149 check_closed_broadcast!(nodes[0], true);
8150 check_added_monitors!(nodes[0], 1);
8151 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8153 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8154 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8155 check_spends!(node_txn[0], revoked_local_txn[0]);
8156 check_spends!(node_txn[1], revoked_local_txn[0]);
8157 check_spends!(node_txn[2], revoked_local_txn[0]);
8158 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8162 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8163 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8164 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8166 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8167 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8168 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8169 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8175 fn test_override_channel_config() {
8176 let chanmon_cfgs = create_chanmon_cfgs(2);
8177 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8178 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8179 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8181 // Node0 initiates a channel to node1 using the override config.
8182 let mut override_config = UserConfig::default();
8183 override_config.own_channel_config.our_to_self_delay = 200;
8185 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8187 // Assert the channel created by node0 is using the override config.
8188 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8189 assert_eq!(res.channel_flags, 0);
8190 assert_eq!(res.to_self_delay, 200);
8194 fn test_override_0msat_htlc_minimum() {
8195 let mut zero_config = UserConfig::default();
8196 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8197 let chanmon_cfgs = create_chanmon_cfgs(2);
8198 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8199 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8200 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8202 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8203 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8204 assert_eq!(res.htlc_minimum_msat, 1);
8206 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8207 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8208 assert_eq!(res.htlc_minimum_msat, 1);
8212 fn test_simple_mpp() {
8213 // Simple test of sending a multi-path payment.
8214 let chanmon_cfgs = create_chanmon_cfgs(4);
8215 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8216 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8217 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8219 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8220 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8221 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8222 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8223 let logger = test_utils::TestLogger::new();
8225 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8226 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8227 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8228 let path = route.paths[0].clone();
8229 route.paths.push(path);
8230 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8231 route.paths[0][0].short_channel_id = chan_1_id;
8232 route.paths[0][1].short_channel_id = chan_3_id;
8233 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8234 route.paths[1][0].short_channel_id = chan_2_id;
8235 route.paths[1][1].short_channel_id = chan_4_id;
8236 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8237 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8241 fn test_preimage_storage() {
8242 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8243 let chanmon_cfgs = create_chanmon_cfgs(2);
8244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8246 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8248 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8251 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8253 let logger = test_utils::TestLogger::new();
8254 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8255 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8256 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8257 check_added_monitors!(nodes[0], 1);
8258 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8259 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8260 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8261 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8263 // Note that after leaving the above scope we have no knowledge of any arguments or return
8264 // values from previous calls.
8265 expect_pending_htlcs_forwardable!(nodes[1]);
8266 let events = nodes[1].node.get_and_clear_pending_events();
8267 assert_eq!(events.len(), 1);
8269 Event::PaymentReceived { ref purpose, .. } => {
8271 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8272 assert_eq!(*user_payment_id, 42);
8273 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8275 _ => panic!("expected PaymentPurpose::InvoicePayment")
8278 _ => panic!("Unexpected event"),
8283 fn test_secret_timeout() {
8284 // Simple test of payment secret storage time outs
8285 let chanmon_cfgs = create_chanmon_cfgs(2);
8286 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8287 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8288 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8290 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8292 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8294 // We should fail to register the same payment hash twice, at least until we've connected a
8295 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8296 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8297 assert_eq!(err, "Duplicate payment hash");
8298 } else { panic!(); }
8300 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8302 header: BlockHeader {
8304 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8305 merkle_root: Default::default(),
8306 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8310 connect_block(&nodes[1], &block);
8311 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8312 assert_eq!(err, "Duplicate payment hash");
8313 } else { panic!(); }
8315 // If we then connect the second block, we should be able to register the same payment hash
8316 // again with a different user_payment_id (this time getting a new payment secret).
8317 block.header.prev_blockhash = block.header.block_hash();
8318 block.header.time += 1;
8319 connect_block(&nodes[1], &block);
8320 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8321 assert_ne!(payment_secret_1, our_payment_secret);
8324 let logger = test_utils::TestLogger::new();
8325 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8326 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8327 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8328 check_added_monitors!(nodes[0], 1);
8329 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8330 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8331 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8332 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8334 // Note that after leaving the above scope we have no knowledge of any arguments or return
8335 // values from previous calls.
8336 expect_pending_htlcs_forwardable!(nodes[1]);
8337 let events = nodes[1].node.get_and_clear_pending_events();
8338 assert_eq!(events.len(), 1);
8340 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8341 assert!(payment_preimage.is_none());
8342 assert_eq!(user_payment_id, 42);
8343 assert_eq!(payment_secret, our_payment_secret);
8344 // We don't actually have the payment preimage with which to claim this payment!
8346 _ => panic!("Unexpected event"),
8351 fn test_bad_secret_hash() {
8352 // Simple test of unregistered payment hash/invalid payment secret handling
8353 let chanmon_cfgs = create_chanmon_cfgs(2);
8354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8356 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8358 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8360 let random_payment_hash = PaymentHash([42; 32]);
8361 let random_payment_secret = PaymentSecret([43; 32]);
8362 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8364 let logger = test_utils::TestLogger::new();
8365 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8366 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8368 // All the below cases should end up being handled exactly identically, so we macro the
8369 // resulting events.
8370 macro_rules! handle_unknown_invalid_payment_data {
8372 check_added_monitors!(nodes[0], 1);
8373 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8374 let payment_event = SendEvent::from_event(events.pop().unwrap());
8375 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8376 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8378 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8379 // again to process the pending backwards-failure of the HTLC
8380 expect_pending_htlcs_forwardable!(nodes[1]);
8381 expect_pending_htlcs_forwardable!(nodes[1]);
8382 check_added_monitors!(nodes[1], 1);
8384 // We should fail the payment back
8385 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8386 match events.pop().unwrap() {
8387 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8388 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8389 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8391 _ => panic!("Unexpected event"),
8396 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8397 // Error data is the HTLC value (100,000) and current block height
8398 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8400 // Send a payment with the right payment hash but the wrong payment secret
8401 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8402 handle_unknown_invalid_payment_data!();
8403 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8405 // Send a payment with a random payment hash, but the right payment secret
8406 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8407 handle_unknown_invalid_payment_data!();
8408 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8410 // Send a payment with a random payment hash and random payment secret
8411 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8412 handle_unknown_invalid_payment_data!();
8413 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8417 fn test_update_err_monitor_lockdown() {
8418 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8419 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8420 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8422 // This scenario may happen in a watchtower setup, where watchtower process a block height
8423 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8424 // commitment at same time.
8426 let chanmon_cfgs = create_chanmon_cfgs(2);
8427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8431 // Create some initial channel
8432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8433 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8435 // Rebalance the network to generate htlc in the two directions
8436 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8438 // Route a HTLC from node 0 to node 1 (but don't settle)
8439 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8441 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8442 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8443 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8444 let persister = test_utils::TestPersister::new();
8446 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8447 let monitor = monitors.get(&outpoint).unwrap();
8448 let mut w = test_utils::TestVecWriter(Vec::new());
8449 monitor.write(&mut w).unwrap();
8450 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8451 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8452 assert!(new_monitor == *monitor);
8453 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);
8454 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8457 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8458 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8459 // transaction lock time requirements here.
8460 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8461 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8463 // Try to update ChannelMonitor
8464 assert!(nodes[1].node.claim_funds(preimage));
8465 check_added_monitors!(nodes[1], 1);
8466 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8467 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8468 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8469 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8470 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8471 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8472 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8473 } else { assert!(false); }
8474 } else { assert!(false); };
8475 // Our local monitor is in-sync and hasn't processed yet timeout
8476 check_added_monitors!(nodes[0], 1);
8477 let events = nodes[0].node.get_and_clear_pending_events();
8478 assert_eq!(events.len(), 1);
8482 fn test_concurrent_monitor_claim() {
8483 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8484 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8485 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8486 // state N+1 confirms. Alice claims output from state N+1.
8488 let chanmon_cfgs = create_chanmon_cfgs(2);
8489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8491 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8493 // Create some initial channel
8494 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8495 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8497 // Rebalance the network to generate htlc in the two directions
8498 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8500 // Route a HTLC from node 0 to node 1 (but don't settle)
8501 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8503 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8504 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8505 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8506 let persister = test_utils::TestPersister::new();
8507 let watchtower_alice = {
8508 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8509 let monitor = monitors.get(&outpoint).unwrap();
8510 let mut w = test_utils::TestVecWriter(Vec::new());
8511 monitor.write(&mut w).unwrap();
8512 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8513 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8514 assert!(new_monitor == *monitor);
8515 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);
8516 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8519 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8520 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8521 // transaction lock time requirements here.
8522 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8523 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8525 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8527 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8528 assert_eq!(txn.len(), 2);
8532 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8533 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8534 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8535 let persister = test_utils::TestPersister::new();
8536 let watchtower_bob = {
8537 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8538 let monitor = monitors.get(&outpoint).unwrap();
8539 let mut w = test_utils::TestVecWriter(Vec::new());
8540 monitor.write(&mut w).unwrap();
8541 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8542 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8543 assert!(new_monitor == *monitor);
8544 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);
8545 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8548 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8549 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8551 // Route another payment to generate another update with still previous HTLC pending
8552 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8554 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8555 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8556 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8558 check_added_monitors!(nodes[1], 1);
8560 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8561 assert_eq!(updates.update_add_htlcs.len(), 1);
8562 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8563 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8564 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8565 // Watchtower Alice should already have seen the block and reject the update
8566 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8567 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8568 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8569 } else { assert!(false); }
8570 } else { assert!(false); };
8571 // Our local monitor is in-sync and hasn't processed yet timeout
8572 check_added_monitors!(nodes[0], 1);
8574 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8575 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8576 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8578 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8581 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8582 assert_eq!(txn.len(), 2);
8583 bob_state_y = txn[0].clone();
8587 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8588 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8589 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);
8591 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8592 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8593 // the onchain detection of the HTLC output
8594 assert_eq!(htlc_txn.len(), 2);
8595 check_spends!(htlc_txn[0], bob_state_y);
8596 check_spends!(htlc_txn[1], bob_state_y);
8601 fn test_pre_lockin_no_chan_closed_update() {
8602 // Test that if a peer closes a channel in response to a funding_created message we don't
8603 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8606 // Doing so would imply a channel monitor update before the initial channel monitor
8607 // registration, violating our API guarantees.
8609 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8610 // then opening a second channel with the same funding output as the first (which is not
8611 // rejected because the first channel does not exist in the ChannelManager) and closing it
8612 // before receiving funding_signed.
8613 let chanmon_cfgs = create_chanmon_cfgs(2);
8614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8616 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8618 // Create an initial channel
8619 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8620 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8621 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8622 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8623 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8625 // Move the first channel through the funding flow...
8626 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8628 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8629 check_added_monitors!(nodes[0], 0);
8631 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8632 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8633 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8634 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8635 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() });
8639 fn test_htlc_no_detection() {
8640 // This test is a mutation to underscore the detection logic bug we had
8641 // before #653. HTLC value routed is above the remaining balance, thus
8642 // inverting HTLC and `to_remote` output. HTLC will come second and
8643 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8644 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8645 // outputs order detection for correct spending children filtring.
8647 let chanmon_cfgs = create_chanmon_cfgs(2);
8648 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8649 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8650 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8652 // Create some initial channels
8653 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8655 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8656 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8657 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8658 assert_eq!(local_txn[0].input.len(), 1);
8659 assert_eq!(local_txn[0].output.len(), 3);
8660 check_spends!(local_txn[0], chan_1.3);
8662 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8663 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8664 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8665 // We deliberately connect the local tx twice as this should provoke a failure calling
8666 // this test before #653 fix.
8667 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);
8668 check_closed_broadcast!(nodes[0], true);
8669 check_added_monitors!(nodes[0], 1);
8670 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8671 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8673 let htlc_timeout = {
8674 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8675 assert_eq!(node_txn[1].input.len(), 1);
8676 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8677 check_spends!(node_txn[1], local_txn[0]);
8681 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8682 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8683 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8684 expect_payment_failed!(nodes[0], our_payment_hash, true);
8687 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8688 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8689 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8690 // Carol, Alice would be the upstream node, and Carol the downstream.)
8692 // Steps of the test:
8693 // 1) Alice sends a HTLC to Carol through Bob.
8694 // 2) Carol doesn't settle the HTLC.
8695 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8696 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8697 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8698 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8699 // 5) Carol release the preimage to Bob off-chain.
8700 // 6) Bob claims the offered output on the broadcasted commitment.
8701 let chanmon_cfgs = create_chanmon_cfgs(3);
8702 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8703 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8704 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8706 // Create some initial channels
8707 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8708 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8710 // Steps (1) and (2):
8711 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8712 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8714 // Check that Alice's commitment transaction now contains an output for this HTLC.
8715 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8716 check_spends!(alice_txn[0], chan_ab.3);
8717 assert_eq!(alice_txn[0].output.len(), 2);
8718 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8719 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8720 assert_eq!(alice_txn.len(), 2);
8722 // Steps (3) and (4):
8723 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8724 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8725 let mut force_closing_node = 0; // Alice force-closes
8726 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8727 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8728 check_closed_broadcast!(nodes[force_closing_node], true);
8729 check_added_monitors!(nodes[force_closing_node], 1);
8730 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8731 if go_onchain_before_fulfill {
8732 let txn_to_broadcast = match broadcast_alice {
8733 true => alice_txn.clone(),
8734 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8736 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8737 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8738 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8739 if broadcast_alice {
8740 check_closed_broadcast!(nodes[1], true);
8741 check_added_monitors!(nodes[1], 1);
8742 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8744 assert_eq!(bob_txn.len(), 1);
8745 check_spends!(bob_txn[0], chan_ab.3);
8749 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8750 // process of removing the HTLC from their commitment transactions.
8751 assert!(nodes[2].node.claim_funds(payment_preimage));
8752 check_added_monitors!(nodes[2], 1);
8753 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8754 assert!(carol_updates.update_add_htlcs.is_empty());
8755 assert!(carol_updates.update_fail_htlcs.is_empty());
8756 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8757 assert!(carol_updates.update_fee.is_none());
8758 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8760 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8761 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8762 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8763 if !go_onchain_before_fulfill && broadcast_alice {
8764 let events = nodes[1].node.get_and_clear_pending_msg_events();
8765 assert_eq!(events.len(), 1);
8767 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8768 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8770 _ => panic!("Unexpected event"),
8773 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8774 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8775 // Carol<->Bob's updated commitment transaction info.
8776 check_added_monitors!(nodes[1], 2);
8778 let events = nodes[1].node.get_and_clear_pending_msg_events();
8779 assert_eq!(events.len(), 2);
8780 let bob_revocation = match events[0] {
8781 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8782 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8785 _ => panic!("Unexpected event"),
8787 let bob_updates = match events[1] {
8788 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8789 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8792 _ => panic!("Unexpected event"),
8795 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8796 check_added_monitors!(nodes[2], 1);
8797 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8798 check_added_monitors!(nodes[2], 1);
8800 let events = nodes[2].node.get_and_clear_pending_msg_events();
8801 assert_eq!(events.len(), 1);
8802 let carol_revocation = match events[0] {
8803 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8804 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8807 _ => panic!("Unexpected event"),
8809 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8810 check_added_monitors!(nodes[1], 1);
8812 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8813 // here's where we put said channel's commitment tx on-chain.
8814 let mut txn_to_broadcast = alice_txn.clone();
8815 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8816 if !go_onchain_before_fulfill {
8817 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8818 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8819 // If Bob was the one to force-close, he will have already passed these checks earlier.
8820 if broadcast_alice {
8821 check_closed_broadcast!(nodes[1], true);
8822 check_added_monitors!(nodes[1], 1);
8823 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8825 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8826 if broadcast_alice {
8827 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8828 // new block being connected. The ChannelManager being notified triggers a monitor update,
8829 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8830 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8832 assert_eq!(bob_txn.len(), 3);
8833 check_spends!(bob_txn[1], chan_ab.3);
8835 assert_eq!(bob_txn.len(), 2);
8836 check_spends!(bob_txn[0], chan_ab.3);
8841 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8842 // broadcasted commitment transaction.
8844 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8845 if go_onchain_before_fulfill {
8846 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8847 assert_eq!(bob_txn.len(), 2);
8849 let script_weight = match broadcast_alice {
8850 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8851 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8853 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8854 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8855 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8856 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8857 if broadcast_alice && !go_onchain_before_fulfill {
8858 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8859 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8861 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8862 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8868 fn test_onchain_htlc_settlement_after_close() {
8869 do_test_onchain_htlc_settlement_after_close(true, true);
8870 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8871 do_test_onchain_htlc_settlement_after_close(true, false);
8872 do_test_onchain_htlc_settlement_after_close(false, false);
8876 fn test_duplicate_chan_id() {
8877 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8878 // already open we reject it and keep the old channel.
8880 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8881 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8882 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8883 // updating logic for the existing channel.
8884 let chanmon_cfgs = create_chanmon_cfgs(2);
8885 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8886 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8887 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8889 // Create an initial channel
8890 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8891 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8892 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8893 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()));
8895 // Try to create a second channel with the same temporary_channel_id as the first and check
8896 // that it is rejected.
8897 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8899 let events = nodes[1].node.get_and_clear_pending_msg_events();
8900 assert_eq!(events.len(), 1);
8902 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8903 // Technically, at this point, nodes[1] would be justified in thinking both the
8904 // first (valid) and second (invalid) channels are closed, given they both have
8905 // the same non-temporary channel_id. However, currently we do not, so we just
8906 // move forward with it.
8907 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8908 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8910 _ => panic!("Unexpected event"),
8914 // Move the first channel through the funding flow...
8915 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8917 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8918 check_added_monitors!(nodes[0], 0);
8920 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8921 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8923 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8924 assert_eq!(added_monitors.len(), 1);
8925 assert_eq!(added_monitors[0].0, funding_output);
8926 added_monitors.clear();
8928 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8930 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8931 let channel_id = funding_outpoint.to_channel_id();
8933 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8936 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8937 // Technically this is allowed by the spec, but we don't support it and there's little reason
8938 // to. Still, it shouldn't cause any other issues.
8939 open_chan_msg.temporary_channel_id = channel_id;
8940 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8942 let events = nodes[1].node.get_and_clear_pending_msg_events();
8943 assert_eq!(events.len(), 1);
8945 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8946 // Technically, at this point, nodes[1] would be justified in thinking both
8947 // channels are closed, but currently we do not, so we just move forward with it.
8948 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8949 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8951 _ => panic!("Unexpected event"),
8955 // Now try to create a second channel which has a duplicate funding output.
8956 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8957 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8958 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8959 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()));
8960 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8962 let funding_created = {
8963 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8964 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8965 let logger = test_utils::TestLogger::new();
8966 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8968 check_added_monitors!(nodes[0], 0);
8969 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8970 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8971 // still needs to be cleared here.
8972 check_added_monitors!(nodes[1], 1);
8974 // ...still, nodes[1] will reject the duplicate channel.
8976 let events = nodes[1].node.get_and_clear_pending_msg_events();
8977 assert_eq!(events.len(), 1);
8979 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8980 // Technically, at this point, nodes[1] would be justified in thinking both
8981 // channels are closed, but currently we do not, so we just move forward with it.
8982 assert_eq!(msg.channel_id, channel_id);
8983 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8985 _ => panic!("Unexpected event"),
8989 // finally, finish creating the original channel and send a payment over it to make sure
8990 // everything is functional.
8991 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8993 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8994 assert_eq!(added_monitors.len(), 1);
8995 assert_eq!(added_monitors[0].0, funding_output);
8996 added_monitors.clear();
8999 let events_4 = nodes[0].node.get_and_clear_pending_events();
9000 assert_eq!(events_4.len(), 0);
9001 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9002 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9004 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9005 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9006 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9007 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9011 fn test_error_chans_closed() {
9012 // Test that we properly handle error messages, closing appropriate channels.
9014 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9015 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9016 // we can test various edge cases around it to ensure we don't regress.
9017 let chanmon_cfgs = create_chanmon_cfgs(3);
9018 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9019 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9020 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9022 // Create some initial channels
9023 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9024 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9025 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9027 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9028 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9029 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9031 // Closing a channel from a different peer has no effect
9032 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9033 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9035 // Closing one channel doesn't impact others
9036 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9037 check_added_monitors!(nodes[0], 1);
9038 check_closed_broadcast!(nodes[0], false);
9039 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9040 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9041 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9042 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);
9043 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);
9045 // A null channel ID should close all channels
9046 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9047 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9048 check_added_monitors!(nodes[0], 2);
9049 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9050 let events = nodes[0].node.get_and_clear_pending_msg_events();
9051 assert_eq!(events.len(), 2);
9053 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9054 assert_eq!(msg.contents.flags & 2, 2);
9056 _ => panic!("Unexpected event"),
9059 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9060 assert_eq!(msg.contents.flags & 2, 2);
9062 _ => panic!("Unexpected event"),
9064 // Note that at this point users of a standard PeerHandler will end up calling
9065 // peer_disconnected with no_connection_possible set to false, duplicating the
9066 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9067 // users with their own peer handling logic. We duplicate the call here, however.
9068 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9069 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9071 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9072 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9073 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9077 fn test_invalid_funding_tx() {
9078 // Test that we properly handle invalid funding transactions sent to us from a peer.
9080 // Previously, all other major lightning implementations had failed to properly sanitize
9081 // funding transactions from their counterparties, leading to a multi-implementation critical
9082 // security vulnerability (though we always sanitized properly, we've previously had
9083 // un-released crashes in the sanitization process).
9084 let chanmon_cfgs = create_chanmon_cfgs(2);
9085 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9086 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9087 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9089 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9090 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()));
9091 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()));
9093 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9094 for output in tx.output.iter_mut() {
9095 // Make the confirmed funding transaction have a bogus script_pubkey
9096 output.script_pubkey = bitcoin::Script::new();
9099 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9100 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()));
9101 check_added_monitors!(nodes[1], 1);
9103 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()));
9104 check_added_monitors!(nodes[0], 1);
9106 let events_1 = nodes[0].node.get_and_clear_pending_events();
9107 assert_eq!(events_1.len(), 0);
9109 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9110 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9111 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9113 confirm_transaction_at(&nodes[1], &tx, 1);
9114 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9115 check_added_monitors!(nodes[1], 1);
9116 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9117 assert_eq!(events_2.len(), 1);
9118 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9119 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9120 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9121 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9122 } else { panic!(); }
9123 } else { panic!(); }
9124 assert_eq!(nodes[1].node.list_channels().len(), 0);
9127 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9128 // In the first version of the chain::Confirm interface, after a refactor was made to not
9129 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9130 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9131 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9132 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9133 // spending transaction until height N+1 (or greater). This was due to the way
9134 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9135 // spending transaction at the height the input transaction was confirmed at, not whether we
9136 // should broadcast a spending transaction at the current height.
9137 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9138 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9139 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9140 // until we learned about an additional block.
9142 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9143 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9144 let chanmon_cfgs = create_chanmon_cfgs(3);
9145 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9146 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9147 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9148 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9150 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9151 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9152 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9153 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9154 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9156 nodes[1].node.force_close_channel(&channel_id).unwrap();
9157 check_closed_broadcast!(nodes[1], true);
9158 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9159 check_added_monitors!(nodes[1], 1);
9160 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9161 assert_eq!(node_txn.len(), 1);
9163 let conf_height = nodes[1].best_block_info().1;
9164 if !test_height_before_timelock {
9165 connect_blocks(&nodes[1], 24 * 6);
9167 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9168 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9169 if test_height_before_timelock {
9170 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9171 // generate any events or broadcast any transactions
9172 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9173 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9175 // We should broadcast an HTLC transaction spending our funding transaction first
9176 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9177 assert_eq!(spending_txn.len(), 2);
9178 assert_eq!(spending_txn[0], node_txn[0]);
9179 check_spends!(spending_txn[1], node_txn[0]);
9180 // We should also generate a SpendableOutputs event with the to_self output (as its
9182 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9183 assert_eq!(descriptor_spend_txn.len(), 1);
9185 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9186 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9187 // additional block built on top of the current chain.
9188 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9189 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9190 expect_pending_htlcs_forwardable!(nodes[1]);
9191 check_added_monitors!(nodes[1], 1);
9193 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9194 assert!(updates.update_add_htlcs.is_empty());
9195 assert!(updates.update_fulfill_htlcs.is_empty());
9196 assert_eq!(updates.update_fail_htlcs.len(), 1);
9197 assert!(updates.update_fail_malformed_htlcs.is_empty());
9198 assert!(updates.update_fee.is_none());
9199 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9200 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9201 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9206 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9207 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9208 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9212 fn test_forwardable_regen() {
9213 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9214 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9216 // We test it for both payment receipt and payment forwarding.
9218 let chanmon_cfgs = create_chanmon_cfgs(3);
9219 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9220 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9221 let persister: test_utils::TestPersister;
9222 let new_chain_monitor: test_utils::TestChainMonitor;
9223 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9224 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9225 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9226 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9228 // First send a payment to nodes[1]
9229 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9230 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9231 check_added_monitors!(nodes[0], 1);
9233 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9234 assert_eq!(events.len(), 1);
9235 let payment_event = SendEvent::from_event(events.pop().unwrap());
9236 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9237 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9239 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9241 // Next send a payment which is forwarded by nodes[1]
9242 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9243 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9244 check_added_monitors!(nodes[0], 1);
9246 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9247 assert_eq!(events.len(), 1);
9248 let payment_event = SendEvent::from_event(events.pop().unwrap());
9249 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9250 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9252 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9254 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9256 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9257 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9258 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9260 let nodes_1_serialized = nodes[1].node.encode();
9261 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9262 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9264 let monitors = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
9265 let mut monitor_iter = monitors.iter();
9266 monitor_iter.next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
9267 monitor_iter.next().unwrap().1.write(&mut chan_1_monitor_serialized).unwrap();
9270 persister = test_utils::TestPersister::new();
9271 let keys_manager = &chanmon_cfgs[1].keys_manager;
9272 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);
9273 nodes[1].chain_monitor = &new_chain_monitor;
9275 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9276 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9277 &mut chan_0_monitor_read, keys_manager).unwrap();
9278 assert!(chan_0_monitor_read.is_empty());
9279 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9280 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9281 &mut chan_1_monitor_read, keys_manager).unwrap();
9282 assert!(chan_1_monitor_read.is_empty());
9284 let mut nodes_1_read = &nodes_1_serialized[..];
9285 let (_, nodes_1_deserialized_tmp) = {
9286 let mut channel_monitors = HashMap::new();
9287 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9288 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9289 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9290 default_config: UserConfig::default(),
9292 fee_estimator: node_cfgs[1].fee_estimator,
9293 chain_monitor: nodes[1].chain_monitor,
9294 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9295 logger: nodes[1].logger,
9299 nodes_1_deserialized = nodes_1_deserialized_tmp;
9300 assert!(nodes_1_read.is_empty());
9302 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9303 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9304 nodes[1].node = &nodes_1_deserialized;
9305 check_added_monitors!(nodes[1], 2);
9307 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9308 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9309 // the commitment state.
9310 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9312 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9314 expect_pending_htlcs_forwardable!(nodes[1]);
9315 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9316 check_added_monitors!(nodes[1], 1);
9318 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9319 assert_eq!(events.len(), 1);
9320 let payment_event = SendEvent::from_event(events.pop().unwrap());
9321 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9322 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9323 expect_pending_htlcs_forwardable!(nodes[2]);
9324 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9326 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9327 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9331 fn test_keysend_payments_to_public_node() {
9332 let chanmon_cfgs = create_chanmon_cfgs(2);
9333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9335 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9337 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9338 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9339 let payer_pubkey = nodes[0].node.get_our_node_id();
9340 let payee_pubkey = nodes[1].node.get_our_node_id();
9341 let route = get_route(&payer_pubkey, network_graph, &payee_pubkey, None,
9342 None, &vec![], 10000, 40,
9343 nodes[0].logger).unwrap();
9345 let test_preimage = PaymentPreimage([42; 32]);
9346 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9347 check_added_monitors!(nodes[0], 1);
9348 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9349 assert_eq!(events.len(), 1);
9350 let event = events.pop().unwrap();
9351 let path = vec![&nodes[1]];
9352 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9353 claim_payment(&nodes[0], &path, test_preimage);
9357 fn test_keysend_payments_to_private_node() {
9358 let chanmon_cfgs = create_chanmon_cfgs(2);
9359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9361 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9363 let payer_pubkey = nodes[0].node.get_our_node_id();
9364 let payee_pubkey = nodes[1].node.get_our_node_id();
9365 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9366 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9368 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9369 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9370 let first_hops = nodes[0].node.list_usable_channels();
9371 let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9372 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9373 nodes[0].logger).unwrap();
9375 let test_preimage = PaymentPreimage([42; 32]);
9376 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9377 check_added_monitors!(nodes[0], 1);
9378 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9379 assert_eq!(events.len(), 1);
9380 let event = events.pop().unwrap();
9381 let path = vec![&nodes[1]];
9382 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9383 claim_payment(&nodes[0], &path, test_preimage);