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, MppId, 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::CommitmentTxBroadcasted);
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_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 let events = nodes[0].node.get_and_clear_pending_events();
1930 expect_payment_sent!(nodes[0], payment_preimage_1, events);
1932 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1934 check_added_monitors!(nodes[1], 1);
1935 // B is already AwaitingRAA, so cant generate a CS here
1936 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1939 check_added_monitors!(nodes[1], 1);
1940 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1942 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1943 check_added_monitors!(nodes[0], 1);
1944 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1946 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1947 check_added_monitors!(nodes[1], 1);
1948 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1950 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1951 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1952 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1953 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1954 // on-chain as necessary).
1955 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1956 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1957 check_added_monitors!(nodes[0], 1);
1958 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1959 let events = nodes[0].node.get_and_clear_pending_events();
1960 expect_payment_sent!(nodes[0], payment_preimage_2, events);
1962 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1963 check_added_monitors!(nodes[1], 1);
1964 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1966 expect_pending_htlcs_forwardable!(nodes[1]);
1967 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1969 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1970 // resolve the second HTLC from A's point of view.
1971 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1972 check_added_monitors!(nodes[0], 1);
1973 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1975 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1976 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1977 let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
1979 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1980 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();
1981 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1982 check_added_monitors!(nodes[1], 1);
1983 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1984 assert_eq!(events.len(), 1);
1985 SendEvent::from_event(events.remove(0))
1988 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1989 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1990 check_added_monitors!(nodes[0], 1);
1991 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1993 // Now just resolve all the outstanding messages/HTLCs for completeness...
1995 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1996 check_added_monitors!(nodes[1], 1);
1997 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1999 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2000 check_added_monitors!(nodes[1], 1);
2002 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2003 check_added_monitors!(nodes[0], 1);
2004 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2006 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2007 check_added_monitors!(nodes[1], 1);
2008 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2010 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2011 check_added_monitors!(nodes[0], 1);
2013 expect_pending_htlcs_forwardable!(nodes[0]);
2014 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2016 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2017 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2021 fn channel_monitor_network_test() {
2022 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2023 // tests that ChannelMonitor is able to recover from various states.
2024 let chanmon_cfgs = create_chanmon_cfgs(5);
2025 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2026 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2027 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2029 // Create some initial channels
2030 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2031 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2032 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2033 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2035 // Make sure all nodes are at the same starting height
2036 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2037 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2038 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2039 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2040 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2042 // Rebalance the network a bit by relaying one payment through all the channels...
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);
2045 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2046 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2048 // Simple case with no pending HTLCs:
2049 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2050 check_added_monitors!(nodes[1], 1);
2051 check_closed_broadcast!(nodes[1], false);
2053 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2054 assert_eq!(node_txn.len(), 1);
2055 mine_transaction(&nodes[0], &node_txn[0]);
2056 check_added_monitors!(nodes[0], 1);
2057 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2059 check_closed_broadcast!(nodes[0], true);
2060 assert_eq!(nodes[0].node.list_channels().len(), 0);
2061 assert_eq!(nodes[1].node.list_channels().len(), 1);
2062 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
2063 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2065 // One pending HTLC is discarded by the force-close:
2066 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2068 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2069 // broadcasted until we reach the timelock time).
2070 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2071 check_closed_broadcast!(nodes[1], false);
2072 check_added_monitors!(nodes[1], 1);
2074 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2075 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2076 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2077 mine_transaction(&nodes[2], &node_txn[0]);
2078 check_added_monitors!(nodes[2], 1);
2079 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2081 check_closed_broadcast!(nodes[2], true);
2082 assert_eq!(nodes[1].node.list_channels().len(), 0);
2083 assert_eq!(nodes[2].node.list_channels().len(), 1);
2084 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2085 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxBroadcasted);
2087 macro_rules! claim_funds {
2088 ($node: expr, $prev_node: expr, $preimage: expr) => {
2090 assert!($node.node.claim_funds($preimage));
2091 check_added_monitors!($node, 1);
2093 let events = $node.node.get_and_clear_pending_msg_events();
2094 assert_eq!(events.len(), 1);
2096 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2097 assert!(update_add_htlcs.is_empty());
2098 assert!(update_fail_htlcs.is_empty());
2099 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2101 _ => panic!("Unexpected event"),
2107 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2108 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2109 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2110 check_added_monitors!(nodes[2], 1);
2111 check_closed_broadcast!(nodes[2], false);
2112 let node2_commitment_txid;
2114 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2115 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2116 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2117 node2_commitment_txid = node_txn[0].txid();
2119 // Claim the payment on nodes[3], giving it knowledge of the preimage
2120 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2121 mine_transaction(&nodes[3], &node_txn[0]);
2122 check_added_monitors!(nodes[3], 1);
2123 check_preimage_claim(&nodes[3], &node_txn);
2125 check_closed_broadcast!(nodes[3], true);
2126 assert_eq!(nodes[2].node.list_channels().len(), 0);
2127 assert_eq!(nodes[3].node.list_channels().len(), 1);
2128 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2129 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxBroadcasted);
2131 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2132 // confusing us in the following tests.
2133 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2135 // One pending HTLC to time out:
2136 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2137 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2140 let (close_chan_update_1, close_chan_update_2) = {
2141 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2142 let events = nodes[3].node.get_and_clear_pending_msg_events();
2143 assert_eq!(events.len(), 2);
2144 let close_chan_update_1 = match events[0] {
2145 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2148 _ => panic!("Unexpected event"),
2151 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2152 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2154 _ => panic!("Unexpected event"),
2156 check_added_monitors!(nodes[3], 1);
2158 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2160 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2161 node_txn.retain(|tx| {
2162 if tx.input[0].previous_output.txid == node2_commitment_txid {
2168 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2170 // Claim the payment on nodes[4], giving it knowledge of the preimage
2171 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2173 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2174 let events = nodes[4].node.get_and_clear_pending_msg_events();
2175 assert_eq!(events.len(), 2);
2176 let close_chan_update_2 = match events[0] {
2177 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2180 _ => panic!("Unexpected event"),
2183 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2184 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2186 _ => panic!("Unexpected event"),
2188 check_added_monitors!(nodes[4], 1);
2189 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2191 mine_transaction(&nodes[4], &node_txn[0]);
2192 check_preimage_claim(&nodes[4], &node_txn);
2193 (close_chan_update_1, close_chan_update_2)
2195 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2196 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2197 assert_eq!(nodes[3].node.list_channels().len(), 0);
2198 assert_eq!(nodes[4].node.list_channels().len(), 0);
2200 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2201 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxBroadcasted);
2202 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxBroadcasted);
2206 fn test_justice_tx() {
2207 // Test justice txn built on revoked HTLC-Success tx, against both sides
2208 let mut alice_config = UserConfig::default();
2209 alice_config.channel_options.announced_channel = true;
2210 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2211 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2212 let mut bob_config = UserConfig::default();
2213 bob_config.channel_options.announced_channel = true;
2214 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2215 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2216 let user_cfgs = [Some(alice_config), Some(bob_config)];
2217 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2218 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2219 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2220 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2221 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2222 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2223 // Create some new channels:
2224 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2226 // A pending HTLC which will be revoked:
2227 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2228 // Get the will-be-revoked local txn from nodes[0]
2229 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2230 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2231 assert_eq!(revoked_local_txn[0].input.len(), 1);
2232 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2233 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2234 assert_eq!(revoked_local_txn[1].input.len(), 1);
2235 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2236 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2237 // Revoke the old state
2238 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2241 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2243 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2244 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2245 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2247 check_spends!(node_txn[0], revoked_local_txn[0]);
2248 node_txn.swap_remove(0);
2249 node_txn.truncate(1);
2251 check_added_monitors!(nodes[1], 1);
2252 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2253 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2255 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2256 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2257 // Verify broadcast of revoked HTLC-timeout
2258 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2259 check_added_monitors!(nodes[0], 1);
2260 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
2261 // Broadcast revoked HTLC-timeout on node 1
2262 mine_transaction(&nodes[1], &node_txn[1]);
2263 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2265 get_announce_close_broadcast_events(&nodes, 0, 1);
2267 assert_eq!(nodes[0].node.list_channels().len(), 0);
2268 assert_eq!(nodes[1].node.list_channels().len(), 0);
2270 // We test justice_tx build by A on B's revoked HTLC-Success tx
2271 // Create some new channels:
2272 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2274 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2278 // A pending HTLC which will be revoked:
2279 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2280 // Get the will-be-revoked local txn from B
2281 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2282 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2283 assert_eq!(revoked_local_txn[0].input.len(), 1);
2284 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2285 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2286 // Revoke the old state
2287 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2289 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2291 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2292 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2293 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2295 check_spends!(node_txn[0], revoked_local_txn[0]);
2296 node_txn.swap_remove(0);
2298 check_added_monitors!(nodes[0], 1);
2299 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2301 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2302 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2303 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2304 check_added_monitors!(nodes[1], 1);
2305 mine_transaction(&nodes[0], &node_txn[1]);
2306 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
2307 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2309 get_announce_close_broadcast_events(&nodes, 0, 1);
2310 assert_eq!(nodes[0].node.list_channels().len(), 0);
2311 assert_eq!(nodes[1].node.list_channels().len(), 0);
2315 fn revoked_output_claim() {
2316 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2317 // transaction is broadcast by its counterparty
2318 let chanmon_cfgs = create_chanmon_cfgs(2);
2319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2321 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2322 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2323 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2324 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2325 assert_eq!(revoked_local_txn.len(), 1);
2326 // Only output is the full channel value back to nodes[0]:
2327 assert_eq!(revoked_local_txn[0].output.len(), 1);
2328 // Send a payment through, updating everyone's latest commitment txn
2329 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2331 // Inform nodes[1] that nodes[0] broadcast a stale tx
2332 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2333 check_added_monitors!(nodes[1], 1);
2334 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2335 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2336 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2338 check_spends!(node_txn[0], revoked_local_txn[0]);
2339 check_spends!(node_txn[1], chan_1.3);
2341 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2342 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2343 get_announce_close_broadcast_events(&nodes, 0, 1);
2344 check_added_monitors!(nodes[0], 1);
2345 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
2349 fn claim_htlc_outputs_shared_tx() {
2350 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2351 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2352 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2357 // Create some new channel:
2358 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2360 // Rebalance the network to generate htlc in the two directions
2361 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2362 // 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
2363 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2364 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2366 // Get the will-be-revoked local txn from node[0]
2367 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2368 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2369 assert_eq!(revoked_local_txn[0].input.len(), 1);
2370 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2371 assert_eq!(revoked_local_txn[1].input.len(), 1);
2372 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2373 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2374 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2376 //Revoke the old state
2377 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2380 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2381 check_added_monitors!(nodes[0], 1);
2382 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
2383 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2384 check_added_monitors!(nodes[1], 1);
2385 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2386 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2387 let events = nodes[1].node.get_and_clear_pending_events();
2388 expect_payment_failed!(nodes[1], events, payment_hash_2, true);
2390 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2391 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2393 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2394 check_spends!(node_txn[0], revoked_local_txn[0]);
2396 let mut witness_lens = BTreeSet::new();
2397 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2398 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2399 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2400 assert_eq!(witness_lens.len(), 3);
2401 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2402 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2403 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2405 // Next nodes[1] broadcasts its current local tx state:
2406 assert_eq!(node_txn[1].input.len(), 1);
2407 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2409 get_announce_close_broadcast_events(&nodes, 0, 1);
2410 assert_eq!(nodes[0].node.list_channels().len(), 0);
2411 assert_eq!(nodes[1].node.list_channels().len(), 0);
2415 fn claim_htlc_outputs_single_tx() {
2416 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2417 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2418 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2421 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2423 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2425 // Rebalance the network to generate htlc in the two directions
2426 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2427 // 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
2428 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2429 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2430 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2432 // Get the will-be-revoked local txn from node[0]
2433 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2435 //Revoke the old state
2436 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2439 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2440 check_added_monitors!(nodes[0], 1);
2441 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2442 check_added_monitors!(nodes[1], 1);
2443 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2444 let mut events = nodes[0].node.get_and_clear_pending_events();
2445 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2447 Event::ChannelClosed { .. } => {}
2448 _ => panic!("Unexpected event"),
2451 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2452 let events = nodes[1].node.get_and_clear_pending_events();
2453 expect_payment_failed!(nodes[1], events, payment_hash_2, true);
2455 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2456 assert_eq!(node_txn.len(), 9);
2457 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2458 // ChannelManager: local commmitment + local HTLC-timeout (2)
2459 // 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)
2460 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2462 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2463 assert_eq!(node_txn[0].input.len(), 1);
2464 check_spends!(node_txn[0], chan_1.3);
2465 assert_eq!(node_txn[1].input.len(), 1);
2466 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2467 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2468 check_spends!(node_txn[1], node_txn[0]);
2470 // Justice transactions are indices 1-2-4
2471 assert_eq!(node_txn[2].input.len(), 1);
2472 assert_eq!(node_txn[3].input.len(), 1);
2473 assert_eq!(node_txn[4].input.len(), 1);
2475 check_spends!(node_txn[2], revoked_local_txn[0]);
2476 check_spends!(node_txn[3], revoked_local_txn[0]);
2477 check_spends!(node_txn[4], revoked_local_txn[0]);
2479 let mut witness_lens = BTreeSet::new();
2480 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2481 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2482 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2483 assert_eq!(witness_lens.len(), 3);
2484 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2485 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2486 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2488 get_announce_close_broadcast_events(&nodes, 0, 1);
2489 assert_eq!(nodes[0].node.list_channels().len(), 0);
2490 assert_eq!(nodes[1].node.list_channels().len(), 0);
2494 fn test_htlc_on_chain_success() {
2495 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2496 // the preimage backward accordingly. So here we test that ChannelManager is
2497 // broadcasting the right event to other nodes in payment path.
2498 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2499 // A --------------------> B ----------------------> C (preimage)
2500 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2501 // commitment transaction was broadcast.
2502 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2504 // B should be able to claim via preimage if A then broadcasts its local tx.
2505 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2506 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2507 // PaymentSent event).
2509 let chanmon_cfgs = create_chanmon_cfgs(3);
2510 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2511 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2512 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2514 // Create some initial channels
2515 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2516 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2518 // Ensure all nodes are at the same height
2519 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2520 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2521 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2522 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2524 // Rebalance the network a bit by relaying one payment through all the channels...
2525 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2526 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2528 let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2529 let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2531 // Broadcast legit commitment tx from C on B's chain
2532 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2533 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2534 assert_eq!(commitment_tx.len(), 1);
2535 check_spends!(commitment_tx[0], chan_2.3);
2536 nodes[2].node.claim_funds(our_payment_preimage);
2537 nodes[2].node.claim_funds(our_payment_preimage_2);
2538 check_added_monitors!(nodes[2], 2);
2539 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2540 assert!(updates.update_add_htlcs.is_empty());
2541 assert!(updates.update_fail_htlcs.is_empty());
2542 assert!(updates.update_fail_malformed_htlcs.is_empty());
2543 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2545 mine_transaction(&nodes[2], &commitment_tx[0]);
2546 check_closed_broadcast!(nodes[2], true);
2547 check_added_monitors!(nodes[2], 1);
2548 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxBroadcasted);
2549 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)
2550 assert_eq!(node_txn.len(), 5);
2551 assert_eq!(node_txn[0], node_txn[3]);
2552 assert_eq!(node_txn[1], node_txn[4]);
2553 assert_eq!(node_txn[2], commitment_tx[0]);
2554 check_spends!(node_txn[0], commitment_tx[0]);
2555 check_spends!(node_txn[1], commitment_tx[0]);
2556 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2557 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2558 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2559 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2560 assert_eq!(node_txn[0].lock_time, 0);
2561 assert_eq!(node_txn[1].lock_time, 0);
2563 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2564 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2565 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2566 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2568 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2569 assert_eq!(added_monitors.len(), 1);
2570 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2571 added_monitors.clear();
2573 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2574 assert_eq!(forwarded_events.len(), 3);
2575 match forwarded_events[0] {
2576 Event::ChannelClosed { .. } => {}
2577 _ => panic!("Unexpected event"),
2579 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2580 } else { panic!(); }
2581 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2582 } else { panic!(); }
2583 let events = nodes[1].node.get_and_clear_pending_msg_events();
2585 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2586 assert_eq!(added_monitors.len(), 2);
2587 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2588 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2589 added_monitors.clear();
2591 assert_eq!(events.len(), 3);
2593 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2594 _ => panic!("Unexpected event"),
2597 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2598 _ => panic!("Unexpected event"),
2602 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, .. } } => {
2603 assert!(update_add_htlcs.is_empty());
2604 assert!(update_fail_htlcs.is_empty());
2605 assert_eq!(update_fulfill_htlcs.len(), 1);
2606 assert!(update_fail_malformed_htlcs.is_empty());
2607 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2609 _ => panic!("Unexpected event"),
2611 macro_rules! check_tx_local_broadcast {
2612 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2613 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2614 assert_eq!(node_txn.len(), 3);
2615 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2616 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2617 check_spends!(node_txn[1], $commitment_tx);
2618 check_spends!(node_txn[2], $commitment_tx);
2619 assert_ne!(node_txn[1].lock_time, 0);
2620 assert_ne!(node_txn[2].lock_time, 0);
2622 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2623 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2624 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2625 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2627 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2628 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2629 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2630 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2632 check_spends!(node_txn[0], $chan_tx);
2633 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2637 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2638 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2639 // timeout-claim of the output that nodes[2] just claimed via success.
2640 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2642 // Broadcast legit commitment tx from A on B's chain
2643 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2644 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2645 check_spends!(node_a_commitment_tx[0], chan_1.3);
2646 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2647 check_closed_broadcast!(nodes[1], true);
2648 check_added_monitors!(nodes[1], 1);
2649 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2650 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2651 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2652 let commitment_spend =
2653 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2654 check_spends!(node_txn[1], commitment_tx[0]);
2655 check_spends!(node_txn[2], commitment_tx[0]);
2656 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2659 check_spends!(node_txn[0], commitment_tx[0]);
2660 check_spends!(node_txn[1], commitment_tx[0]);
2661 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2665 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2666 assert_eq!(commitment_spend.input.len(), 2);
2667 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2668 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2669 assert_eq!(commitment_spend.lock_time, 0);
2670 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2671 check_spends!(node_txn[3], chan_1.3);
2672 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2673 check_spends!(node_txn[4], node_txn[3]);
2674 check_spends!(node_txn[5], node_txn[3]);
2675 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2676 // we already checked the same situation with A.
2678 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2679 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2680 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2681 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2682 check_closed_broadcast!(nodes[0], true);
2683 check_added_monitors!(nodes[0], 1);
2684 let events = nodes[0].node.get_and_clear_pending_events();
2685 assert_eq!(events.len(), 3);
2686 let mut first_claimed = false;
2687 for event in events {
2689 Event::PaymentSent { payment_preimage } => {
2690 if payment_preimage == our_payment_preimage {
2691 assert!(!first_claimed);
2692 first_claimed = true;
2694 assert_eq!(payment_preimage, our_payment_preimage_2);
2697 Event::ChannelClosed { .. } => {},
2698 _ => panic!("Unexpected event"),
2701 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2704 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2705 // Test that in case of a unilateral close onchain, we detect the state of output and
2706 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2707 // broadcasting the right event to other nodes in payment path.
2708 // A ------------------> B ----------------------> C (timeout)
2709 // B's commitment tx C's commitment tx
2711 // B's HTLC timeout tx B's timeout tx
2713 let chanmon_cfgs = create_chanmon_cfgs(3);
2714 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2715 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2716 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2717 *nodes[0].connect_style.borrow_mut() = connect_style;
2718 *nodes[1].connect_style.borrow_mut() = connect_style;
2719 *nodes[2].connect_style.borrow_mut() = connect_style;
2721 // Create some intial channels
2722 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2723 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2725 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2726 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2727 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2729 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2731 // Broadcast legit commitment tx from C on B's chain
2732 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2733 check_spends!(commitment_tx[0], chan_2.3);
2734 nodes[2].node.fail_htlc_backwards(&payment_hash);
2735 check_added_monitors!(nodes[2], 0);
2736 expect_pending_htlcs_forwardable!(nodes[2]);
2737 check_added_monitors!(nodes[2], 1);
2739 let events = nodes[2].node.get_and_clear_pending_msg_events();
2740 assert_eq!(events.len(), 1);
2742 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, .. } } => {
2743 assert!(update_add_htlcs.is_empty());
2744 assert!(!update_fail_htlcs.is_empty());
2745 assert!(update_fulfill_htlcs.is_empty());
2746 assert!(update_fail_malformed_htlcs.is_empty());
2747 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2749 _ => panic!("Unexpected event"),
2751 mine_transaction(&nodes[2], &commitment_tx[0]);
2752 check_closed_broadcast!(nodes[2], true);
2753 check_added_monitors!(nodes[2], 1);
2754 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxBroadcasted);
2755 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2756 assert_eq!(node_txn.len(), 1);
2757 check_spends!(node_txn[0], chan_2.3);
2758 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2760 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2761 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2762 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2763 mine_transaction(&nodes[1], &commitment_tx[0]);
2764 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2767 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2768 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2769 assert_eq!(node_txn[0], node_txn[3]);
2770 assert_eq!(node_txn[1], node_txn[4]);
2772 check_spends!(node_txn[2], commitment_tx[0]);
2773 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2775 check_spends!(node_txn[0], chan_2.3);
2776 check_spends!(node_txn[1], node_txn[0]);
2777 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2778 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2780 timeout_tx = node_txn[2].clone();
2784 mine_transaction(&nodes[1], &timeout_tx);
2785 check_added_monitors!(nodes[1], 1);
2786 check_closed_broadcast!(nodes[1], true);
2788 // B will rebroadcast a fee-bumped timeout transaction here.
2789 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2790 assert_eq!(node_txn.len(), 1);
2791 check_spends!(node_txn[0], commitment_tx[0]);
2794 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2796 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2797 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2798 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2799 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2800 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2801 if node_txn.len() == 1 {
2802 check_spends!(node_txn[0], chan_2.3);
2804 assert_eq!(node_txn.len(), 0);
2808 expect_pending_htlcs_forwardable!(nodes[1]);
2809 check_added_monitors!(nodes[1], 1);
2810 let events = nodes[1].node.get_and_clear_pending_msg_events();
2811 assert_eq!(events.len(), 1);
2813 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, .. } } => {
2814 assert!(update_add_htlcs.is_empty());
2815 assert!(!update_fail_htlcs.is_empty());
2816 assert!(update_fulfill_htlcs.is_empty());
2817 assert!(update_fail_malformed_htlcs.is_empty());
2818 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2820 _ => panic!("Unexpected event"),
2823 // Broadcast legit commitment tx from B on A's chain
2824 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2825 check_spends!(commitment_tx[0], chan_1.3);
2827 mine_transaction(&nodes[0], &commitment_tx[0]);
2828 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2830 check_closed_broadcast!(nodes[0], true);
2831 check_added_monitors!(nodes[0], 1);
2832 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
2833 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2834 assert_eq!(node_txn.len(), 2);
2835 check_spends!(node_txn[0], chan_1.3);
2836 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2837 check_spends!(node_txn[1], commitment_tx[0]);
2838 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842 fn test_htlc_on_chain_timeout() {
2843 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2844 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2845 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2849 fn test_simple_commitment_revoked_fail_backward() {
2850 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2851 // and fail backward accordingly.
2853 let chanmon_cfgs = create_chanmon_cfgs(3);
2854 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2855 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2856 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2858 // Create some initial channels
2859 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2860 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2862 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2863 // Get the will-be-revoked local txn from nodes[2]
2864 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2865 // Revoke the old state
2866 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2868 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2870 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2871 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
2872 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2873 check_added_monitors!(nodes[1], 1);
2874 check_closed_broadcast!(nodes[1], true);
2876 expect_pending_htlcs_forwardable!(nodes[1]);
2877 check_added_monitors!(nodes[1], 1);
2878 let events = nodes[1].node.get_and_clear_pending_msg_events();
2879 assert_eq!(events.len(), 1);
2881 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, .. } } => {
2882 assert!(update_add_htlcs.is_empty());
2883 assert_eq!(update_fail_htlcs.len(), 1);
2884 assert!(update_fulfill_htlcs.is_empty());
2885 assert!(update_fail_malformed_htlcs.is_empty());
2886 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2888 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2889 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2890 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2892 _ => panic!("Unexpected event"),
2896 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2897 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2898 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2899 // commitment transaction anymore.
2900 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2901 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2902 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2903 // technically disallowed and we should probably handle it reasonably.
2904 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2905 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2907 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2908 // commitment_signed (implying it will be in the latest remote commitment transaction).
2909 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2910 // and once they revoke the previous commitment transaction (allowing us to send a new
2911 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2912 let chanmon_cfgs = create_chanmon_cfgs(3);
2913 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2914 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2915 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2917 // Create some initial channels
2918 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2919 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2921 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 });
2922 // Get the will-be-revoked local txn from nodes[2]
2923 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2924 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2925 // Revoke the old state
2926 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2928 let value = if use_dust {
2929 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2930 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2931 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2934 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2935 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2936 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2938 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2939 expect_pending_htlcs_forwardable!(nodes[2]);
2940 check_added_monitors!(nodes[2], 1);
2941 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2942 assert!(updates.update_add_htlcs.is_empty());
2943 assert!(updates.update_fulfill_htlcs.is_empty());
2944 assert!(updates.update_fail_malformed_htlcs.is_empty());
2945 assert_eq!(updates.update_fail_htlcs.len(), 1);
2946 assert!(updates.update_fee.is_none());
2947 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2948 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2949 // Drop the last RAA from 3 -> 2
2951 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2952 expect_pending_htlcs_forwardable!(nodes[2]);
2953 check_added_monitors!(nodes[2], 1);
2954 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2955 assert!(updates.update_add_htlcs.is_empty());
2956 assert!(updates.update_fulfill_htlcs.is_empty());
2957 assert!(updates.update_fail_malformed_htlcs.is_empty());
2958 assert_eq!(updates.update_fail_htlcs.len(), 1);
2959 assert!(updates.update_fee.is_none());
2960 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2961 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2962 check_added_monitors!(nodes[1], 1);
2963 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2964 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2965 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2966 check_added_monitors!(nodes[2], 1);
2968 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2969 expect_pending_htlcs_forwardable!(nodes[2]);
2970 check_added_monitors!(nodes[2], 1);
2971 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2972 assert!(updates.update_add_htlcs.is_empty());
2973 assert!(updates.update_fulfill_htlcs.is_empty());
2974 assert!(updates.update_fail_malformed_htlcs.is_empty());
2975 assert_eq!(updates.update_fail_htlcs.len(), 1);
2976 assert!(updates.update_fee.is_none());
2977 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2978 // At this point first_payment_hash has dropped out of the latest two commitment
2979 // transactions that nodes[1] is tracking...
2980 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2981 check_added_monitors!(nodes[1], 1);
2982 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2983 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2984 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2985 check_added_monitors!(nodes[2], 1);
2987 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2988 // on nodes[2]'s RAA.
2989 let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
2990 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2991 let logger = test_utils::TestLogger::new();
2992 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();
2993 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2994 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2995 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2996 check_added_monitors!(nodes[1], 0);
2999 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3000 // One monitor for the new revocation preimage, no second on as we won't generate a new
3001 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3002 check_added_monitors!(nodes[1], 1);
3003 let events = nodes[1].node.get_and_clear_pending_events();
3004 assert_eq!(events.len(), 1);
3006 Event::PendingHTLCsForwardable { .. } => { },
3007 _ => panic!("Unexpected event"),
3009 // Deliberately don't process the pending fail-back so they all fail back at once after
3010 // block connection just like the !deliver_bs_raa case
3013 let mut failed_htlcs = HashSet::new();
3014 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3016 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3017 check_added_monitors!(nodes[1], 1);
3018 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3020 let events = nodes[1].node.get_and_clear_pending_events();
3021 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3023 Event::ChannelClosed { .. } => { },
3024 _ => panic!("Unexepected event"),
3027 Event::PaymentFailed { ref payment_hash, .. } => {
3028 assert_eq!(*payment_hash, fourth_payment_hash);
3030 _ => panic!("Unexpected event"),
3032 if !deliver_bs_raa {
3034 Event::PendingHTLCsForwardable { .. } => { },
3035 _ => panic!("Unexpected event"),
3038 nodes[1].node.process_pending_htlc_forwards();
3039 check_added_monitors!(nodes[1], 1);
3041 let events = nodes[1].node.get_and_clear_pending_msg_events();
3042 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3043 match events[if deliver_bs_raa { 1 } else { 0 }] {
3044 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3045 _ => panic!("Unexpected event"),
3047 match events[if deliver_bs_raa { 2 } else { 1 }] {
3048 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3049 assert_eq!(channel_id, chan_2.2);
3050 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3052 _ => panic!("Unexpected event"),
3056 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, .. } } => {
3057 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3058 assert_eq!(update_add_htlcs.len(), 1);
3059 assert!(update_fulfill_htlcs.is_empty());
3060 assert!(update_fail_htlcs.is_empty());
3061 assert!(update_fail_malformed_htlcs.is_empty());
3063 _ => panic!("Unexpected event"),
3066 match events[if deliver_bs_raa { 3 } else { 2 }] {
3067 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, .. } } => {
3068 assert!(update_add_htlcs.is_empty());
3069 assert_eq!(update_fail_htlcs.len(), 3);
3070 assert!(update_fulfill_htlcs.is_empty());
3071 assert!(update_fail_malformed_htlcs.is_empty());
3072 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3074 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3075 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3076 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3078 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3080 let events = nodes[0].node.get_and_clear_pending_events();
3081 assert_eq!(events.len(), 3);
3083 Event::PaymentFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3084 assert!(failed_htlcs.insert(payment_hash.0));
3085 // If we delivered B's RAA we got an unknown preimage error, not something
3086 // that we should update our routing table for.
3087 if !deliver_bs_raa {
3088 assert!(network_update.is_some());
3091 _ => panic!("Unexpected event"),
3094 Event::PaymentFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3095 assert!(failed_htlcs.insert(payment_hash.0));
3096 assert!(network_update.is_some());
3098 _ => panic!("Unexpected event"),
3101 Event::PaymentFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3102 assert!(failed_htlcs.insert(payment_hash.0));
3103 assert!(network_update.is_some());
3105 _ => panic!("Unexpected event"),
3108 _ => panic!("Unexpected event"),
3111 assert!(failed_htlcs.contains(&first_payment_hash.0));
3112 assert!(failed_htlcs.contains(&second_payment_hash.0));
3113 assert!(failed_htlcs.contains(&third_payment_hash.0));
3117 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3118 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3119 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3120 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3121 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3125 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3126 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3127 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3128 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3129 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3133 fn fail_backward_pending_htlc_upon_channel_failure() {
3134 let chanmon_cfgs = create_chanmon_cfgs(2);
3135 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3136 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3137 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3138 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3139 let logger = test_utils::TestLogger::new();
3141 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3143 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3144 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3145 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();
3146 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3147 check_added_monitors!(nodes[0], 1);
3149 let payment_event = {
3150 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3151 assert_eq!(events.len(), 1);
3152 SendEvent::from_event(events.remove(0))
3154 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3155 assert_eq!(payment_event.msgs.len(), 1);
3158 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3159 let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3161 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3162 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();
3163 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3164 check_added_monitors!(nodes[0], 0);
3166 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3169 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3171 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3173 let secp_ctx = Secp256k1::new();
3174 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3175 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3176 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3177 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();
3178 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3179 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3180 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3182 // Send a 0-msat update_add_htlc to fail the channel.
3183 let update_add_htlc = msgs::UpdateAddHTLC {
3189 onion_routing_packet,
3191 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3193 let events = nodes[0].node.get_and_clear_pending_events();
3194 // Check that Alice fails backward the pending HTLC from the second payment.
3195 expect_payment_failed!(nodes[0], events[0..1].to_vec(), failed_payment_hash, true);
3197 Event::ChannelClosed { .. } => {}
3198 _ => panic!("Unexpected event"),
3200 check_closed_broadcast!(nodes[0], true);
3201 check_added_monitors!(nodes[0], 1);
3205 fn test_htlc_ignore_latest_remote_commitment() {
3206 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3207 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3208 let chanmon_cfgs = create_chanmon_cfgs(2);
3209 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3210 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3211 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3212 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3214 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3215 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3216 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3217 check_closed_broadcast!(nodes[0], true);
3218 check_added_monitors!(nodes[0], 1);
3219 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3221 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3222 assert_eq!(node_txn.len(), 3);
3223 assert_eq!(node_txn[0], node_txn[1]);
3225 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3226 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3227 check_closed_broadcast!(nodes[1], true);
3228 check_added_monitors!(nodes[1], 1);
3229 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
3231 // Duplicate the connect_block call since this may happen due to other listeners
3232 // registering new transactions
3233 header.prev_blockhash = header.block_hash();
3234 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3238 fn test_force_close_fail_back() {
3239 // Check which HTLCs are failed-backwards on channel force-closure
3240 let chanmon_cfgs = create_chanmon_cfgs(3);
3241 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3242 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3243 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3244 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3245 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3246 let logger = test_utils::TestLogger::new();
3248 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3250 let mut payment_event = {
3251 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3252 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();
3253 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3254 check_added_monitors!(nodes[0], 1);
3256 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3257 assert_eq!(events.len(), 1);
3258 SendEvent::from_event(events.remove(0))
3261 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3262 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3264 expect_pending_htlcs_forwardable!(nodes[1]);
3266 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3267 assert_eq!(events_2.len(), 1);
3268 payment_event = SendEvent::from_event(events_2.remove(0));
3269 assert_eq!(payment_event.msgs.len(), 1);
3271 check_added_monitors!(nodes[1], 1);
3272 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3273 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3274 check_added_monitors!(nodes[2], 1);
3275 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3277 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3278 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3279 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3281 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3282 check_closed_broadcast!(nodes[2], true);
3283 check_added_monitors!(nodes[2], 1);
3284 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3286 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3287 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3288 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3289 // back to nodes[1] upon timeout otherwise.
3290 assert_eq!(node_txn.len(), 1);
3294 mine_transaction(&nodes[1], &tx);
3296 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3297 check_closed_broadcast!(nodes[1], true);
3298 check_added_monitors!(nodes[1], 1);
3299 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
3301 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3303 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3304 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3305 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3307 mine_transaction(&nodes[2], &tx);
3308 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3309 assert_eq!(node_txn.len(), 1);
3310 assert_eq!(node_txn[0].input.len(), 1);
3311 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3312 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3313 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3315 check_spends!(node_txn[0], tx);
3319 fn test_dup_events_on_peer_disconnect() {
3320 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3321 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3322 // as we used to generate the event immediately upon receipt of the payment preimage in the
3323 // update_fulfill_htlc message.
3325 let chanmon_cfgs = create_chanmon_cfgs(2);
3326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3328 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3329 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3331 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3333 assert!(nodes[1].node.claim_funds(payment_preimage));
3334 check_added_monitors!(nodes[1], 1);
3335 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3336 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3337 let events = nodes[0].node.get_and_clear_pending_events();
3338 expect_payment_sent!(nodes[0], payment_preimage, events);
3340 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3341 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3343 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3344 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3348 fn test_simple_peer_disconnect() {
3349 // Test that we can reconnect when there are no lost messages
3350 let chanmon_cfgs = create_chanmon_cfgs(3);
3351 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3352 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3353 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3354 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3355 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3357 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3358 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3359 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3361 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3362 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3363 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3364 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3366 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3367 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3368 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3370 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3371 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3372 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3373 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3375 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3376 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3378 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3379 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3381 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3383 let events = nodes[0].node.get_and_clear_pending_events();
3384 assert_eq!(events.len(), 2);
3386 Event::PaymentSent { payment_preimage } => {
3387 assert_eq!(payment_preimage, payment_preimage_3);
3389 _ => panic!("Unexpected event"),
3392 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3393 assert_eq!(payment_hash, payment_hash_5);
3394 assert!(rejected_by_dest);
3396 _ => panic!("Unexpected event"),
3400 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3401 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3404 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3405 // Test that we can reconnect when in-flight HTLC updates get dropped
3406 let chanmon_cfgs = create_chanmon_cfgs(2);
3407 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3408 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3409 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3411 let mut as_funding_locked = None;
3412 if messages_delivered == 0 {
3413 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3414 as_funding_locked = Some(funding_locked);
3415 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3416 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3417 // it before the channel_reestablish message.
3419 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3422 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3424 let logger = test_utils::TestLogger::new();
3425 let payment_event = {
3426 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3427 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3428 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3429 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3430 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3431 check_added_monitors!(nodes[0], 1);
3433 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3434 assert_eq!(events.len(), 1);
3435 SendEvent::from_event(events.remove(0))
3437 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3439 if messages_delivered < 2 {
3440 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3442 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3443 if messages_delivered >= 3 {
3444 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3445 check_added_monitors!(nodes[1], 1);
3446 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3448 if messages_delivered >= 4 {
3449 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3450 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3451 check_added_monitors!(nodes[0], 1);
3453 if messages_delivered >= 5 {
3454 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3455 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3456 // No commitment_signed so get_event_msg's assert(len == 1) passes
3457 check_added_monitors!(nodes[0], 1);
3459 if messages_delivered >= 6 {
3460 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3461 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3462 check_added_monitors!(nodes[1], 1);
3469 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3470 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3471 if messages_delivered < 3 {
3472 if simulate_broken_lnd {
3473 // lnd has a long-standing bug where they send a funding_locked prior to a
3474 // channel_reestablish if you reconnect prior to funding_locked time.
3476 // Here we simulate that behavior, delivering a funding_locked immediately on
3477 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3478 // in `reconnect_nodes` but we currently don't fail based on that.
3480 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3481 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3483 // Even if the funding_locked messages get exchanged, as long as nothing further was
3484 // received on either side, both sides will need to resend them.
3485 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3486 } else if messages_delivered == 3 {
3487 // nodes[0] still wants its RAA + commitment_signed
3488 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3489 } else if messages_delivered == 4 {
3490 // nodes[0] still wants its commitment_signed
3491 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3492 } else if messages_delivered == 5 {
3493 // nodes[1] still wants its final RAA
3494 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3495 } else if messages_delivered == 6 {
3496 // Everything was delivered...
3497 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3500 let events_1 = nodes[1].node.get_and_clear_pending_events();
3501 assert_eq!(events_1.len(), 1);
3503 Event::PendingHTLCsForwardable { .. } => { },
3504 _ => panic!("Unexpected event"),
3507 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3508 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3509 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3511 nodes[1].node.process_pending_htlc_forwards();
3513 let events_2 = nodes[1].node.get_and_clear_pending_events();
3514 assert_eq!(events_2.len(), 1);
3516 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3517 assert_eq!(payment_hash_1, *payment_hash);
3518 assert_eq!(amt, 1000000);
3520 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3521 assert!(payment_preimage.is_none());
3522 assert_eq!(payment_secret_1, *payment_secret);
3524 _ => panic!("expected PaymentPurpose::InvoicePayment")
3527 _ => panic!("Unexpected event"),
3530 nodes[1].node.claim_funds(payment_preimage_1);
3531 check_added_monitors!(nodes[1], 1);
3533 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3534 assert_eq!(events_3.len(), 1);
3535 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3536 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3537 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3538 assert!(updates.update_add_htlcs.is_empty());
3539 assert!(updates.update_fail_htlcs.is_empty());
3540 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3541 assert!(updates.update_fail_malformed_htlcs.is_empty());
3542 assert!(updates.update_fee.is_none());
3543 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3545 _ => panic!("Unexpected event"),
3548 if messages_delivered >= 1 {
3549 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3551 let events_4 = nodes[0].node.get_and_clear_pending_events();
3552 assert_eq!(events_4.len(), 1);
3554 Event::PaymentSent { ref payment_preimage } => {
3555 assert_eq!(payment_preimage_1, *payment_preimage);
3557 _ => panic!("Unexpected event"),
3560 if messages_delivered >= 2 {
3561 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3562 check_added_monitors!(nodes[0], 1);
3563 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3565 if messages_delivered >= 3 {
3566 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3567 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3568 check_added_monitors!(nodes[1], 1);
3570 if messages_delivered >= 4 {
3571 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3572 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3573 // No commitment_signed so get_event_msg's assert(len == 1) passes
3574 check_added_monitors!(nodes[1], 1);
3576 if messages_delivered >= 5 {
3577 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3578 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3579 check_added_monitors!(nodes[0], 1);
3586 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3587 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3588 if messages_delivered < 2 {
3589 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3590 if messages_delivered < 1 {
3591 let events_4 = nodes[0].node.get_and_clear_pending_events();
3592 assert_eq!(events_4.len(), 1);
3594 Event::PaymentSent { ref payment_preimage } => {
3595 assert_eq!(payment_preimage_1, *payment_preimage);
3597 _ => panic!("Unexpected event"),
3600 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3602 } else if messages_delivered == 2 {
3603 // nodes[0] still wants its RAA + commitment_signed
3604 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3605 } else if messages_delivered == 3 {
3606 // nodes[0] still wants its commitment_signed
3607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3608 } else if messages_delivered == 4 {
3609 // nodes[1] still wants its final RAA
3610 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3611 } else if messages_delivered == 5 {
3612 // Everything was delivered...
3613 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3616 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3617 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3618 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3620 // Channel should still work fine...
3621 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3622 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3623 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3624 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3625 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3626 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3630 fn test_drop_messages_peer_disconnect_a() {
3631 do_test_drop_messages_peer_disconnect(0, true);
3632 do_test_drop_messages_peer_disconnect(0, false);
3633 do_test_drop_messages_peer_disconnect(1, false);
3634 do_test_drop_messages_peer_disconnect(2, false);
3638 fn test_drop_messages_peer_disconnect_b() {
3639 do_test_drop_messages_peer_disconnect(3, false);
3640 do_test_drop_messages_peer_disconnect(4, false);
3641 do_test_drop_messages_peer_disconnect(5, false);
3642 do_test_drop_messages_peer_disconnect(6, false);
3646 fn test_funding_peer_disconnect() {
3647 // Test that we can lock in our funding tx while disconnected
3648 let chanmon_cfgs = create_chanmon_cfgs(2);
3649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3651 let persister: test_utils::TestPersister;
3652 let new_chain_monitor: test_utils::TestChainMonitor;
3653 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3654 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3655 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3657 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3658 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3660 confirm_transaction(&nodes[0], &tx);
3661 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3662 assert_eq!(events_1.len(), 1);
3664 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3665 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3667 _ => panic!("Unexpected event"),
3670 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3672 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3673 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3675 confirm_transaction(&nodes[1], &tx);
3676 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3677 assert_eq!(events_2.len(), 2);
3678 let funding_locked = match events_2[0] {
3679 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3680 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3683 _ => panic!("Unexpected event"),
3685 let bs_announcement_sigs = match events_2[1] {
3686 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3687 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3690 _ => panic!("Unexpected event"),
3693 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3696 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3697 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3698 assert_eq!(events_3.len(), 2);
3699 let as_announcement_sigs = match events_3[0] {
3700 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3701 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3704 _ => panic!("Unexpected event"),
3706 let (as_announcement, as_update) = match events_3[1] {
3707 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3708 (msg.clone(), update_msg.clone())
3710 _ => panic!("Unexpected event"),
3713 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3714 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3715 assert_eq!(events_4.len(), 1);
3716 let (_, bs_update) = match events_4[0] {
3717 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3718 (msg.clone(), update_msg.clone())
3720 _ => panic!("Unexpected event"),
3723 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3724 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3725 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3727 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3728 let logger = test_utils::TestLogger::new();
3729 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();
3730 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3731 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3733 // Check that after deserialization and reconnection we can still generate an identical
3734 // channel_announcement from the cached signatures.
3735 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3737 let nodes_0_serialized = nodes[0].node.encode();
3738 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3739 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3741 persister = test_utils::TestPersister::new();
3742 let keys_manager = &chanmon_cfgs[0].keys_manager;
3743 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);
3744 nodes[0].chain_monitor = &new_chain_monitor;
3745 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3746 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3747 &mut chan_0_monitor_read, keys_manager).unwrap();
3748 assert!(chan_0_monitor_read.is_empty());
3750 let mut nodes_0_read = &nodes_0_serialized[..];
3751 let (_, nodes_0_deserialized_tmp) = {
3752 let mut channel_monitors = HashMap::new();
3753 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3754 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3755 default_config: UserConfig::default(),
3757 fee_estimator: node_cfgs[0].fee_estimator,
3758 chain_monitor: nodes[0].chain_monitor,
3759 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3760 logger: nodes[0].logger,
3764 nodes_0_deserialized = nodes_0_deserialized_tmp;
3765 assert!(nodes_0_read.is_empty());
3767 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3768 nodes[0].node = &nodes_0_deserialized;
3769 check_added_monitors!(nodes[0], 1);
3771 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3773 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3774 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3775 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3776 let mut found_announcement = false;
3777 for event in msgs.iter() {
3779 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3780 if *msg == as_announcement { found_announcement = true; }
3782 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3783 _ => panic!("Unexpected event"),
3786 assert!(found_announcement);
3790 fn test_drop_messages_peer_disconnect_dual_htlc() {
3791 // Test that we can handle reconnecting when both sides of a channel have pending
3792 // commitment_updates when we disconnect.
3793 let chanmon_cfgs = create_chanmon_cfgs(2);
3794 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3795 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3796 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3797 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3798 let logger = test_utils::TestLogger::new();
3800 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3802 // Now try to send a second payment which will fail to send
3803 let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
3804 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3805 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();
3806 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3807 check_added_monitors!(nodes[0], 1);
3809 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3810 assert_eq!(events_1.len(), 1);
3812 MessageSendEvent::UpdateHTLCs { .. } => {},
3813 _ => panic!("Unexpected event"),
3816 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3817 check_added_monitors!(nodes[1], 1);
3819 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3820 assert_eq!(events_2.len(), 1);
3822 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 } } => {
3823 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3824 assert!(update_add_htlcs.is_empty());
3825 assert_eq!(update_fulfill_htlcs.len(), 1);
3826 assert!(update_fail_htlcs.is_empty());
3827 assert!(update_fail_malformed_htlcs.is_empty());
3828 assert!(update_fee.is_none());
3830 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3831 let events_3 = nodes[0].node.get_and_clear_pending_events();
3832 assert_eq!(events_3.len(), 1);
3834 Event::PaymentSent { ref payment_preimage } => {
3835 assert_eq!(*payment_preimage, payment_preimage_1);
3837 _ => panic!("Unexpected event"),
3840 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3841 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3842 // No commitment_signed so get_event_msg's assert(len == 1) passes
3843 check_added_monitors!(nodes[0], 1);
3845 _ => panic!("Unexpected event"),
3848 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3849 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3851 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3852 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3853 assert_eq!(reestablish_1.len(), 1);
3854 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3855 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3856 assert_eq!(reestablish_2.len(), 1);
3858 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3859 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3860 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3861 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3863 assert!(as_resp.0.is_none());
3864 assert!(bs_resp.0.is_none());
3866 assert!(bs_resp.1.is_none());
3867 assert!(bs_resp.2.is_none());
3869 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3871 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3872 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3873 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3874 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3875 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3876 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3877 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3878 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3879 // No commitment_signed so get_event_msg's assert(len == 1) passes
3880 check_added_monitors!(nodes[1], 1);
3882 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3883 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3884 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3885 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3886 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3887 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3888 assert!(bs_second_commitment_signed.update_fee.is_none());
3889 check_added_monitors!(nodes[1], 1);
3891 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3892 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3893 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3894 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3895 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3896 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3897 assert!(as_commitment_signed.update_fee.is_none());
3898 check_added_monitors!(nodes[0], 1);
3900 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3901 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3902 // No commitment_signed so get_event_msg's assert(len == 1) passes
3903 check_added_monitors!(nodes[0], 1);
3905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3906 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3907 // No commitment_signed so get_event_msg's assert(len == 1) passes
3908 check_added_monitors!(nodes[1], 1);
3910 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3911 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3912 check_added_monitors!(nodes[1], 1);
3914 expect_pending_htlcs_forwardable!(nodes[1]);
3916 let events_5 = nodes[1].node.get_and_clear_pending_events();
3917 assert_eq!(events_5.len(), 1);
3919 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3920 assert_eq!(payment_hash_2, *payment_hash);
3922 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3923 assert!(payment_preimage.is_none());
3924 assert_eq!(payment_secret_2, *payment_secret);
3926 _ => panic!("expected PaymentPurpose::InvoicePayment")
3929 _ => panic!("Unexpected event"),
3932 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3933 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3934 check_added_monitors!(nodes[0], 1);
3936 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3939 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3940 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3941 // to avoid our counterparty failing the channel.
3942 let chanmon_cfgs = create_chanmon_cfgs(2);
3943 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3944 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3945 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3947 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3948 let logger = test_utils::TestLogger::new();
3950 let our_payment_hash = if send_partial_mpp {
3951 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3952 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();
3953 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
3954 // Use the utility function send_payment_along_path to send the payment with MPP data which
3955 // indicates there are more HTLCs coming.
3956 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.
3957 let mpp_id = MppId([42; 32]);
3958 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, mpp_id, &None).unwrap();
3959 check_added_monitors!(nodes[0], 1);
3960 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3961 assert_eq!(events.len(), 1);
3962 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3963 // hop should *not* yet generate any PaymentReceived event(s).
3964 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3967 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3970 let mut block = Block {
3971 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3974 connect_block(&nodes[0], &block);
3975 connect_block(&nodes[1], &block);
3976 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3977 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3978 block.header.prev_blockhash = block.block_hash();
3979 connect_block(&nodes[0], &block);
3980 connect_block(&nodes[1], &block);
3983 expect_pending_htlcs_forwardable!(nodes[1]);
3985 check_added_monitors!(nodes[1], 1);
3986 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3987 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3988 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3989 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3990 assert!(htlc_timeout_updates.update_fee.is_none());
3992 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3993 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3994 // 100_000 msat as u64, followed by the height at which we failed back above
3995 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3996 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3997 let events = nodes[0].node.get_and_clear_pending_events();
3998 expect_payment_failed!(nodes[0], events, our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4002 fn test_htlc_timeout() {
4003 do_test_htlc_timeout(true);
4004 do_test_htlc_timeout(false);
4007 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4008 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4009 let chanmon_cfgs = create_chanmon_cfgs(3);
4010 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4011 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4012 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4013 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4014 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4016 // Make sure all nodes are at the same starting height
4017 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4018 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4019 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4021 let logger = test_utils::TestLogger::new();
4023 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4024 let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4026 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4027 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();
4028 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4030 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4031 check_added_monitors!(nodes[1], 1);
4033 // Now attempt to route a second payment, which should be placed in the holding cell
4034 let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4036 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4037 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();
4038 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
4039 check_added_monitors!(nodes[0], 1);
4040 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4041 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4042 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4043 expect_pending_htlcs_forwardable!(nodes[1]);
4044 check_added_monitors!(nodes[1], 0);
4046 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4047 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();
4048 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4049 check_added_monitors!(nodes[1], 0);
4052 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4053 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4054 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4055 connect_blocks(&nodes[1], 1);
4058 expect_pending_htlcs_forwardable!(nodes[1]);
4059 check_added_monitors!(nodes[1], 1);
4060 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4061 assert_eq!(fail_commit.len(), 1);
4062 match fail_commit[0] {
4063 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4064 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4065 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4067 _ => unreachable!(),
4069 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4071 let events = nodes[1].node.get_and_clear_pending_events();
4072 expect_payment_failed!(nodes[1], events, second_payment_hash, true);
4077 fn test_holding_cell_htlc_add_timeouts() {
4078 do_test_holding_cell_htlc_add_timeouts(false);
4079 do_test_holding_cell_htlc_add_timeouts(true);
4083 fn test_no_txn_manager_serialize_deserialize() {
4084 let chanmon_cfgs = create_chanmon_cfgs(2);
4085 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4086 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4087 let logger: test_utils::TestLogger;
4088 let fee_estimator: test_utils::TestFeeEstimator;
4089 let persister: test_utils::TestPersister;
4090 let new_chain_monitor: test_utils::TestChainMonitor;
4091 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4092 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4094 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4096 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4098 let nodes_0_serialized = nodes[0].node.encode();
4099 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4100 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4102 logger = test_utils::TestLogger::new();
4103 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4104 persister = test_utils::TestPersister::new();
4105 let keys_manager = &chanmon_cfgs[0].keys_manager;
4106 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4107 nodes[0].chain_monitor = &new_chain_monitor;
4108 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4109 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4110 &mut chan_0_monitor_read, keys_manager).unwrap();
4111 assert!(chan_0_monitor_read.is_empty());
4113 let mut nodes_0_read = &nodes_0_serialized[..];
4114 let config = UserConfig::default();
4115 let (_, nodes_0_deserialized_tmp) = {
4116 let mut channel_monitors = HashMap::new();
4117 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4118 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4119 default_config: config,
4121 fee_estimator: &fee_estimator,
4122 chain_monitor: nodes[0].chain_monitor,
4123 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4128 nodes_0_deserialized = nodes_0_deserialized_tmp;
4129 assert!(nodes_0_read.is_empty());
4131 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4132 nodes[0].node = &nodes_0_deserialized;
4133 assert_eq!(nodes[0].node.list_channels().len(), 1);
4134 check_added_monitors!(nodes[0], 1);
4136 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4137 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4138 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4139 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4141 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4142 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4143 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4144 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4146 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4147 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4148 for node in nodes.iter() {
4149 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4150 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4151 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4154 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4159 let chanmon_cfgs = create_chanmon_cfgs(4);
4160 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4161 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4162 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4164 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4165 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4166 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4167 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4168 let logger = test_utils::TestLogger::new();
4170 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
4171 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4172 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();
4173 let path = route.paths[0].clone();
4174 route.paths.push(path);
4175 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
4176 route.paths[0][0].short_channel_id = chan_1_id;
4177 route.paths[0][1].short_channel_id = chan_3_id;
4178 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
4179 route.paths[1][0].short_channel_id = chan_2_id;
4180 route.paths[1][1].short_channel_id = chan_4_id;
4181 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
4182 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
4186 fn test_dup_htlc_onchain_fails_on_reload() {
4187 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4188 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4189 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4190 // the ChannelMonitor tells it to.
4192 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4193 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4194 // PaymentFailed event appearing). However, because we may not serialize the relevant
4195 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4196 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4197 // and de-duplicates ChannelMonitor events.
4199 // This tests that explicit tracking behavior.
4200 let chanmon_cfgs = create_chanmon_cfgs(2);
4201 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4202 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4203 let persister: test_utils::TestPersister;
4204 let new_chain_monitor: test_utils::TestChainMonitor;
4205 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4206 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4208 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4210 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4212 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4213 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4214 check_closed_broadcast!(nodes[0], true);
4215 check_added_monitors!(nodes[0], 1);
4216 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4218 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4219 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4221 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4222 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4223 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4224 assert_eq!(node_txn.len(), 3);
4225 assert_eq!(node_txn[0], node_txn[1]);
4227 assert!(nodes[1].node.claim_funds(payment_preimage));
4228 check_added_monitors!(nodes[1], 1);
4230 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4231 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4232 check_closed_broadcast!(nodes[1], true);
4233 check_added_monitors!(nodes[1], 1);
4234 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
4235 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4237 header.prev_blockhash = nodes[0].best_block_hash();
4238 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4240 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4241 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4242 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4243 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4244 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4246 header.prev_blockhash = nodes[0].best_block_hash();
4247 let claim_block = Block { header, txdata: claim_txn};
4248 connect_block(&nodes[0], &claim_block);
4249 let events = nodes[0].node.get_and_clear_pending_events();
4250 expect_payment_sent!(nodes[0], payment_preimage, events);
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;
4581 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4582 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4583 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4584 //... and we can even still claim the payment!
4585 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4587 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4588 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4589 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4590 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4591 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4592 assert_eq!(msg_events.len(), 1);
4593 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4595 &ErrorAction::SendErrorMessage { ref msg } => {
4596 assert_eq!(msg.channel_id, channel_id);
4598 _ => panic!("Unexpected event!"),
4603 macro_rules! check_spendable_outputs {
4604 ($node: expr, $keysinterface: expr) => {
4606 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4607 let mut txn = Vec::new();
4608 let mut all_outputs = Vec::new();
4609 let secp_ctx = Secp256k1::new();
4610 for event in events.drain(..) {
4612 Event::SpendableOutputs { mut outputs } => {
4613 for outp in outputs.drain(..) {
4614 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4615 all_outputs.push(outp);
4618 _ => panic!("Unexpected event"),
4621 if all_outputs.len() > 1 {
4622 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) {
4632 fn test_claim_sizeable_push_msat() {
4633 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4634 let chanmon_cfgs = create_chanmon_cfgs(2);
4635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4637 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4639 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4640 nodes[1].node.force_close_channel(&chan.2).unwrap();
4641 check_closed_broadcast!(nodes[1], true);
4642 check_added_monitors!(nodes[1], 1);
4643 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4644 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4645 assert_eq!(node_txn.len(), 1);
4646 check_spends!(node_txn[0], chan.3);
4647 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
4649 mine_transaction(&nodes[1], &node_txn[0]);
4650 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4652 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4653 assert_eq!(spend_txn.len(), 1);
4654 assert_eq!(spend_txn[0].input.len(), 1);
4655 check_spends!(spend_txn[0], node_txn[0]);
4656 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4660 fn test_claim_on_remote_sizeable_push_msat() {
4661 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4662 // to_remote output is encumbered by a P2WPKH
4663 let chanmon_cfgs = create_chanmon_cfgs(2);
4664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4666 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4668 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4669 nodes[0].node.force_close_channel(&chan.2).unwrap();
4670 check_closed_broadcast!(nodes[0], true);
4671 check_added_monitors!(nodes[0], 1);
4672 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4674 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4675 assert_eq!(node_txn.len(), 1);
4676 check_spends!(node_txn[0], chan.3);
4677 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
4679 mine_transaction(&nodes[1], &node_txn[0]);
4680 check_closed_broadcast!(nodes[1], true);
4681 check_added_monitors!(nodes[1], 1);
4682 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
4683 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4685 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4686 assert_eq!(spend_txn.len(), 1);
4687 check_spends!(spend_txn[0], node_txn[0]);
4691 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4692 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4693 // to_remote output is encumbered by a P2WPKH
4695 let chanmon_cfgs = create_chanmon_cfgs(2);
4696 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4697 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4698 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4700 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4701 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4702 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4703 assert_eq!(revoked_local_txn[0].input.len(), 1);
4704 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4706 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4707 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4708 check_closed_broadcast!(nodes[1], true);
4709 check_added_monitors!(nodes[1], 1);
4710 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
4712 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4713 mine_transaction(&nodes[1], &node_txn[0]);
4714 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4716 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4717 assert_eq!(spend_txn.len(), 3);
4718 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4719 check_spends!(spend_txn[1], node_txn[0]);
4720 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4724 fn test_static_spendable_outputs_preimage_tx() {
4725 let chanmon_cfgs = create_chanmon_cfgs(2);
4726 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4727 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4728 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4730 // Create some initial channels
4731 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4733 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4735 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4736 assert_eq!(commitment_tx[0].input.len(), 1);
4737 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4739 // Settle A's commitment tx on B's chain
4740 assert!(nodes[1].node.claim_funds(payment_preimage));
4741 check_added_monitors!(nodes[1], 1);
4742 mine_transaction(&nodes[1], &commitment_tx[0]);
4743 check_added_monitors!(nodes[1], 1);
4744 let events = nodes[1].node.get_and_clear_pending_msg_events();
4746 MessageSendEvent::UpdateHTLCs { .. } => {},
4747 _ => panic!("Unexpected event"),
4750 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4751 _ => panic!("Unexepected event"),
4754 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4755 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4756 assert_eq!(node_txn.len(), 3);
4757 check_spends!(node_txn[0], commitment_tx[0]);
4758 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4759 check_spends!(node_txn[1], chan_1.3);
4760 check_spends!(node_txn[2], node_txn[1]);
4762 mine_transaction(&nodes[1], &node_txn[0]);
4763 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
4764 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4766 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4767 assert_eq!(spend_txn.len(), 1);
4768 check_spends!(spend_txn[0], node_txn[0]);
4772 fn test_static_spendable_outputs_timeout_tx() {
4773 let chanmon_cfgs = create_chanmon_cfgs(2);
4774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4776 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4778 // Create some initial channels
4779 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4781 // Rebalance the network a bit by relaying one payment through all the channels ...
4782 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4784 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4786 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4787 assert_eq!(commitment_tx[0].input.len(), 1);
4788 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4790 // Settle A's commitment tx on B' chain
4791 mine_transaction(&nodes[1], &commitment_tx[0]);
4792 check_added_monitors!(nodes[1], 1);
4793 let events = nodes[1].node.get_and_clear_pending_msg_events();
4795 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4796 _ => panic!("Unexpected event"),
4798 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4800 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4801 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4802 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4803 check_spends!(node_txn[0], chan_1.3.clone());
4804 check_spends!(node_txn[1], commitment_tx[0].clone());
4805 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4807 mine_transaction(&nodes[1], &node_txn[1]);
4808 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
4809 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4810 let events = nodes[1].node.get_and_clear_pending_events();
4811 expect_payment_failed!(nodes[1], events, 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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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 { .. } => {}
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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::CommitmentTxBroadcasted);
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]);
5450 let events = nodes[2].node.get_and_clear_pending_events();
5451 if deliver_last_raa {
5452 assert_eq!(events.len(), 2);
5454 Event::ChannelClosed { .. } => {}
5455 _ => panic!("Unexpected event"),
5457 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5458 check_closed_broadcast!(nodes[2], true);
5459 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5461 assert_eq!(events.len(), 1);
5463 Event::ChannelClosed { .. } => {}
5464 _ => panic!("Unexpected event"),
5466 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5467 check_closed_broadcast!(nodes[2], true);
5468 expect_pending_htlcs_forwardable!(nodes[2]);
5471 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5472 let events = nodes[2].node.get_and_clear_pending_events();
5473 if deliver_last_raa {
5474 assert_eq!(events.len(), 2);
5476 Event::ChannelClosed { .. } => {}
5477 _ => panic!("Unexpected event"),
5479 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5480 check_closed_broadcast!(nodes[2], true);
5481 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5483 assert_eq!(events.len(), 1);
5485 Event::ChannelClosed { .. } => {}
5486 _ => panic!("Unexpected event"),
5488 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5489 check_closed_broadcast!(nodes[2], true);
5490 expect_pending_htlcs_forwardable!(nodes[2]);
5493 check_added_monitors!(nodes[2], 3);
5495 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5496 assert_eq!(cs_msgs.len(), 2);
5497 let mut a_done = false;
5498 for msg in cs_msgs {
5500 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5501 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5502 // should be failed-backwards here.
5503 let target = if *node_id == nodes[0].node.get_our_node_id() {
5504 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5505 for htlc in &updates.update_fail_htlcs {
5506 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 });
5508 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5513 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5514 for htlc in &updates.update_fail_htlcs {
5515 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5517 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5518 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5521 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5522 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5523 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5524 if announce_latest {
5525 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5526 if *node_id == nodes[0].node.get_our_node_id() {
5527 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5530 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5532 _ => panic!("Unexpected event"),
5536 let as_events = nodes[0].node.get_and_clear_pending_events();
5537 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5538 let mut as_failds = HashSet::new();
5539 let mut as_updates = 0;
5540 for event in as_events.iter() {
5541 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5542 assert!(as_failds.insert(*payment_hash));
5543 if *payment_hash != payment_hash_2 {
5544 assert_eq!(*rejected_by_dest, deliver_last_raa);
5546 assert!(!rejected_by_dest);
5548 if network_update.is_some() {
5551 } else { panic!("Unexpected event"); }
5553 assert!(as_failds.contains(&payment_hash_1));
5554 assert!(as_failds.contains(&payment_hash_2));
5555 if announce_latest {
5556 assert!(as_failds.contains(&payment_hash_3));
5557 assert!(as_failds.contains(&payment_hash_5));
5559 assert!(as_failds.contains(&payment_hash_6));
5561 let bs_events = nodes[1].node.get_and_clear_pending_events();
5562 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5563 let mut bs_failds = HashSet::new();
5564 let mut bs_updates = 0;
5565 for event in bs_events.iter() {
5566 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5567 assert!(bs_failds.insert(*payment_hash));
5568 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5569 assert_eq!(*rejected_by_dest, deliver_last_raa);
5571 assert!(!rejected_by_dest);
5573 if network_update.is_some() {
5576 } else { panic!("Unexpected event"); }
5578 assert!(bs_failds.contains(&payment_hash_1));
5579 assert!(bs_failds.contains(&payment_hash_2));
5580 if announce_latest {
5581 assert!(bs_failds.contains(&payment_hash_4));
5583 assert!(bs_failds.contains(&payment_hash_5));
5585 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5586 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5587 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5588 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5589 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5590 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5594 fn test_fail_backwards_latest_remote_announce_a() {
5595 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5599 fn test_fail_backwards_latest_remote_announce_b() {
5600 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5604 fn test_fail_backwards_previous_remote_announce() {
5605 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5606 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5607 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5611 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5612 let chanmon_cfgs = create_chanmon_cfgs(2);
5613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5617 // Create some initial channels
5618 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5620 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5621 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5622 assert_eq!(local_txn[0].input.len(), 1);
5623 check_spends!(local_txn[0], chan_1.3);
5625 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5626 mine_transaction(&nodes[0], &local_txn[0]);
5627 check_closed_broadcast!(nodes[0], true);
5628 check_added_monitors!(nodes[0], 1);
5629 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
5630 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5632 let htlc_timeout = {
5633 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5634 assert_eq!(node_txn.len(), 2);
5635 check_spends!(node_txn[0], chan_1.3);
5636 assert_eq!(node_txn[1].input.len(), 1);
5637 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5638 check_spends!(node_txn[1], local_txn[0]);
5642 mine_transaction(&nodes[0], &htlc_timeout);
5643 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5644 let events = nodes[0].node.get_and_clear_pending_events();
5645 expect_payment_failed!(nodes[0], events, our_payment_hash, true);
5647 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5648 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5649 assert_eq!(spend_txn.len(), 3);
5650 check_spends!(spend_txn[0], local_txn[0]);
5651 assert_eq!(spend_txn[1].input.len(), 1);
5652 check_spends!(spend_txn[1], htlc_timeout);
5653 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5654 assert_eq!(spend_txn[2].input.len(), 2);
5655 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5656 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5657 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5661 fn test_key_derivation_params() {
5662 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5663 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5664 // let us re-derive the channel key set to then derive a delayed_payment_key.
5666 let chanmon_cfgs = create_chanmon_cfgs(3);
5668 // We manually create the node configuration to backup the seed.
5669 let seed = [42; 32];
5670 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5671 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);
5672 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() };
5673 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5674 node_cfgs.remove(0);
5675 node_cfgs.insert(0, node);
5677 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5678 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5680 // Create some initial channels
5681 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5683 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5684 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5685 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5687 // Ensure all nodes are at the same height
5688 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5689 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5690 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5691 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5693 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5694 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5695 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5696 assert_eq!(local_txn_1[0].input.len(), 1);
5697 check_spends!(local_txn_1[0], chan_1.3);
5699 // We check funding pubkey are unique
5700 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]));
5701 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]));
5702 if from_0_funding_key_0 == from_1_funding_key_0
5703 || from_0_funding_key_0 == from_1_funding_key_1
5704 || from_0_funding_key_1 == from_1_funding_key_0
5705 || from_0_funding_key_1 == from_1_funding_key_1 {
5706 panic!("Funding pubkeys aren't unique");
5709 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5710 mine_transaction(&nodes[0], &local_txn_1[0]);
5711 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5712 check_closed_broadcast!(nodes[0], true);
5713 check_added_monitors!(nodes[0], 1);
5714 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
5716 let htlc_timeout = {
5717 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5718 assert_eq!(node_txn[1].input.len(), 1);
5719 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5720 check_spends!(node_txn[1], local_txn_1[0]);
5724 mine_transaction(&nodes[0], &htlc_timeout);
5725 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5726 let events = nodes[0].node.get_and_clear_pending_events();
5727 expect_payment_failed!(nodes[0], events, our_payment_hash, true);
5729 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5730 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5731 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5732 assert_eq!(spend_txn.len(), 3);
5733 check_spends!(spend_txn[0], local_txn_1[0]);
5734 assert_eq!(spend_txn[1].input.len(), 1);
5735 check_spends!(spend_txn[1], htlc_timeout);
5736 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5737 assert_eq!(spend_txn[2].input.len(), 2);
5738 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5739 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5740 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5744 fn test_static_output_closing_tx() {
5745 let chanmon_cfgs = create_chanmon_cfgs(2);
5746 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5747 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5748 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5750 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5752 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5753 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5755 mine_transaction(&nodes[0], &closing_tx);
5756 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5757 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5759 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5760 assert_eq!(spend_txn.len(), 1);
5761 check_spends!(spend_txn[0], closing_tx);
5763 mine_transaction(&nodes[1], &closing_tx);
5764 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5765 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5767 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5768 assert_eq!(spend_txn.len(), 1);
5769 check_spends!(spend_txn[0], closing_tx);
5772 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5773 let chanmon_cfgs = create_chanmon_cfgs(2);
5774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5776 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5777 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5779 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5781 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5782 // present in B's local commitment transaction, but none of A's commitment transactions.
5783 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5784 check_added_monitors!(nodes[1], 1);
5786 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5787 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5788 let events = nodes[0].node.get_and_clear_pending_events();
5789 assert_eq!(events.len(), 1);
5791 Event::PaymentSent { payment_preimage } => {
5792 assert_eq!(payment_preimage, our_payment_preimage);
5794 _ => panic!("Unexpected event"),
5797 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5798 check_added_monitors!(nodes[0], 1);
5799 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5800 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5801 check_added_monitors!(nodes[1], 1);
5803 let starting_block = nodes[1].best_block_info();
5804 let mut block = Block {
5805 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5808 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5809 connect_block(&nodes[1], &block);
5810 block.header.prev_blockhash = block.block_hash();
5812 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5813 check_closed_broadcast!(nodes[1], true);
5814 check_added_monitors!(nodes[1], 1);
5815 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
5818 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5819 let chanmon_cfgs = create_chanmon_cfgs(2);
5820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5822 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5823 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5824 let logger = test_utils::TestLogger::new();
5826 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
5827 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5828 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();
5829 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5830 check_added_monitors!(nodes[0], 1);
5832 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5834 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5835 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5836 // to "time out" the HTLC.
5838 let starting_block = nodes[1].best_block_info();
5839 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5841 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5842 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5843 header.prev_blockhash = header.block_hash();
5845 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5846 check_closed_broadcast!(nodes[0], true);
5847 check_added_monitors!(nodes[0], 1);
5848 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
5851 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5852 let chanmon_cfgs = create_chanmon_cfgs(3);
5853 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5854 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5855 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5856 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5858 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5859 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5860 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5861 // actually revoked.
5862 let htlc_value = if use_dust { 50000 } else { 3000000 };
5863 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5864 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5865 expect_pending_htlcs_forwardable!(nodes[1]);
5866 check_added_monitors!(nodes[1], 1);
5868 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5869 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5870 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5871 check_added_monitors!(nodes[0], 1);
5872 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5873 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5874 check_added_monitors!(nodes[1], 1);
5875 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5876 check_added_monitors!(nodes[1], 1);
5877 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5879 if check_revoke_no_close {
5880 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5881 check_added_monitors!(nodes[0], 1);
5884 let starting_block = nodes[1].best_block_info();
5885 let mut block = Block {
5886 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5889 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5890 connect_block(&nodes[0], &block);
5891 block.header.prev_blockhash = block.block_hash();
5893 if !check_revoke_no_close {
5894 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5895 check_closed_broadcast!(nodes[0], true);
5896 check_added_monitors!(nodes[0], 1);
5897 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
5899 let events = nodes[0].node.get_and_clear_pending_events();
5900 expect_payment_failed!(nodes[0], events, our_payment_hash, true);
5904 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5905 // There are only a few cases to test here:
5906 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5907 // broadcastable commitment transactions result in channel closure,
5908 // * its included in an unrevoked-but-previous remote commitment transaction,
5909 // * its included in the latest remote or local commitment transactions.
5910 // We test each of the three possible commitment transactions individually and use both dust and
5912 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5913 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5914 // tested for at least one of the cases in other tests.
5916 fn htlc_claim_single_commitment_only_a() {
5917 do_htlc_claim_local_commitment_only(true);
5918 do_htlc_claim_local_commitment_only(false);
5920 do_htlc_claim_current_remote_commitment_only(true);
5921 do_htlc_claim_current_remote_commitment_only(false);
5925 fn htlc_claim_single_commitment_only_b() {
5926 do_htlc_claim_previous_remote_commitment_only(true, false);
5927 do_htlc_claim_previous_remote_commitment_only(false, false);
5928 do_htlc_claim_previous_remote_commitment_only(true, true);
5929 do_htlc_claim_previous_remote_commitment_only(false, true);
5934 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5935 let chanmon_cfgs = create_chanmon_cfgs(2);
5936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5938 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5939 //Force duplicate channel ids
5940 for node in nodes.iter() {
5941 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5944 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5945 let channel_value_satoshis=10000;
5946 let push_msat=10001;
5947 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5948 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5949 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5951 //Create a second channel with a channel_id collision
5952 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5956 fn bolt2_open_channel_sending_node_checks_part2() {
5957 let chanmon_cfgs = create_chanmon_cfgs(2);
5958 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5959 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5960 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5962 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5963 let channel_value_satoshis=2^24;
5964 let push_msat=10001;
5965 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5967 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5968 let channel_value_satoshis=10000;
5969 // Test when push_msat is equal to 1000 * funding_satoshis.
5970 let push_msat=1000*channel_value_satoshis+1;
5971 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5973 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5974 let channel_value_satoshis=10000;
5975 let push_msat=10001;
5976 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
5977 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5978 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5980 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5981 // 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
5982 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5984 // 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.
5985 assert!(BREAKDOWN_TIMEOUT>0);
5986 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5988 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5989 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5990 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5992 // 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.
5993 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5994 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5995 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5996 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5997 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6001 fn bolt2_open_channel_sane_dust_limit() {
6002 let chanmon_cfgs = create_chanmon_cfgs(2);
6003 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6004 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6005 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6007 let channel_value_satoshis=1000000;
6008 let push_msat=10001;
6009 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6010 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6011 node0_to_1_send_open_channel.dust_limit_satoshis = 661;
6012 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6014 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6015 let events = nodes[1].node.get_and_clear_pending_msg_events();
6016 let err_msg = match events[0] {
6017 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6020 _ => panic!("Unexpected event"),
6022 assert_eq!(err_msg.data, "dust_limit_satoshis (661) is greater than the implementation limit (660)");
6025 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6026 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6027 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6028 // is no longer affordable once it's freed.
6030 fn test_fail_holding_cell_htlc_upon_free() {
6031 let chanmon_cfgs = create_chanmon_cfgs(2);
6032 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6033 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6034 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6035 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6036 let logger = test_utils::TestLogger::new();
6038 // First nodes[0] generates an update_fee, setting the channel's
6039 // pending_update_fee.
6041 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6042 *feerate_lock += 20;
6044 nodes[0].node.timer_tick_occurred();
6045 check_added_monitors!(nodes[0], 1);
6047 let events = nodes[0].node.get_and_clear_pending_msg_events();
6048 assert_eq!(events.len(), 1);
6049 let (update_msg, commitment_signed) = match events[0] {
6050 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6051 (update_fee.as_ref(), commitment_signed)
6053 _ => panic!("Unexpected event"),
6056 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6058 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6059 let channel_reserve = chan_stat.channel_reserve_msat;
6060 let feerate = get_feerate!(nodes[0], chan.2);
6062 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6063 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6064 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6065 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6066 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();
6068 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6069 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6070 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6071 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6073 // Flush the pending fee update.
6074 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6075 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6076 check_added_monitors!(nodes[1], 1);
6077 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6078 check_added_monitors!(nodes[0], 1);
6080 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6081 // HTLC, but now that the fee has been raised the payment will now fail, causing
6082 // us to surface its failure to the user.
6083 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6084 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6085 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);
6086 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 {}",
6087 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6088 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6090 // Check that the payment failed to be sent out.
6091 let events = nodes[0].node.get_and_clear_pending_events();
6092 assert_eq!(events.len(), 1);
6094 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref error_code, ref error_data, ref all_paths_failed } => {
6095 assert_eq!(our_payment_hash.clone(), *payment_hash);
6096 assert_eq!(*rejected_by_dest, false);
6097 assert_eq!(*all_paths_failed, true);
6098 assert_eq!(*network_update, None);
6099 assert_eq!(*error_code, None);
6100 assert_eq!(*error_data, None);
6102 _ => panic!("Unexpected event"),
6106 // Test that if multiple HTLCs are released from the holding cell and one is
6107 // valid but the other is no longer valid upon release, the valid HTLC can be
6108 // successfully completed while the other one fails as expected.
6110 fn test_free_and_fail_holding_cell_htlcs() {
6111 let chanmon_cfgs = create_chanmon_cfgs(2);
6112 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6113 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6114 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6115 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6116 let logger = test_utils::TestLogger::new();
6118 // First nodes[0] generates an update_fee, setting the channel's
6119 // pending_update_fee.
6121 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6122 *feerate_lock += 200;
6124 nodes[0].node.timer_tick_occurred();
6125 check_added_monitors!(nodes[0], 1);
6127 let events = nodes[0].node.get_and_clear_pending_msg_events();
6128 assert_eq!(events.len(), 1);
6129 let (update_msg, commitment_signed) = match events[0] {
6130 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6131 (update_fee.as_ref(), commitment_signed)
6133 _ => panic!("Unexpected event"),
6136 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6138 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6139 let channel_reserve = chan_stat.channel_reserve_msat;
6140 let feerate = get_feerate!(nodes[0], chan.2);
6142 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6143 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6145 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6146 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6147 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6148 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();
6149 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();
6151 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6152 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6153 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6154 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6155 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6156 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6157 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6159 // Flush the pending fee update.
6160 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6161 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6162 check_added_monitors!(nodes[1], 1);
6163 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6164 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6165 check_added_monitors!(nodes[0], 2);
6167 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6168 // but now that the fee has been raised the second payment will now fail, causing us
6169 // to surface its failure to the user. The first payment should succeed.
6170 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6171 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6172 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);
6173 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 {}",
6174 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6175 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6177 // Check that the second payment failed to be sent out.
6178 let events = nodes[0].node.get_and_clear_pending_events();
6179 assert_eq!(events.len(), 1);
6181 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref error_code, ref error_data, ref all_paths_failed } => {
6182 assert_eq!(payment_hash_2.clone(), *payment_hash);
6183 assert_eq!(*rejected_by_dest, false);
6184 assert_eq!(*all_paths_failed, true);
6185 assert_eq!(*network_update, None);
6186 assert_eq!(*error_code, None);
6187 assert_eq!(*error_data, None);
6189 _ => panic!("Unexpected event"),
6192 // Complete the first payment and the RAA from the fee update.
6193 let (payment_event, send_raa_event) = {
6194 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6195 assert_eq!(msgs.len(), 2);
6196 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6198 let raa = match send_raa_event {
6199 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6200 _ => panic!("Unexpected event"),
6202 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6203 check_added_monitors!(nodes[1], 1);
6204 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6205 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6206 let events = nodes[1].node.get_and_clear_pending_events();
6207 assert_eq!(events.len(), 1);
6209 Event::PendingHTLCsForwardable { .. } => {},
6210 _ => panic!("Unexpected event"),
6212 nodes[1].node.process_pending_htlc_forwards();
6213 let events = nodes[1].node.get_and_clear_pending_events();
6214 assert_eq!(events.len(), 1);
6216 Event::PaymentReceived { .. } => {},
6217 _ => panic!("Unexpected event"),
6219 nodes[1].node.claim_funds(payment_preimage_1);
6220 check_added_monitors!(nodes[1], 1);
6221 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6222 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6223 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6224 let events = nodes[0].node.get_and_clear_pending_events();
6225 assert_eq!(events.len(), 1);
6227 Event::PaymentSent { ref payment_preimage } => {
6228 assert_eq!(*payment_preimage, payment_preimage_1);
6230 _ => panic!("Unexpected event"),
6234 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6235 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6236 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6239 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6240 let chanmon_cfgs = create_chanmon_cfgs(3);
6241 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6242 // When this test was written, the default base fee floated based on the HTLC count.
6243 // It is now fixed, so we simply set the fee to the expected value here.
6244 let mut config = test_default_channel_config();
6245 config.channel_options.forwarding_fee_base_msat = 196;
6246 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6247 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6248 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6249 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6250 let logger = test_utils::TestLogger::new();
6252 // First nodes[1] generates an update_fee, setting the channel's
6253 // pending_update_fee.
6255 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6256 *feerate_lock += 20;
6258 nodes[1].node.timer_tick_occurred();
6259 check_added_monitors!(nodes[1], 1);
6261 let events = nodes[1].node.get_and_clear_pending_msg_events();
6262 assert_eq!(events.len(), 1);
6263 let (update_msg, commitment_signed) = match events[0] {
6264 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6265 (update_fee.as_ref(), commitment_signed)
6267 _ => panic!("Unexpected event"),
6270 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6272 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6273 let channel_reserve = chan_stat.channel_reserve_msat;
6274 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6276 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6278 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6279 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6280 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6281 let payment_event = {
6282 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6283 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();
6284 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6285 check_added_monitors!(nodes[0], 1);
6287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6288 assert_eq!(events.len(), 1);
6290 SendEvent::from_event(events.remove(0))
6292 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6293 check_added_monitors!(nodes[1], 0);
6294 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6295 expect_pending_htlcs_forwardable!(nodes[1]);
6297 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6298 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6300 // Flush the pending fee update.
6301 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6302 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6303 check_added_monitors!(nodes[2], 1);
6304 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6305 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6306 check_added_monitors!(nodes[1], 2);
6308 // A final RAA message is generated to finalize the fee update.
6309 let events = nodes[1].node.get_and_clear_pending_msg_events();
6310 assert_eq!(events.len(), 1);
6312 let raa_msg = match &events[0] {
6313 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6316 _ => panic!("Unexpected event"),
6319 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6320 check_added_monitors!(nodes[2], 1);
6321 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6323 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6324 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6325 assert_eq!(process_htlc_forwards_event.len(), 1);
6326 match &process_htlc_forwards_event[0] {
6327 &Event::PendingHTLCsForwardable { .. } => {},
6328 _ => panic!("Unexpected event"),
6331 // In response, we call ChannelManager's process_pending_htlc_forwards
6332 nodes[1].node.process_pending_htlc_forwards();
6333 check_added_monitors!(nodes[1], 1);
6335 // This causes the HTLC to be failed backwards.
6336 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6337 assert_eq!(fail_event.len(), 1);
6338 let (fail_msg, commitment_signed) = match &fail_event[0] {
6339 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6340 assert_eq!(updates.update_add_htlcs.len(), 0);
6341 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6342 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6343 assert_eq!(updates.update_fail_htlcs.len(), 1);
6344 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6346 _ => panic!("Unexpected event"),
6349 // Pass the failure messages back to nodes[0].
6350 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6351 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6353 // Complete the HTLC failure+removal process.
6354 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6355 check_added_monitors!(nodes[0], 1);
6356 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6357 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6358 check_added_monitors!(nodes[1], 2);
6359 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6360 assert_eq!(final_raa_event.len(), 1);
6361 let raa = match &final_raa_event[0] {
6362 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6363 _ => panic!("Unexpected event"),
6365 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6366 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6367 check_added_monitors!(nodes[0], 1);
6370 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6371 // 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.
6372 //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.
6375 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6376 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6377 let chanmon_cfgs = create_chanmon_cfgs(2);
6378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6380 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6381 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6383 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6384 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6385 let logger = test_utils::TestLogger::new();
6386 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();
6387 route.paths[0][0].fee_msat = 100;
6389 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6390 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6391 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6392 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6396 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6397 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6398 let chanmon_cfgs = create_chanmon_cfgs(2);
6399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6401 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6402 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6403 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6405 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6406 let logger = test_utils::TestLogger::new();
6407 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();
6408 route.paths[0][0].fee_msat = 0;
6409 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6410 assert_eq!(err, "Cannot send 0-msat HTLC"));
6412 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6413 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6417 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6418 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6419 let chanmon_cfgs = create_chanmon_cfgs(2);
6420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6422 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6423 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6425 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6426 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6427 let logger = test_utils::TestLogger::new();
6428 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();
6429 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6430 check_added_monitors!(nodes[0], 1);
6431 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6432 updates.update_add_htlcs[0].amount_msat = 0;
6434 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6435 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6436 check_closed_broadcast!(nodes[1], true).unwrap();
6437 check_added_monitors!(nodes[1], 1);
6438 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6442 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6443 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6444 //It is enforced when constructing a route.
6445 let chanmon_cfgs = create_chanmon_cfgs(2);
6446 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6447 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6448 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6449 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6450 let logger = test_utils::TestLogger::new();
6452 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6454 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6455 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();
6456 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6457 assert_eq!(err, &"Channel CLTV overflowed?"));
6461 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6462 //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.
6463 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6464 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6465 let chanmon_cfgs = create_chanmon_cfgs(2);
6466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6468 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6469 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6470 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6472 let logger = test_utils::TestLogger::new();
6473 for i in 0..max_accepted_htlcs {
6474 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6475 let payment_event = {
6476 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6477 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();
6478 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6479 check_added_monitors!(nodes[0], 1);
6481 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6482 assert_eq!(events.len(), 1);
6483 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6484 assert_eq!(htlcs[0].htlc_id, i);
6488 SendEvent::from_event(events.remove(0))
6490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6491 check_added_monitors!(nodes[1], 0);
6492 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6494 expect_pending_htlcs_forwardable!(nodes[1]);
6495 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6497 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6498 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6499 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();
6500 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6501 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6503 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6504 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6508 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6509 //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.
6510 let chanmon_cfgs = create_chanmon_cfgs(2);
6511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6514 let channel_value = 100000;
6515 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6516 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6518 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6520 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6521 // Manually create a route over our max in flight (which our router normally automatically
6523 let route = Route { paths: vec![vec![RouteHop {
6524 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6525 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6526 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6528 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6529 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)));
6531 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6532 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);
6534 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6537 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6539 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6540 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6541 let chanmon_cfgs = create_chanmon_cfgs(2);
6542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6545 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6546 let htlc_minimum_msat: u64;
6548 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6549 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6550 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6553 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6554 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6555 let logger = test_utils::TestLogger::new();
6556 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();
6557 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6558 check_added_monitors!(nodes[0], 1);
6559 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6560 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6561 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6562 assert!(nodes[1].node.list_channels().is_empty());
6563 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6564 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()));
6565 check_added_monitors!(nodes[1], 1);
6566 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send less than our minimum HTLC value. Lower limit: (1000). Actual: (999)".to_string() });
6570 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6571 //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
6572 let chanmon_cfgs = create_chanmon_cfgs(2);
6573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6576 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6577 let logger = test_utils::TestLogger::new();
6579 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6580 let channel_reserve = chan_stat.channel_reserve_msat;
6581 let feerate = get_feerate!(nodes[0], chan.2);
6582 // The 2* and +1 are for the fee spike reserve.
6583 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6585 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6586 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6587 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6588 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();
6589 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6590 check_added_monitors!(nodes[0], 1);
6591 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6593 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6594 // at this time channel-initiatee receivers are not required to enforce that senders
6595 // respect the fee_spike_reserve.
6596 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6597 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6599 assert!(nodes[1].node.list_channels().is_empty());
6600 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6601 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6602 check_added_monitors!(nodes[1], 1);
6603 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
6607 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6608 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6609 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6610 let chanmon_cfgs = create_chanmon_cfgs(2);
6611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6613 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6614 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6615 let logger = test_utils::TestLogger::new();
6617 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6618 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6620 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6621 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();
6623 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6624 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6625 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6626 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6628 let mut msg = msgs::UpdateAddHTLC {
6632 payment_hash: our_payment_hash,
6633 cltv_expiry: htlc_cltv,
6634 onion_routing_packet: onion_packet.clone(),
6637 for i in 0..super::channel::OUR_MAX_HTLCS {
6638 msg.htlc_id = i as u64;
6639 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6641 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6642 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6644 assert!(nodes[1].node.list_channels().is_empty());
6645 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6646 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6647 check_added_monitors!(nodes[1], 1);
6648 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote tried to push more than our max accepted HTLCs (50)".to_string() });
6652 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6653 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6654 let chanmon_cfgs = create_chanmon_cfgs(2);
6655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6657 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6658 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6659 let logger = test_utils::TestLogger::new();
6661 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6662 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6663 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();
6664 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6665 check_added_monitors!(nodes[0], 1);
6666 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6667 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6668 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6670 assert!(nodes[1].node.list_channels().is_empty());
6671 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6672 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6673 check_added_monitors!(nodes[1], 1);
6674 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them over our max HTLC value (100000000)".to_string() });
6678 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6679 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6680 let chanmon_cfgs = create_chanmon_cfgs(2);
6681 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6682 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6683 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6684 let logger = test_utils::TestLogger::new();
6686 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6687 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6688 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6689 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();
6690 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6691 check_added_monitors!(nodes[0], 1);
6692 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6693 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6694 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696 assert!(nodes[1].node.list_channels().is_empty());
6697 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6698 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6699 check_added_monitors!(nodes[1], 1);
6700 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote provided CLTV expiry in seconds instead of block height".to_string() });
6704 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6705 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6706 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6707 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6708 let chanmon_cfgs = create_chanmon_cfgs(2);
6709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6711 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6712 let logger = test_utils::TestLogger::new();
6714 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6715 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6716 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6717 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();
6718 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6719 check_added_monitors!(nodes[0], 1);
6720 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].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 //Disconnect and Reconnect
6724 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6725 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6726 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6727 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6728 assert_eq!(reestablish_1.len(), 1);
6729 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6730 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6731 assert_eq!(reestablish_2.len(), 1);
6732 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6733 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6734 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6735 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6739 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6740 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6741 check_added_monitors!(nodes[1], 1);
6742 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6744 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6746 assert!(nodes[1].node.list_channels().is_empty());
6747 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6748 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6749 check_added_monitors!(nodes[1], 1);
6750 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote skipped HTLC ID (skipped ID: 1)".to_string() });
6754 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6755 //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.
6757 let chanmon_cfgs = create_chanmon_cfgs(2);
6758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6760 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6761 let logger = test_utils::TestLogger::new();
6762 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6763 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6764 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6765 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();
6766 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6768 check_added_monitors!(nodes[0], 1);
6769 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6770 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6772 let update_msg = msgs::UpdateFulfillHTLC{
6775 payment_preimage: our_payment_preimage,
6778 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6780 assert!(nodes[0].node.list_channels().is_empty());
6781 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6782 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()));
6783 check_added_monitors!(nodes[0], 1);
6784 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Remote tried to fulfill/fail HTLC (0) before it had been committed".to_string() });
6788 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6789 //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.
6791 let chanmon_cfgs = create_chanmon_cfgs(2);
6792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6794 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6795 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6796 let logger = test_utils::TestLogger::new();
6798 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6799 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6800 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();
6801 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6802 check_added_monitors!(nodes[0], 1);
6803 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6804 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6806 let update_msg = msgs::UpdateFailHTLC{
6809 reason: msgs::OnionErrorPacket { data: Vec::new()},
6812 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6814 assert!(nodes[0].node.list_channels().is_empty());
6815 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6816 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()));
6817 check_added_monitors!(nodes[0], 1);
6818 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Remote tried to fulfill/fail HTLC (0) before it had been committed".to_string() });
6822 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6823 //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.
6825 let chanmon_cfgs = create_chanmon_cfgs(2);
6826 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6827 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6828 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6829 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6830 let logger = test_utils::TestLogger::new();
6832 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6833 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6834 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();
6835 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6836 check_added_monitors!(nodes[0], 1);
6837 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6838 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6839 let update_msg = msgs::UpdateFailMalformedHTLC{
6842 sha256_of_onion: [1; 32],
6843 failure_code: 0x8000,
6846 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6848 assert!(nodes[0].node.list_channels().is_empty());
6849 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6850 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()));
6851 check_added_monitors!(nodes[0], 1);
6852 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Remote tried to fulfill/fail HTLC (0) before it had been committed".to_string() });
6856 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6857 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6859 let chanmon_cfgs = create_chanmon_cfgs(2);
6860 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6861 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6862 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6863 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6865 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6867 nodes[1].node.claim_funds(our_payment_preimage);
6868 check_added_monitors!(nodes[1], 1);
6870 let events = nodes[1].node.get_and_clear_pending_msg_events();
6871 assert_eq!(events.len(), 1);
6872 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6874 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, .. } } => {
6875 assert!(update_add_htlcs.is_empty());
6876 assert_eq!(update_fulfill_htlcs.len(), 1);
6877 assert!(update_fail_htlcs.is_empty());
6878 assert!(update_fail_malformed_htlcs.is_empty());
6879 assert!(update_fee.is_none());
6880 update_fulfill_htlcs[0].clone()
6882 _ => panic!("Unexpected event"),
6886 update_fulfill_msg.htlc_id = 1;
6888 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6890 assert!(nodes[0].node.list_channels().is_empty());
6891 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6892 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6893 check_added_monitors!(nodes[0], 1);
6894 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Remote tried to fulfill/fail an HTLC we couldn\'t find".to_string()});
6898 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6899 //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.
6901 let chanmon_cfgs = create_chanmon_cfgs(2);
6902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6905 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6907 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6909 nodes[1].node.claim_funds(our_payment_preimage);
6910 check_added_monitors!(nodes[1], 1);
6912 let events = nodes[1].node.get_and_clear_pending_msg_events();
6913 assert_eq!(events.len(), 1);
6914 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6916 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, .. } } => {
6917 assert!(update_add_htlcs.is_empty());
6918 assert_eq!(update_fulfill_htlcs.len(), 1);
6919 assert!(update_fail_htlcs.is_empty());
6920 assert!(update_fail_malformed_htlcs.is_empty());
6921 assert!(update_fee.is_none());
6922 update_fulfill_htlcs[0].clone()
6924 _ => panic!("Unexpected event"),
6928 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6930 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6932 assert!(nodes[0].node.list_channels().is_empty());
6933 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6934 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6935 check_added_monitors!(nodes[0], 1);
6936 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Remote tried to fulfill HTLC (0) with an incorrect preimage".to_string() });
6940 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6941 //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.
6943 let chanmon_cfgs = create_chanmon_cfgs(2);
6944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6946 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6947 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6948 let logger = test_utils::TestLogger::new();
6950 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6951 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6952 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();
6953 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6954 check_added_monitors!(nodes[0], 1);
6956 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6957 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6959 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6960 check_added_monitors!(nodes[1], 0);
6961 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6963 let events = nodes[1].node.get_and_clear_pending_msg_events();
6965 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6967 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, .. } } => {
6968 assert!(update_add_htlcs.is_empty());
6969 assert!(update_fulfill_htlcs.is_empty());
6970 assert!(update_fail_htlcs.is_empty());
6971 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6972 assert!(update_fee.is_none());
6973 update_fail_malformed_htlcs[0].clone()
6975 _ => panic!("Unexpected event"),
6978 update_msg.failure_code &= !0x8000;
6979 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6981 assert!(nodes[0].node.list_channels().is_empty());
6982 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6983 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6984 check_added_monitors!(nodes[0], 1);
6985 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Got update_fail_malformed_htlc with BADONION not set".to_string() });
6989 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6990 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6991 // * 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.
6993 let chanmon_cfgs = create_chanmon_cfgs(3);
6994 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6995 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6996 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6997 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6998 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6999 let logger = test_utils::TestLogger::new();
7001 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7004 let mut payment_event = {
7005 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7006 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();
7007 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7008 check_added_monitors!(nodes[0], 1);
7009 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7010 assert_eq!(events.len(), 1);
7011 SendEvent::from_event(events.remove(0))
7013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7014 check_added_monitors!(nodes[1], 0);
7015 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7016 expect_pending_htlcs_forwardable!(nodes[1]);
7017 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7018 assert_eq!(events_2.len(), 1);
7019 check_added_monitors!(nodes[1], 1);
7020 payment_event = SendEvent::from_event(events_2.remove(0));
7021 assert_eq!(payment_event.msgs.len(), 1);
7024 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7025 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7026 check_added_monitors!(nodes[2], 0);
7027 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7029 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7030 assert_eq!(events_3.len(), 1);
7031 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7033 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 } } => {
7034 assert!(update_add_htlcs.is_empty());
7035 assert!(update_fulfill_htlcs.is_empty());
7036 assert!(update_fail_htlcs.is_empty());
7037 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7038 assert!(update_fee.is_none());
7039 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7041 _ => panic!("Unexpected event"),
7045 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7047 check_added_monitors!(nodes[1], 0);
7048 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7049 expect_pending_htlcs_forwardable!(nodes[1]);
7050 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7051 assert_eq!(events_4.len(), 1);
7053 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7055 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, .. } } => {
7056 assert!(update_add_htlcs.is_empty());
7057 assert!(update_fulfill_htlcs.is_empty());
7058 assert_eq!(update_fail_htlcs.len(), 1);
7059 assert!(update_fail_malformed_htlcs.is_empty());
7060 assert!(update_fee.is_none());
7062 _ => panic!("Unexpected event"),
7065 check_added_monitors!(nodes[1], 1);
7068 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7069 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7070 // 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
7071 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7073 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7074 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7075 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7076 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7077 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7078 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7080 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7082 // We route 2 dust-HTLCs between A and B
7083 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7084 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7085 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7087 // Cache one local commitment tx as previous
7088 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7090 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7091 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7092 check_added_monitors!(nodes[1], 0);
7093 expect_pending_htlcs_forwardable!(nodes[1]);
7094 check_added_monitors!(nodes[1], 1);
7096 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7097 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7098 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7099 check_added_monitors!(nodes[0], 1);
7101 // Cache one local commitment tx as lastest
7102 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7104 let events = nodes[0].node.get_and_clear_pending_msg_events();
7106 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7107 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7109 _ => panic!("Unexpected event"),
7112 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7113 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7115 _ => panic!("Unexpected event"),
7118 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7119 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7120 if announce_latest {
7121 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7123 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7126 check_closed_broadcast!(nodes[0], true);
7127 check_added_monitors!(nodes[0], 1);
7128 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
7130 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7131 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7132 let events = nodes[0].node.get_and_clear_pending_events();
7133 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7134 assert_eq!(events.len(), 2);
7135 let mut first_failed = false;
7136 for event in events {
7138 Event::PaymentFailed { payment_hash, .. } => {
7139 if payment_hash == payment_hash_1 {
7140 assert!(!first_failed);
7141 first_failed = true;
7143 assert_eq!(payment_hash, payment_hash_2);
7146 _ => panic!("Unexpected event"),
7152 fn test_failure_delay_dust_htlc_local_commitment() {
7153 do_test_failure_delay_dust_htlc_local_commitment(true);
7154 do_test_failure_delay_dust_htlc_local_commitment(false);
7157 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7158 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7159 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7160 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7161 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7162 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7163 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7165 let chanmon_cfgs = create_chanmon_cfgs(3);
7166 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7167 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7168 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7169 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7171 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7173 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7174 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7176 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7177 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7179 // We revoked bs_commitment_tx
7181 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7182 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7185 let mut timeout_tx = Vec::new();
7187 // We fail dust-HTLC 1 by broadcast of local commitment tx
7188 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7189 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
7190 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7191 let events = nodes[0].node.get_and_clear_pending_events();
7192 expect_payment_failed!(nodes[0], events, dust_hash, true);
7194 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7195 check_closed_broadcast!(nodes[0], true);
7196 check_added_monitors!(nodes[0], 1);
7197 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7198 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7199 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7200 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7201 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7202 mine_transaction(&nodes[0], &timeout_tx[0]);
7203 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7204 let events = nodes[0].node.get_and_clear_pending_events();
7205 expect_payment_failed!(nodes[0], events, non_dust_hash, true);
7207 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7208 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7209 check_closed_broadcast!(nodes[0], true);
7210 check_added_monitors!(nodes[0], 1);
7211 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
7212 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7213 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7214 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7216 let events = nodes[0].node.get_and_clear_pending_events();
7217 expect_payment_failed!(nodes[0], events, dust_hash, true);
7218 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7219 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7220 mine_transaction(&nodes[0], &timeout_tx[0]);
7221 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7222 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7223 let events = nodes[0].node.get_and_clear_pending_events();
7224 expect_payment_failed!(nodes[0], events, non_dust_hash, true);
7226 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7228 let events = nodes[0].node.get_and_clear_pending_events();
7229 assert_eq!(events.len(), 2);
7232 Event::PaymentFailed { payment_hash, .. } => {
7233 if payment_hash == dust_hash { first = true; }
7234 else { first = false; }
7236 _ => panic!("Unexpected event"),
7239 Event::PaymentFailed { payment_hash, .. } => {
7240 if first { assert_eq!(payment_hash, non_dust_hash); }
7241 else { assert_eq!(payment_hash, dust_hash); }
7243 _ => panic!("Unexpected event"),
7250 fn test_sweep_outbound_htlc_failure_update() {
7251 do_test_sweep_outbound_htlc_failure_update(false, true);
7252 do_test_sweep_outbound_htlc_failure_update(false, false);
7253 do_test_sweep_outbound_htlc_failure_update(true, false);
7257 fn test_user_configurable_csv_delay() {
7258 // We test our channel constructors yield errors when we pass them absurd csv delay
7260 let mut low_our_to_self_config = UserConfig::default();
7261 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7262 let mut high_their_to_self_config = UserConfig::default();
7263 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7264 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7265 let chanmon_cfgs = create_chanmon_cfgs(2);
7266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7270 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7271 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) {
7273 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())); },
7274 _ => panic!("Unexpected event"),
7276 } else { assert!(false) }
7278 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7279 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7280 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7281 open_channel.to_self_delay = 200;
7282 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) {
7284 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())); },
7285 _ => panic!("Unexpected event"),
7287 } else { assert!(false); }
7289 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7290 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7291 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()));
7292 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7293 accept_channel.to_self_delay = 200;
7294 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7295 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7297 &ErrorAction::SendErrorMessage { ref msg } => {
7298 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()));
7300 _ => { assert!(false); }
7302 } else { assert!(false); }
7303 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "They wanted our payments to be delayed by a needlessly long period. Upper limit: 100. Actual: 200".to_string() });
7305 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7306 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7307 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7308 open_channel.to_self_delay = 200;
7309 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) {
7311 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())); },
7312 _ => panic!("Unexpected event"),
7314 } else { assert!(false); }
7318 fn test_data_loss_protect() {
7319 // We want to be sure that :
7320 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7321 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7322 // * we close channel in case of detecting other being fallen behind
7323 // * we are able to claim our own outputs thanks to to_remote being static
7324 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7330 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7331 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7332 // during signing due to revoked tx
7333 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7334 let keys_manager = &chanmon_cfgs[0].keys_manager;
7337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7339 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7341 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7343 // Cache node A state before any channel update
7344 let previous_node_state = nodes[0].node.encode();
7345 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7346 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7348 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7349 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7351 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7352 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7354 // Restore node A from previous state
7355 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7356 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7357 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7358 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7359 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7360 persister = test_utils::TestPersister::new();
7361 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7363 let mut channel_monitors = HashMap::new();
7364 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7365 <(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 {
7366 keys_manager: keys_manager,
7367 fee_estimator: &fee_estimator,
7368 chain_monitor: &monitor,
7370 tx_broadcaster: &tx_broadcaster,
7371 default_config: UserConfig::default(),
7375 nodes[0].node = &node_state_0;
7376 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7377 nodes[0].chain_monitor = &monitor;
7378 nodes[0].chain_source = &chain_source;
7380 check_added_monitors!(nodes[0], 1);
7382 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7383 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7385 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7387 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7388 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7389 check_added_monitors!(nodes[0], 1);
7392 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7393 assert_eq!(node_txn.len(), 0);
7396 let mut reestablish_1 = Vec::with_capacity(1);
7397 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7398 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7399 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7400 reestablish_1.push(msg.clone());
7401 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7402 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7404 &ErrorAction::SendErrorMessage { ref msg } => {
7405 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");
7407 _ => panic!("Unexpected event!"),
7410 panic!("Unexpected event")
7414 // Check we close channel detecting A is fallen-behind
7415 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7416 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7417 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7418 check_added_monitors!(nodes[1], 1);
7420 // Check A is able to claim to_remote output
7421 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7422 assert_eq!(node_txn.len(), 1);
7423 check_spends!(node_txn[0], chan.3);
7424 assert_eq!(node_txn[0].output.len(), 2);
7425 mine_transaction(&nodes[0], &node_txn[0]);
7426 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7427 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() });
7428 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7429 assert_eq!(spend_txn.len(), 1);
7430 check_spends!(spend_txn[0], node_txn[0]);
7434 fn test_check_htlc_underpaying() {
7435 // Send payment through A -> B but A is maliciously
7436 // sending a probe payment (i.e less than expected value0
7437 // to B, B should refuse payment.
7439 let chanmon_cfgs = create_chanmon_cfgs(2);
7440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7442 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7444 // Create some initial channels
7445 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7447 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();
7448 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7449 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7450 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7451 check_added_monitors!(nodes[0], 1);
7453 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7454 assert_eq!(events.len(), 1);
7455 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7456 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7457 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7459 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7460 // and then will wait a second random delay before failing the HTLC back:
7461 expect_pending_htlcs_forwardable!(nodes[1]);
7462 expect_pending_htlcs_forwardable!(nodes[1]);
7464 // Node 3 is expecting payment of 100_000 but received 10_000,
7465 // it should fail htlc like we didn't know the preimage.
7466 nodes[1].node.process_pending_htlc_forwards();
7468 let events = nodes[1].node.get_and_clear_pending_msg_events();
7469 assert_eq!(events.len(), 1);
7470 let (update_fail_htlc, commitment_signed) = match events[0] {
7471 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 } } => {
7472 assert!(update_add_htlcs.is_empty());
7473 assert!(update_fulfill_htlcs.is_empty());
7474 assert_eq!(update_fail_htlcs.len(), 1);
7475 assert!(update_fail_malformed_htlcs.is_empty());
7476 assert!(update_fee.is_none());
7477 (update_fail_htlcs[0].clone(), commitment_signed)
7479 _ => panic!("Unexpected event"),
7481 check_added_monitors!(nodes[1], 1);
7483 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7484 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7486 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7487 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7488 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7489 let events = nodes[0].node.get_and_clear_pending_events();
7490 expect_payment_failed!(nodes[0], events, our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7494 fn test_announce_disable_channels() {
7495 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7496 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7498 let chanmon_cfgs = create_chanmon_cfgs(2);
7499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7503 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7504 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7505 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7508 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7509 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7511 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7512 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7513 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7514 assert_eq!(msg_events.len(), 3);
7515 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7516 for e in msg_events {
7518 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7519 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7520 // Check that each channel gets updated exactly once
7521 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7522 panic!("Generated ChannelUpdate for wrong chan!");
7525 _ => panic!("Unexpected event"),
7529 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7530 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7531 assert_eq!(reestablish_1.len(), 3);
7532 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7533 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7534 assert_eq!(reestablish_2.len(), 3);
7536 // Reestablish chan_1
7537 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7538 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7539 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7540 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7541 // Reestablish chan_2
7542 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7543 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7544 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7545 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7546 // Reestablish chan_3
7547 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7548 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7549 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7550 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7552 nodes[0].node.timer_tick_occurred();
7553 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7554 nodes[0].node.timer_tick_occurred();
7555 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7556 assert_eq!(msg_events.len(), 3);
7557 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7558 for e in msg_events {
7560 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7561 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7562 // Check that each channel gets updated exactly once
7563 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7564 panic!("Generated ChannelUpdate for wrong chan!");
7567 _ => panic!("Unexpected event"),
7573 fn test_priv_forwarding_rejection() {
7574 // If we have a private channel with outbound liquidity, and
7575 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7576 // to forward through that channel.
7577 let chanmon_cfgs = create_chanmon_cfgs(3);
7578 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7579 let mut no_announce_cfg = test_default_channel_config();
7580 no_announce_cfg.channel_options.announced_channel = false;
7581 no_announce_cfg.accept_forwards_to_priv_channels = false;
7582 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7583 let persister: test_utils::TestPersister;
7584 let new_chain_monitor: test_utils::TestChainMonitor;
7585 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7586 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7588 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7590 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7591 // not send for private channels.
7592 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7593 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7594 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7595 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7596 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7598 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7599 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7600 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()));
7601 check_added_monitors!(nodes[2], 1);
7603 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()));
7604 check_added_monitors!(nodes[1], 1);
7606 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7607 confirm_transaction_at(&nodes[1], &tx, conf_height);
7608 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7609 confirm_transaction_at(&nodes[2], &tx, conf_height);
7610 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7611 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7612 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()));
7613 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7614 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7615 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7617 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7618 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7619 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7621 // We should always be able to forward through nodes[1] as long as its out through a public
7623 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7625 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7626 // to nodes[2], which should be rejected:
7627 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7628 let route = get_route(&nodes[0].node.get_our_node_id(),
7629 &nodes[0].net_graph_msg_handler.network_graph,
7630 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
7631 &[&RouteHint(vec![RouteHintHop {
7632 src_node_id: nodes[1].node.get_our_node_id(),
7633 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7634 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7635 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7636 htlc_minimum_msat: None,
7637 htlc_maximum_msat: None,
7638 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7640 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7641 check_added_monitors!(nodes[0], 1);
7642 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7643 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7644 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7646 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7647 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7648 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7649 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7650 assert!(htlc_fail_updates.update_fee.is_none());
7652 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7653 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7654 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7656 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7657 // to true. Sadly there is currently no way to change it at runtime.
7659 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7660 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7662 let nodes_1_serialized = nodes[1].node.encode();
7663 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7664 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7666 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7667 let mut mon_iter = mons.iter();
7668 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7669 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7672 persister = test_utils::TestPersister::new();
7673 let keys_manager = &chanmon_cfgs[1].keys_manager;
7674 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);
7675 nodes[1].chain_monitor = &new_chain_monitor;
7677 let mut monitor_a_read = &monitor_a_serialized.0[..];
7678 let mut monitor_b_read = &monitor_b_serialized.0[..];
7679 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7680 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7681 assert!(monitor_a_read.is_empty());
7682 assert!(monitor_b_read.is_empty());
7684 no_announce_cfg.accept_forwards_to_priv_channels = true;
7686 let mut nodes_1_read = &nodes_1_serialized[..];
7687 let (_, nodes_1_deserialized_tmp) = {
7688 let mut channel_monitors = HashMap::new();
7689 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7690 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7691 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7692 default_config: no_announce_cfg,
7694 fee_estimator: node_cfgs[1].fee_estimator,
7695 chain_monitor: nodes[1].chain_monitor,
7696 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7697 logger: nodes[1].logger,
7701 assert!(nodes_1_read.is_empty());
7702 nodes_1_deserialized = nodes_1_deserialized_tmp;
7704 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7705 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7706 check_added_monitors!(nodes[1], 2);
7707 nodes[1].node = &nodes_1_deserialized;
7709 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7710 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7711 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7712 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7713 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7714 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7715 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7716 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7718 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7719 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7720 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7721 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7722 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7723 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7724 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7725 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7727 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7728 check_added_monitors!(nodes[0], 1);
7729 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7730 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7734 fn test_bump_penalty_txn_on_revoked_commitment() {
7735 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7736 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7738 let chanmon_cfgs = create_chanmon_cfgs(2);
7739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7741 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7743 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7744 let logger = test_utils::TestLogger::new();
7746 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7747 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7748 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();
7749 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7751 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7752 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7753 assert_eq!(revoked_txn[0].output.len(), 4);
7754 assert_eq!(revoked_txn[0].input.len(), 1);
7755 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7756 let revoked_txid = revoked_txn[0].txid();
7758 let mut penalty_sum = 0;
7759 for outp in revoked_txn[0].output.iter() {
7760 if outp.script_pubkey.is_v0_p2wsh() {
7761 penalty_sum += outp.value;
7765 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7766 let header_114 = connect_blocks(&nodes[1], 14);
7768 // Actually revoke tx by claiming a HTLC
7769 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7770 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7771 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7772 check_added_monitors!(nodes[1], 1);
7774 // One or more justice tx should have been broadcast, check it
7778 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7779 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7780 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7781 assert_eq!(node_txn[0].output.len(), 1);
7782 check_spends!(node_txn[0], revoked_txn[0]);
7783 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7784 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7785 penalty_1 = node_txn[0].txid();
7789 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7790 connect_blocks(&nodes[1], 15);
7791 let mut penalty_2 = penalty_1;
7792 let mut feerate_2 = 0;
7794 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7795 assert_eq!(node_txn.len(), 1);
7796 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7797 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7798 assert_eq!(node_txn[0].output.len(), 1);
7799 check_spends!(node_txn[0], revoked_txn[0]);
7800 penalty_2 = node_txn[0].txid();
7801 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7802 assert_ne!(penalty_2, penalty_1);
7803 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7804 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7805 // Verify 25% bump heuristic
7806 assert!(feerate_2 * 100 >= feerate_1 * 125);
7810 assert_ne!(feerate_2, 0);
7812 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7813 connect_blocks(&nodes[1], 1);
7815 let mut feerate_3 = 0;
7817 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7818 assert_eq!(node_txn.len(), 1);
7819 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7820 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7821 assert_eq!(node_txn[0].output.len(), 1);
7822 check_spends!(node_txn[0], revoked_txn[0]);
7823 penalty_3 = node_txn[0].txid();
7824 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7825 assert_ne!(penalty_3, penalty_2);
7826 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7827 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7828 // Verify 25% bump heuristic
7829 assert!(feerate_3 * 100 >= feerate_2 * 125);
7833 assert_ne!(feerate_3, 0);
7835 nodes[1].node.get_and_clear_pending_events();
7836 nodes[1].node.get_and_clear_pending_msg_events();
7840 fn test_bump_penalty_txn_on_revoked_htlcs() {
7841 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7842 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7844 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7845 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7846 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7847 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7848 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7850 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7851 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7852 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7853 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7854 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7855 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7856 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7857 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7859 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7860 assert_eq!(revoked_local_txn[0].input.len(), 1);
7861 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7863 // Revoke local commitment tx
7864 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7866 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7867 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7868 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7869 check_closed_broadcast!(nodes[1], true);
7870 check_added_monitors!(nodes[1], 1);
7871 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
7872 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7874 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7875 assert_eq!(revoked_htlc_txn.len(), 3);
7876 check_spends!(revoked_htlc_txn[1], chan.3);
7878 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7879 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7880 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7882 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7883 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7884 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7885 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7887 // Broadcast set of revoked txn on A
7888 let hash_128 = connect_blocks(&nodes[0], 40);
7889 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7890 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7891 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7892 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7893 let events = nodes[0].node.get_and_clear_pending_events();
7894 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7896 Event::ChannelClosed { .. } => {}
7897 _ => panic!("Unexpected event"),
7903 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7904 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7905 // Verify claim tx are spending revoked HTLC txn
7907 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7908 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7909 // which are included in the same block (they are broadcasted because we scan the
7910 // transactions linearly and generate claims as we go, they likely should be removed in the
7912 assert_eq!(node_txn[0].input.len(), 1);
7913 check_spends!(node_txn[0], revoked_local_txn[0]);
7914 assert_eq!(node_txn[1].input.len(), 1);
7915 check_spends!(node_txn[1], revoked_local_txn[0]);
7916 assert_eq!(node_txn[2].input.len(), 1);
7917 check_spends!(node_txn[2], revoked_local_txn[0]);
7919 // Each of the three justice transactions claim a separate (single) output of the three
7920 // available, which we check here:
7921 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7922 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7923 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7925 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7926 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7928 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7929 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7930 // a remote commitment tx has already been confirmed).
7931 check_spends!(node_txn[3], chan.3);
7933 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7934 // output, checked above).
7935 assert_eq!(node_txn[4].input.len(), 2);
7936 assert_eq!(node_txn[4].output.len(), 1);
7937 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7939 first = node_txn[4].txid();
7940 // Store both feerates for later comparison
7941 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7942 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7943 penalty_txn = vec![node_txn[2].clone()];
7947 // Connect one more block to see if bumped penalty are issued for HTLC txn
7948 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7949 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7950 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7951 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7953 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7954 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7956 check_spends!(node_txn[0], revoked_local_txn[0]);
7957 check_spends!(node_txn[1], revoked_local_txn[0]);
7958 // Note that these are both bogus - they spend outputs already claimed in block 129:
7959 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7960 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7962 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7963 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7969 // Few more blocks to confirm penalty txn
7970 connect_blocks(&nodes[0], 4);
7971 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7972 let header_144 = connect_blocks(&nodes[0], 9);
7974 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7975 assert_eq!(node_txn.len(), 1);
7977 assert_eq!(node_txn[0].input.len(), 2);
7978 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7979 // Verify bumped tx is different and 25% bump heuristic
7980 assert_ne!(first, node_txn[0].txid());
7981 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7982 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7983 assert!(feerate_2 * 100 > feerate_1 * 125);
7984 let txn = vec![node_txn[0].clone()];
7988 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7989 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7990 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7991 connect_blocks(&nodes[0], 20);
7993 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7994 // We verify than no new transaction has been broadcast because previously
7995 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7996 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7997 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7998 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7999 // up bumped justice generation.
8000 assert_eq!(node_txn.len(), 0);
8003 check_closed_broadcast!(nodes[0], true);
8004 check_added_monitors!(nodes[0], 1);
8008 fn test_bump_penalty_txn_on_remote_commitment() {
8009 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8010 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8013 // Provide preimage for one
8014 // Check aggregation
8016 let chanmon_cfgs = create_chanmon_cfgs(2);
8017 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8018 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8019 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8021 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8022 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8023 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8025 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8026 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8027 assert_eq!(remote_txn[0].output.len(), 4);
8028 assert_eq!(remote_txn[0].input.len(), 1);
8029 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8031 // Claim a HTLC without revocation (provide B monitor with preimage)
8032 nodes[1].node.claim_funds(payment_preimage);
8033 mine_transaction(&nodes[1], &remote_txn[0]);
8034 check_added_monitors!(nodes[1], 2);
8035 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8037 // One or more claim tx should have been broadcast, check it
8041 let feerate_timeout;
8042 let feerate_preimage;
8044 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8045 // 9 transactions including:
8046 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8047 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8048 // 2 * HTLC-Success (one RBF bump we'll check later)
8050 assert_eq!(node_txn.len(), 8);
8051 assert_eq!(node_txn[0].input.len(), 1);
8052 assert_eq!(node_txn[6].input.len(), 1);
8053 check_spends!(node_txn[0], remote_txn[0]);
8054 check_spends!(node_txn[6], remote_txn[0]);
8055 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
8056 preimage_bump = node_txn[3].clone();
8058 check_spends!(node_txn[1], chan.3);
8059 check_spends!(node_txn[2], node_txn[1]);
8060 assert_eq!(node_txn[1], node_txn[4]);
8061 assert_eq!(node_txn[2], node_txn[5]);
8063 timeout = node_txn[6].txid();
8064 let index = node_txn[6].input[0].previous_output.vout;
8065 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8066 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8068 preimage = node_txn[0].txid();
8069 let index = node_txn[0].input[0].previous_output.vout;
8070 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8071 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8075 assert_ne!(feerate_timeout, 0);
8076 assert_ne!(feerate_preimage, 0);
8078 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8079 connect_blocks(&nodes[1], 15);
8081 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8082 assert_eq!(node_txn.len(), 1);
8083 assert_eq!(node_txn[0].input.len(), 1);
8084 assert_eq!(preimage_bump.input.len(), 1);
8085 check_spends!(node_txn[0], remote_txn[0]);
8086 check_spends!(preimage_bump, remote_txn[0]);
8088 let index = preimage_bump.input[0].previous_output.vout;
8089 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8090 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8091 assert!(new_feerate * 100 > feerate_timeout * 125);
8092 assert_ne!(timeout, preimage_bump.txid());
8094 let index = node_txn[0].input[0].previous_output.vout;
8095 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8096 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8097 assert!(new_feerate * 100 > feerate_preimage * 125);
8098 assert_ne!(preimage, node_txn[0].txid());
8103 nodes[1].node.get_and_clear_pending_events();
8104 nodes[1].node.get_and_clear_pending_msg_events();
8108 fn test_counterparty_raa_skip_no_crash() {
8109 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8110 // commitment transaction, we would have happily carried on and provided them the next
8111 // commitment transaction based on one RAA forward. This would probably eventually have led to
8112 // channel closure, but it would not have resulted in funds loss. Still, our
8113 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8114 // check simply that the channel is closed in response to such an RAA, but don't check whether
8115 // we decide to punish our counterparty for revoking their funds (as we don't currently
8117 let chanmon_cfgs = create_chanmon_cfgs(2);
8118 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8119 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8120 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8121 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8123 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8124 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8126 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8128 // Make signer believe we got a counterparty signature, so that it allows the revocation
8129 keys.get_enforcement_state().last_holder_commitment -= 1;
8130 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8132 // Must revoke without gaps
8133 keys.get_enforcement_state().last_holder_commitment -= 1;
8134 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8136 keys.get_enforcement_state().last_holder_commitment -= 1;
8137 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8138 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8140 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8141 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8142 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8143 check_added_monitors!(nodes[1], 1);
8144 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8148 fn test_bump_txn_sanitize_tracking_maps() {
8149 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8150 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8152 let chanmon_cfgs = create_chanmon_cfgs(2);
8153 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8154 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8155 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8157 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8158 // Lock HTLC in both directions
8159 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8160 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8162 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8163 assert_eq!(revoked_local_txn[0].input.len(), 1);
8164 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8166 // Revoke local commitment tx
8167 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8169 // Broadcast set of revoked txn on A
8170 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8171 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8172 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8174 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8175 check_closed_broadcast!(nodes[0], true);
8176 check_added_monitors!(nodes[0], 1);
8177 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
8179 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8180 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8181 check_spends!(node_txn[0], revoked_local_txn[0]);
8182 check_spends!(node_txn[1], revoked_local_txn[0]);
8183 check_spends!(node_txn[2], revoked_local_txn[0]);
8184 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8188 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8189 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8190 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8192 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8193 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8194 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8195 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8201 fn test_override_channel_config() {
8202 let chanmon_cfgs = create_chanmon_cfgs(2);
8203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8207 // Node0 initiates a channel to node1 using the override config.
8208 let mut override_config = UserConfig::default();
8209 override_config.own_channel_config.our_to_self_delay = 200;
8211 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8213 // Assert the channel created by node0 is using the override config.
8214 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8215 assert_eq!(res.channel_flags, 0);
8216 assert_eq!(res.to_self_delay, 200);
8220 fn test_override_0msat_htlc_minimum() {
8221 let mut zero_config = UserConfig::default();
8222 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8223 let chanmon_cfgs = create_chanmon_cfgs(2);
8224 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8225 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8226 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8228 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8229 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8230 assert_eq!(res.htlc_minimum_msat, 1);
8232 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8233 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8234 assert_eq!(res.htlc_minimum_msat, 1);
8238 fn test_simple_mpp() {
8239 // Simple test of sending a multi-path payment.
8240 let chanmon_cfgs = create_chanmon_cfgs(4);
8241 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8242 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8243 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8245 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8246 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8247 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8248 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8249 let logger = test_utils::TestLogger::new();
8251 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8252 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8253 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();
8254 let path = route.paths[0].clone();
8255 route.paths.push(path);
8256 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8257 route.paths[0][0].short_channel_id = chan_1_id;
8258 route.paths[0][1].short_channel_id = chan_3_id;
8259 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8260 route.paths[1][0].short_channel_id = chan_2_id;
8261 route.paths[1][1].short_channel_id = chan_4_id;
8262 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8263 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8267 fn test_preimage_storage() {
8268 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8269 let chanmon_cfgs = create_chanmon_cfgs(2);
8270 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8271 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8272 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8274 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8277 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8279 let logger = test_utils::TestLogger::new();
8280 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8281 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();
8282 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8283 check_added_monitors!(nodes[0], 1);
8284 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8285 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8286 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8287 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8289 // Note that after leaving the above scope we have no knowledge of any arguments or return
8290 // values from previous calls.
8291 expect_pending_htlcs_forwardable!(nodes[1]);
8292 let events = nodes[1].node.get_and_clear_pending_events();
8293 assert_eq!(events.len(), 1);
8295 Event::PaymentReceived { ref purpose, .. } => {
8297 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8298 assert_eq!(*user_payment_id, 42);
8299 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8301 _ => panic!("expected PaymentPurpose::InvoicePayment")
8304 _ => panic!("Unexpected event"),
8309 fn test_secret_timeout() {
8310 // Simple test of payment secret storage time outs
8311 let chanmon_cfgs = create_chanmon_cfgs(2);
8312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8314 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8316 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8318 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8320 // We should fail to register the same payment hash twice, at least until we've connected a
8321 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8322 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8323 assert_eq!(err, "Duplicate payment hash");
8324 } else { panic!(); }
8326 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8328 header: BlockHeader {
8330 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8331 merkle_root: Default::default(),
8332 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8336 connect_block(&nodes[1], &block);
8337 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8338 assert_eq!(err, "Duplicate payment hash");
8339 } else { panic!(); }
8341 // If we then connect the second block, we should be able to register the same payment hash
8342 // again with a different user_payment_id (this time getting a new payment secret).
8343 block.header.prev_blockhash = block.header.block_hash();
8344 block.header.time += 1;
8345 connect_block(&nodes[1], &block);
8346 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8347 assert_ne!(payment_secret_1, our_payment_secret);
8350 let logger = test_utils::TestLogger::new();
8351 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8352 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();
8353 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8354 check_added_monitors!(nodes[0], 1);
8355 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8356 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8357 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8358 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8360 // Note that after leaving the above scope we have no knowledge of any arguments or return
8361 // values from previous calls.
8362 expect_pending_htlcs_forwardable!(nodes[1]);
8363 let events = nodes[1].node.get_and_clear_pending_events();
8364 assert_eq!(events.len(), 1);
8366 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8367 assert!(payment_preimage.is_none());
8368 assert_eq!(user_payment_id, 42);
8369 assert_eq!(payment_secret, our_payment_secret);
8370 // We don't actually have the payment preimage with which to claim this payment!
8372 _ => panic!("Unexpected event"),
8377 fn test_bad_secret_hash() {
8378 // Simple test of unregistered payment hash/invalid payment secret handling
8379 let chanmon_cfgs = create_chanmon_cfgs(2);
8380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8382 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8384 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8386 let random_payment_hash = PaymentHash([42; 32]);
8387 let random_payment_secret = PaymentSecret([43; 32]);
8388 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8390 let logger = test_utils::TestLogger::new();
8391 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8392 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();
8394 // All the below cases should end up being handled exactly identically, so we macro the
8395 // resulting events.
8396 macro_rules! handle_unknown_invalid_payment_data {
8398 check_added_monitors!(nodes[0], 1);
8399 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8400 let payment_event = SendEvent::from_event(events.pop().unwrap());
8401 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8402 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8404 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8405 // again to process the pending backwards-failure of the HTLC
8406 expect_pending_htlcs_forwardable!(nodes[1]);
8407 expect_pending_htlcs_forwardable!(nodes[1]);
8408 check_added_monitors!(nodes[1], 1);
8410 // We should fail the payment back
8411 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8412 match events.pop().unwrap() {
8413 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8414 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8415 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8417 _ => panic!("Unexpected event"),
8422 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8423 // Error data is the HTLC value (100,000) and current block height
8424 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8426 // Send a payment with the right payment hash but the wrong payment secret
8427 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8428 handle_unknown_invalid_payment_data!();
8429 let events = nodes[0].node.get_and_clear_pending_events();
8430 expect_payment_failed!(nodes[0], events, our_payment_hash, true, expected_error_code, expected_error_data);
8432 // Send a payment with a random payment hash, but the right payment secret
8433 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8434 handle_unknown_invalid_payment_data!();
8435 let events = nodes[0].node.get_and_clear_pending_events();
8436 expect_payment_failed!(nodes[0], events, random_payment_hash, true, expected_error_code, expected_error_data);
8438 // Send a payment with a random payment hash and random payment secret
8439 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8440 handle_unknown_invalid_payment_data!();
8441 let events = nodes[0].node.get_and_clear_pending_events();
8442 expect_payment_failed!(nodes[0], events, random_payment_hash, true, expected_error_code, expected_error_data);
8446 fn test_update_err_monitor_lockdown() {
8447 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8448 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8449 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8451 // This scenario may happen in a watchtower setup, where watchtower process a block height
8452 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8453 // commitment at same time.
8455 let chanmon_cfgs = create_chanmon_cfgs(2);
8456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8458 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8460 // Create some initial channel
8461 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8462 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8464 // Rebalance the network to generate htlc in the two directions
8465 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8467 // Route a HTLC from node 0 to node 1 (but don't settle)
8468 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8470 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8471 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8472 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8473 let persister = test_utils::TestPersister::new();
8475 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8476 let monitor = monitors.get(&outpoint).unwrap();
8477 let mut w = test_utils::TestVecWriter(Vec::new());
8478 monitor.write(&mut w).unwrap();
8479 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8480 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8481 assert!(new_monitor == *monitor);
8482 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);
8483 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8486 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8487 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8488 // transaction lock time requirements here.
8489 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8490 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8492 // Try to update ChannelMonitor
8493 assert!(nodes[1].node.claim_funds(preimage));
8494 check_added_monitors!(nodes[1], 1);
8495 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8496 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8497 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8498 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8499 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8500 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8501 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8502 } else { assert!(false); }
8503 } else { assert!(false); };
8504 // Our local monitor is in-sync and hasn't processed yet timeout
8505 check_added_monitors!(nodes[0], 1);
8506 let events = nodes[0].node.get_and_clear_pending_events();
8507 assert_eq!(events.len(), 1);
8511 fn test_concurrent_monitor_claim() {
8512 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8513 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8514 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8515 // state N+1 confirms. Alice claims output from state N+1.
8517 let chanmon_cfgs = create_chanmon_cfgs(2);
8518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8520 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8522 // Create some initial channel
8523 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8524 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8526 // Rebalance the network to generate htlc in the two directions
8527 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8529 // Route a HTLC from node 0 to node 1 (but don't settle)
8530 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8532 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8533 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8534 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8535 let persister = test_utils::TestPersister::new();
8536 let watchtower_alice = {
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 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8550 // transaction lock time requirements here.
8551 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8552 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8554 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8556 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8557 assert_eq!(txn.len(), 2);
8561 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8562 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8563 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8564 let persister = test_utils::TestPersister::new();
8565 let watchtower_bob = {
8566 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8567 let monitor = monitors.get(&outpoint).unwrap();
8568 let mut w = test_utils::TestVecWriter(Vec::new());
8569 monitor.write(&mut w).unwrap();
8570 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8571 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8572 assert!(new_monitor == *monitor);
8573 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);
8574 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8577 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8578 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8580 // Route another payment to generate another update with still previous HTLC pending
8581 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8583 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8584 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();
8585 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8587 check_added_monitors!(nodes[1], 1);
8589 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8590 assert_eq!(updates.update_add_htlcs.len(), 1);
8591 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8592 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8593 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8594 // Watchtower Alice should already have seen the block and reject the update
8595 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8596 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8597 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8598 } else { assert!(false); }
8599 } else { assert!(false); };
8600 // Our local monitor is in-sync and hasn't processed yet timeout
8601 check_added_monitors!(nodes[0], 1);
8603 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8604 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8605 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8607 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8610 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8611 assert_eq!(txn.len(), 2);
8612 bob_state_y = txn[0].clone();
8616 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8617 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8618 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);
8620 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8621 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8622 // the onchain detection of the HTLC output
8623 assert_eq!(htlc_txn.len(), 2);
8624 check_spends!(htlc_txn[0], bob_state_y);
8625 check_spends!(htlc_txn[1], bob_state_y);
8630 fn test_pre_lockin_no_chan_closed_update() {
8631 // Test that if a peer closes a channel in response to a funding_created message we don't
8632 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8635 // Doing so would imply a channel monitor update before the initial channel monitor
8636 // registration, violating our API guarantees.
8638 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8639 // then opening a second channel with the same funding output as the first (which is not
8640 // rejected because the first channel does not exist in the ChannelManager) and closing it
8641 // before receiving funding_signed.
8642 let chanmon_cfgs = create_chanmon_cfgs(2);
8643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8645 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8647 // Create an initial channel
8648 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8649 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8650 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8651 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8652 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8654 // Move the first channel through the funding flow...
8655 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8657 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8658 check_added_monitors!(nodes[0], 0);
8660 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8661 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8662 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8663 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8664 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() });
8668 fn test_htlc_no_detection() {
8669 // This test is a mutation to underscore the detection logic bug we had
8670 // before #653. HTLC value routed is above the remaining balance, thus
8671 // inverting HTLC and `to_remote` output. HTLC will come second and
8672 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8673 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8674 // outputs order detection for correct spending children filtring.
8676 let chanmon_cfgs = create_chanmon_cfgs(2);
8677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8681 // Create some initial channels
8682 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8684 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8685 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8686 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8687 assert_eq!(local_txn[0].input.len(), 1);
8688 assert_eq!(local_txn[0].output.len(), 3);
8689 check_spends!(local_txn[0], chan_1.3);
8691 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8692 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8693 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8694 // We deliberately connect the local tx twice as this should provoke a failure calling
8695 // this test before #653 fix.
8696 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);
8697 check_closed_broadcast!(nodes[0], true);
8698 check_added_monitors!(nodes[0], 1);
8699 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxBroadcasted);
8700 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8702 let htlc_timeout = {
8703 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8704 assert_eq!(node_txn[1].input.len(), 1);
8705 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8706 check_spends!(node_txn[1], local_txn[0]);
8710 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8711 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8712 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8713 let events = nodes[0].node.get_and_clear_pending_events();
8714 expect_payment_failed!(nodes[0], events, our_payment_hash, true);
8717 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8718 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8719 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8720 // Carol, Alice would be the upstream node, and Carol the downstream.)
8722 // Steps of the test:
8723 // 1) Alice sends a HTLC to Carol through Bob.
8724 // 2) Carol doesn't settle the HTLC.
8725 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8726 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8727 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8728 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8729 // 5) Carol release the preimage to Bob off-chain.
8730 // 6) Bob claims the offered output on the broadcasted commitment.
8731 let chanmon_cfgs = create_chanmon_cfgs(3);
8732 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8733 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8734 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8736 // Create some initial channels
8737 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8738 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8740 // Steps (1) and (2):
8741 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8742 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8744 // Check that Alice's commitment transaction now contains an output for this HTLC.
8745 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8746 check_spends!(alice_txn[0], chan_ab.3);
8747 assert_eq!(alice_txn[0].output.len(), 2);
8748 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8749 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8750 assert_eq!(alice_txn.len(), 2);
8752 // Steps (3) and (4):
8753 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8754 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8755 let mut force_closing_node = 0; // Alice force-closes
8756 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8757 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8758 check_closed_broadcast!(nodes[force_closing_node], true);
8759 check_added_monitors!(nodes[force_closing_node], 1);
8760 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8761 if go_onchain_before_fulfill {
8762 let txn_to_broadcast = match broadcast_alice {
8763 true => alice_txn.clone(),
8764 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8766 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8767 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8768 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8769 if broadcast_alice {
8770 check_closed_broadcast!(nodes[1], true);
8771 check_added_monitors!(nodes[1], 1);
8772 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
8774 assert_eq!(bob_txn.len(), 1);
8775 check_spends!(bob_txn[0], chan_ab.3);
8779 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8780 // process of removing the HTLC from their commitment transactions.
8781 assert!(nodes[2].node.claim_funds(payment_preimage));
8782 check_added_monitors!(nodes[2], 1);
8783 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8784 assert!(carol_updates.update_add_htlcs.is_empty());
8785 assert!(carol_updates.update_fail_htlcs.is_empty());
8786 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8787 assert!(carol_updates.update_fee.is_none());
8788 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8790 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8791 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8792 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8793 if !go_onchain_before_fulfill && broadcast_alice {
8794 let events = nodes[1].node.get_and_clear_pending_msg_events();
8795 assert_eq!(events.len(), 1);
8797 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8798 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8800 _ => panic!("Unexpected event"),
8803 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8804 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8805 // Carol<->Bob's updated commitment transaction info.
8806 check_added_monitors!(nodes[1], 2);
8808 let events = nodes[1].node.get_and_clear_pending_msg_events();
8809 assert_eq!(events.len(), 2);
8810 let bob_revocation = match events[0] {
8811 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8812 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8815 _ => panic!("Unexpected event"),
8817 let bob_updates = match events[1] {
8818 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8819 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8822 _ => panic!("Unexpected event"),
8825 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8826 check_added_monitors!(nodes[2], 1);
8827 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8828 check_added_monitors!(nodes[2], 1);
8830 let events = nodes[2].node.get_and_clear_pending_msg_events();
8831 assert_eq!(events.len(), 1);
8832 let carol_revocation = match events[0] {
8833 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8834 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8837 _ => panic!("Unexpected event"),
8839 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8840 check_added_monitors!(nodes[1], 1);
8842 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8843 // here's where we put said channel's commitment tx on-chain.
8844 let mut txn_to_broadcast = alice_txn.clone();
8845 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8846 if !go_onchain_before_fulfill {
8847 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8848 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8849 // If Bob was the one to force-close, he will have already passed these checks earlier.
8850 if broadcast_alice {
8851 check_closed_broadcast!(nodes[1], true);
8852 check_added_monitors!(nodes[1], 1);
8853 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
8855 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8856 if broadcast_alice {
8857 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8858 // new block being connected. The ChannelManager being notified triggers a monitor update,
8859 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8860 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8862 assert_eq!(bob_txn.len(), 3);
8863 check_spends!(bob_txn[1], chan_ab.3);
8865 assert_eq!(bob_txn.len(), 2);
8866 check_spends!(bob_txn[0], chan_ab.3);
8871 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8872 // broadcasted commitment transaction.
8874 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8875 if go_onchain_before_fulfill {
8876 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8877 assert_eq!(bob_txn.len(), 2);
8879 let script_weight = match broadcast_alice {
8880 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8881 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8883 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8884 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8885 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8886 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8887 if broadcast_alice && !go_onchain_before_fulfill {
8888 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8889 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8891 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8892 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8898 fn test_onchain_htlc_settlement_after_close() {
8899 do_test_onchain_htlc_settlement_after_close(true, true);
8900 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8901 do_test_onchain_htlc_settlement_after_close(true, false);
8902 do_test_onchain_htlc_settlement_after_close(false, false);
8906 fn test_duplicate_chan_id() {
8907 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8908 // already open we reject it and keep the old channel.
8910 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8911 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8912 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8913 // updating logic for the existing channel.
8914 let chanmon_cfgs = create_chanmon_cfgs(2);
8915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8917 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8919 // Create an initial channel
8920 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8921 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8922 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8923 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()));
8925 // Try to create a second channel with the same temporary_channel_id as the first and check
8926 // that it is rejected.
8927 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8929 let events = nodes[1].node.get_and_clear_pending_msg_events();
8930 assert_eq!(events.len(), 1);
8932 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8933 // Technically, at this point, nodes[1] would be justified in thinking both the
8934 // first (valid) and second (invalid) channels are closed, given they both have
8935 // the same non-temporary channel_id. However, currently we do not, so we just
8936 // move forward with it.
8937 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8938 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8940 _ => panic!("Unexpected event"),
8944 // Move the first channel through the funding flow...
8945 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8947 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8948 check_added_monitors!(nodes[0], 0);
8950 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8951 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8953 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8954 assert_eq!(added_monitors.len(), 1);
8955 assert_eq!(added_monitors[0].0, funding_output);
8956 added_monitors.clear();
8958 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8960 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8961 let channel_id = funding_outpoint.to_channel_id();
8963 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8966 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8967 // Technically this is allowed by the spec, but we don't support it and there's little reason
8968 // to. Still, it shouldn't cause any other issues.
8969 open_chan_msg.temporary_channel_id = channel_id;
8970 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8972 let events = nodes[1].node.get_and_clear_pending_msg_events();
8973 assert_eq!(events.len(), 1);
8975 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8976 // Technically, at this point, nodes[1] would be justified in thinking both
8977 // channels are closed, but currently we do not, so we just move forward with it.
8978 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8979 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8981 _ => panic!("Unexpected event"),
8985 // Now try to create a second channel which has a duplicate funding output.
8986 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8987 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8988 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8989 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()));
8990 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8992 let funding_created = {
8993 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8994 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8995 let logger = test_utils::TestLogger::new();
8996 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8998 check_added_monitors!(nodes[0], 0);
8999 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9000 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9001 // still needs to be cleared here.
9002 check_added_monitors!(nodes[1], 1);
9004 // ...still, nodes[1] will reject the duplicate channel.
9006 let events = nodes[1].node.get_and_clear_pending_msg_events();
9007 assert_eq!(events.len(), 1);
9009 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9010 // Technically, at this point, nodes[1] would be justified in thinking both
9011 // channels are closed, but currently we do not, so we just move forward with it.
9012 assert_eq!(msg.channel_id, channel_id);
9013 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9015 _ => panic!("Unexpected event"),
9019 // finally, finish creating the original channel and send a payment over it to make sure
9020 // everything is functional.
9021 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9023 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9024 assert_eq!(added_monitors.len(), 1);
9025 assert_eq!(added_monitors[0].0, funding_output);
9026 added_monitors.clear();
9029 let events_4 = nodes[0].node.get_and_clear_pending_events();
9030 assert_eq!(events_4.len(), 0);
9031 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9032 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9034 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9035 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9036 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9037 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9041 fn test_error_chans_closed() {
9042 // Test that we properly handle error messages, closing appropriate channels.
9044 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9045 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9046 // we can test various edge cases around it to ensure we don't regress.
9047 let chanmon_cfgs = create_chanmon_cfgs(3);
9048 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9049 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9050 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9052 // Create some initial channels
9053 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9054 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9055 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9057 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9058 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9059 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9061 // Closing a channel from a different peer has no effect
9062 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9063 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9065 // Closing one channel doesn't impact others
9066 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9067 check_added_monitors!(nodes[0], 1);
9068 check_closed_broadcast!(nodes[0], false);
9069 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9070 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9071 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9072 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);
9073 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);
9075 // A null channel ID should close all channels
9076 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9077 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9078 check_added_monitors!(nodes[0], 2);
9079 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9080 let events = nodes[0].node.get_and_clear_pending_msg_events();
9081 assert_eq!(events.len(), 2);
9083 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9084 assert_eq!(msg.contents.flags & 2, 2);
9086 _ => panic!("Unexpected event"),
9089 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9090 assert_eq!(msg.contents.flags & 2, 2);
9092 _ => panic!("Unexpected event"),
9094 // Note that at this point users of a standard PeerHandler will end up calling
9095 // peer_disconnected with no_connection_possible set to false, duplicating the
9096 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9097 // users with their own peer handling logic. We duplicate the call here, however.
9098 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9099 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9101 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9102 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9103 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9107 fn test_invalid_funding_tx() {
9108 // Test that we properly handle invalid funding transactions sent to us from a peer.
9110 // Previously, all other major lightning implementations had failed to properly sanitize
9111 // funding transactions from their counterparties, leading to a multi-implementation critical
9112 // security vulnerability (though we always sanitized properly, we've previously had
9113 // un-released crashes in the sanitization process).
9114 let chanmon_cfgs = create_chanmon_cfgs(2);
9115 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9116 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9117 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9119 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9120 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()));
9121 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()));
9123 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9124 for output in tx.output.iter_mut() {
9125 // Make the confirmed funding transaction have a bogus script_pubkey
9126 output.script_pubkey = bitcoin::Script::new();
9129 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9130 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()));
9131 check_added_monitors!(nodes[1], 1);
9133 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()));
9134 check_added_monitors!(nodes[0], 1);
9136 let events_1 = nodes[0].node.get_and_clear_pending_events();
9137 assert_eq!(events_1.len(), 0);
9139 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9140 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9141 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9143 confirm_transaction_at(&nodes[1], &tx, 1);
9144 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxBroadcasted);
9145 check_added_monitors!(nodes[1], 1);
9146 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9147 assert_eq!(events_2.len(), 1);
9148 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9149 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9150 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9151 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9152 } else { panic!(); }
9153 } else { panic!(); }
9154 assert_eq!(nodes[1].node.list_channels().len(), 0);
9157 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9158 // In the first version of the chain::Confirm interface, after a refactor was made to not
9159 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9160 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9161 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9162 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9163 // spending transaction until height N+1 (or greater). This was due to the way
9164 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9165 // spending transaction at the height the input transaction was confirmed at, not whether we
9166 // should broadcast a spending transaction at the current height.
9167 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9168 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9169 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9170 // until we learned about an additional block.
9172 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9173 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9174 let chanmon_cfgs = create_chanmon_cfgs(3);
9175 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9176 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9177 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9178 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9180 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9181 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9182 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9183 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9184 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9186 nodes[1].node.force_close_channel(&channel_id).unwrap();
9187 check_closed_broadcast!(nodes[1], true);
9188 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9189 check_added_monitors!(nodes[1], 1);
9190 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9191 assert_eq!(node_txn.len(), 1);
9193 let conf_height = nodes[1].best_block_info().1;
9194 if !test_height_before_timelock {
9195 connect_blocks(&nodes[1], 24 * 6);
9197 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9198 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9199 if test_height_before_timelock {
9200 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9201 // generate any events or broadcast any transactions
9202 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9203 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9205 // We should broadcast an HTLC transaction spending our funding transaction first
9206 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9207 assert_eq!(spending_txn.len(), 2);
9208 assert_eq!(spending_txn[0], node_txn[0]);
9209 check_spends!(spending_txn[1], node_txn[0]);
9210 // We should also generate a SpendableOutputs event with the to_self output (as its
9212 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9213 assert_eq!(descriptor_spend_txn.len(), 1);
9215 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9216 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9217 // additional block built on top of the current chain.
9218 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9219 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9220 expect_pending_htlcs_forwardable!(nodes[1]);
9221 check_added_monitors!(nodes[1], 1);
9223 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9224 assert!(updates.update_add_htlcs.is_empty());
9225 assert!(updates.update_fulfill_htlcs.is_empty());
9226 assert_eq!(updates.update_fail_htlcs.len(), 1);
9227 assert!(updates.update_fail_malformed_htlcs.is_empty());
9228 assert!(updates.update_fee.is_none());
9229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9230 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9231 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9236 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9237 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9238 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9242 fn test_keysend_payments_to_public_node() {
9243 let chanmon_cfgs = create_chanmon_cfgs(2);
9244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9246 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9248 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9249 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9250 let payer_pubkey = nodes[0].node.get_our_node_id();
9251 let payee_pubkey = nodes[1].node.get_our_node_id();
9252 let route = get_route(&payer_pubkey, network_graph, &payee_pubkey, None,
9253 None, &vec![], 10000, 40,
9254 nodes[0].logger).unwrap();
9256 let test_preimage = PaymentPreimage([42; 32]);
9257 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9258 check_added_monitors!(nodes[0], 1);
9259 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9260 assert_eq!(events.len(), 1);
9261 let event = events.pop().unwrap();
9262 let path = vec![&nodes[1]];
9263 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9264 claim_payment(&nodes[0], &path, test_preimage);
9268 fn test_keysend_payments_to_private_node() {
9269 let chanmon_cfgs = create_chanmon_cfgs(2);
9270 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9271 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9272 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9274 let payer_pubkey = nodes[0].node.get_our_node_id();
9275 let payee_pubkey = nodes[1].node.get_our_node_id();
9276 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9277 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9279 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9280 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9281 let first_hops = nodes[0].node.list_usable_channels();
9282 let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9283 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9284 nodes[0].logger).unwrap();
9286 let test_preimage = PaymentPreimage([42; 32]);
9287 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9288 check_added_monitors!(nodes[0], 1);
9289 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9290 assert_eq!(events.len(), 1);
9291 let event = events.pop().unwrap();
9292 let path = vec![&nodes[1]];
9293 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9294 claim_payment(&nodes[0], &path, test_preimage);
9297 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, at_forward: bool, on_holder_tx: bool) {
9298 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat` policy.
9300 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9301 // trimmed-to-dust HTLC outbound balance and this new payment as included on next counterparty
9302 // commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the update.
9303 // At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC inbound
9304 // and trimmed-to-dust HTLC outbound balance and this new received HTLC as included on next
9305 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail the update.
9306 // Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel might be
9307 // available again for HTLC processing once the dust bandwidth has cleared up.
9309 let chanmon_cfgs = create_chanmon_cfgs(2);
9310 let mut config = test_default_channel_config();
9311 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(config)]);
9314 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9316 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9317 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9318 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9319 open_channel.max_accepted_htlcs = 60;
9320 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9321 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9323 accept_channel.dust_limit_satoshis = 660;
9325 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9327 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9330 if let Some(mut chan) = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9331 chan.holder_dust_limit_satoshis = 660;
9335 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9336 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()));
9337 check_added_monitors!(nodes[1], 1);
9339 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()));
9340 check_added_monitors!(nodes[0], 1);
9342 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9343 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9344 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9347 if dust_outbound_balance {
9349 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 2_300_000);
9350 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9354 route_payment(&nodes[0], &[&nodes[1]], 2_300_000);
9358 if dust_outbound_balance {
9360 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 200_000); // + 177_000 msat of HTLC-success tx at 253 sats/kWU
9361 if let Err(_) = nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9365 route_payment(&nodes[0], &[&nodes[1]], 200_000); // + 167_000 msat of HTLC-timeout tx at 253 sats/kWU
9371 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { 2_300_000 } else { 200_000 });
9372 let mut config = UserConfig::default();
9374 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", 6_900_000, config.channel_options.max_dust_htlc_exposure_msat)));
9376 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", 5_200_000, config.channel_options.max_dust_htlc_exposure_msat)));
9379 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1 ], if on_holder_tx { 2_300_000 } else { 200_000 });
9380 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9381 check_added_monitors!(nodes[0], 1);
9382 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9383 assert_eq!(events.len(), 1);
9384 let payment_event = SendEvent::from_event(events.remove(0));
9385 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9387 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", 6_900_000, config.channel_options.max_dust_htlc_exposure_msat), 1);
9389 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", 5_200_000, config.channel_options.max_dust_htlc_exposure_msat), 1);
9393 let _ = nodes[1].node.get_and_clear_pending_msg_events();
9394 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9395 added_monitors.clear();
9399 fn test_max_dust_htlc_exposure() {
9400 do_test_max_dust_htlc_exposure(true, true, true);
9401 do_test_max_dust_htlc_exposure(false, true, true);
9402 do_test_max_dust_htlc_exposure(false, false, true);
9403 do_test_max_dust_htlc_exposure(false, false, false);
9404 do_test_max_dust_htlc_exposure(true, true, false);
9405 do_test_max_dust_htlc_exposure(true, false, false);
9406 do_test_max_dust_htlc_exposure(true, false, true);
9407 do_test_max_dust_htlc_exposure(false, true, false);